Salome HOME
Merge V9_dev branch into master
authorrnv <rnv@opencascade.com>
Thu, 14 Jun 2018 08:33:23 +0000 (11:33 +0300)
committerrnv <rnv@opencascade.com>
Thu, 14 Jun 2018 08:33:23 +0000 (11:33 +0300)
22 files changed:
1  2 
bin/launchConfigureParser.py
src/KERNEL_PY/salome_iapp.py
src/Launcher/Test/test_launcher.py
src/SALOMEDS/SALOMEDS.cxx
src/SALOMEDS/SALOMEDS_ChildIterator_i.cxx
src/SALOMEDS/SALOMEDS_GenericAttribute_i.cxx
src/SALOMEDS/SALOMEDS_SComponentIterator_i.cxx
src/SALOMEDS/SALOMEDS_SObject.cxx
src/SALOMEDS/SALOMEDS_SObject.hxx
src/SALOMEDS/SALOMEDS_SObject_i.cxx
src/SALOMEDS/SALOMEDS_SObject_i.hxx
src/SALOMEDS/SALOMEDS_Server.cxx
src/SALOMEDS/SALOMEDS_Study.cxx
src/SALOMEDS/SALOMEDS_StudyBuilder.cxx
src/SALOMEDS/SALOMEDS_StudyBuilder.hxx
src/SALOMEDS/SALOMEDS_StudyBuilder_i.cxx
src/SALOMEDS/SALOMEDS_StudyBuilder_i.hxx
src/SALOMEDS/SALOMEDS_Study_i.cxx
src/SALOMEDS/SALOMEDS_Study_i.hxx
src/SALOMEDS/SALOMEDS_UseCaseBuilder_i.cxx
src/SALOMEDS/SALOMEDS_UseCaseIterator_i.cxx
src/SALOMEDSClient/SALOMEDSClient_SObject.hxx

index bde0a996e935916307bd31aaf3dd69e944b0df1e,e32982a549365536fb2735b183a5c5ddd6ebf012..e52313342f939dcace0bed5fd27d97a3e7cef2c1
  # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
  #
  
- import os, glob, string, sys, re
+ import argparse
+ import glob
+ import os
+ import re
+ import sys
  import xml.sax
- import optparse
- import types
  
  from salome_utils import verbose, getPortNumber, getHomeDir
  
  # names of tags in XML configuration file
  doc_tag = "document"
  sec_tag = "section"
@@@ -108,8 -111,9 +111,9 @@@ def version()
          if root_dir and os.path.exists( version_file ):
              filename = version_file
          if filename:
-             str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
-             match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
+             with open(filename, "r") as f:
+                 v = f.readline() # v = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
+             match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', v )
              if match :
                  return match.group( 1 )
      except:
@@@ -213,7 -217,7 +217,7 @@@ def userFile(appname, cfgname)
          files += glob.glob(os.path.join(getHomeDir(), filetmpl2.format(appname)))
      pass
  
-     # ... loop through all files and find most appopriate file (with closest id)
+     # ... loop through all files and find most appropriate file (with closest id)
      appr_id   = -1
      appr_file = ""
      for f in files:
  def process_containers_params( standalone, embedded ):
      # 1. filter inappropriate containers names
      if standalone is not None:
-         standalone = filter( lambda x: x in standalone_choices, standalone )
+         standalone = [x for x in standalone if x in standalone_choices]
      if embedded is not None:
-         embedded   = filter( lambda x: x in embedded_choices,   embedded )
+         embedded   = [x for x in embedded if x in embedded_choices]
  
      # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
      # parameter --> i.e. 'standalone' parameter has higher priority
      if standalone is not None and embedded is not None:
-         embedded = filter( lambda x: x not in standalone, embedded )
+         embedded = [x for x in embedded if x not in standalone]
  
      # 3. return corrected parameters values
      return standalone, embedded
@@@ -264,7 -268,7 +268,7 @@@ section_to_skip = "
  class xml_parser:
      def __init__(self, fileName, _opts, _importHistory):
          #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
-         if verbose(): print "Configure parser: processing %s ..." % fileName
+         if verbose(): print("Configure parser: processing %s ..." % fileName)
          self.fileName = os.path.abspath(fileName)
          self.importHistory = _importHistory
          self.importHistory.append(self.fileName)
              self.opts[ embedded_nam ] = embedded
          pass
  
-     def boolValue( self, str ):
-         strloc = str
-         if isinstance(strloc, types.UnicodeType):
+     def boolValue( self, item):
+         strloc = item
+         if isinstance(strloc, str):
              strloc = strloc.encode().strip()
-         if isinstance(strloc, types.StringType):
-             strlow = strloc.lower()
-             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
+         if isinstance(strloc, bytes):
+             strlow = strloc.decode().lower()
+             if strlow in ("1", "yes", "y", "on", "true", "ok"):
                  return True
              elif strlow in ("0", "no", "n", "off", "false", "cancel"):
                  return False
          return strloc
          pass
  
-     def intValue( self, str ):
-         strloc = str
-         if isinstance(strloc, types.UnicodeType):
+     def intValue( self, item):
+         strloc = item
+         if isinstance(strloc, str):
              strloc = strloc.encode().strip()
-         if isinstance(strloc, types.StringType):
-             strlow = strloc.lower()
-             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
+         if isinstance(strloc, bytes):
+             strlow = strloc.decode().lower()
+             if strlow in ("1", "yes", "y", "on", "true", "ok"):
                  return 1
              elif strlow in ("0", "no", "n", "off", "false", "cancel"):
                  return 0
              else:
-                 return string.atoi(strloc)
+                 return int(strloc.decode())
          return strloc
          pass
  
-     def strValue( self, str ):
-         strloc = str
+     def strValue( self, item):
+         strloc = item
          try:
-             if isinstance(strloc, types.UnicodeType): strloc = strloc.encode().strip()
-             else: strloc = strloc.strip()
+             if isinstance( strloc, str):
+                 strloc = strloc.strip()
+             else:
+                 if isinstance( strloc, bytes):
+                     strloc = strloc.decode().strip()
          except:
              pass
          return strloc
              section_name = attrs.getValue( nam_att )
              if section_name in [lanch_nam, lang_nam]:
                  self.section = section_name # launch section
-             elif self.opts.has_key( modules_nam ) and \
+             elif modules_nam in self.opts and \
                   section_name in self.opts[ modules_nam ]:
                  self.section = section_name # <module> section
              else:
              if os.path.exists(absfname + ext) :
                  absfname += ext
                  if absfname in self.importHistory :
-                     if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
+                     if verbose(): print("Configure parser: Warning : file %s is already imported" % absfname)
                      return # already imported
                  break
              pass
          else:
-             if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
+             if verbose(): print("Configure parser: Error : file %s does not exist" % absfname)
              return
  
          # importing file
              # import file
              imp = xml_parser(absfname, opts, self.importHistory)
              # merge results
-             for key in imp.opts.keys():
-                 if not self.opts.has_key(key):
+             for key in imp.opts:
+                 if key not in self.opts:
                      self.opts[key] = imp.opts[key]
                      pass
                  pass
              pass
          except:
-             if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
+             if verbose(): print("Configure parser: Error : can not read configuration file %s" % absfname)
          pass
  
  
  # -----------------------------------------------------------------------------
  
- booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
-              '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
+ booleans = {'1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
+             '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False}
  
- boolean_choices = booleans.keys()
+ boolean_choices = list(booleans.keys())
  
- def check_embedded(option, opt, value, parser):
-     from optparse import OptionValueError
-     assert value is not None
-     if parser.values.embedded:
-         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
-     else:
-         embedded = []
-     if parser.values.standalone:
-         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
-     else:
-         standalone = []
-     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
-     for v in vals:
-         if v not in embedded_choices:
-             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
-         if v not in embedded:
-             embedded.append( v )
-             if v in standalone:
-                 del standalone[ standalone.index( v ) ]
-                 pass
-     parser.values.embedded = ",".join( embedded )
-     parser.values.standalone = ",".join( standalone )
-     pass
  
- def check_standalone(option, opt, value, parser):
-     from optparse import OptionValueError
-     assert value is not None
-     if parser.values.embedded:
-         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
-     else:
-         embedded = []
-     if parser.values.standalone:
-         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
-     else:
-         standalone = []
-     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
-     for v in vals:
-         if v not in standalone_choices:
-             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
-         if v not in standalone:
-             standalone.append( v )
-             if v in embedded:
-                 del embedded[ embedded.index( v ) ]
-                 pass
-     parser.values.embedded = ",".join( embedded )
-     parser.values.standalone = ",".join( standalone )
-     pass
+ class CheckEmbeddedAction(argparse.Action):
+     def __call__(self, parser, namespace, value, option_string=None):
+         assert value is not None
+         if namespace.embedded:
+             embedded = [a for a in re.split("[:;,]", namespace.embedded) if a.strip()]
+         else:
+             embedded = []
+         if namespace.standalone:
+             standalone = [a for a in re.split("[:;,]", namespace.standalone) if a.strip()]
+         else:
+             standalone = []
+         vals = [a for a in re.split("[:;,]", value) if a.strip()]
+         for v in vals:
+             if v not in embedded_choices:
+                 raise argparse.ArgumentError("option %s: invalid choice: %r (choose from %s)"
+                                              % (self.dest, v, ", ".join(map(repr, embedded_choices))))
+             if v not in embedded:
+                 embedded.append(v)
+                 if v in standalone:
+                     del standalone[standalone.index(v)]
+                     pass
+         namespace.embedded = ",".join(embedded)
+         namespace.standalone = ",".join(standalone)
+         pass
+ class CheckStandaloneAction(argparse.Action):
+     def __call__(self, parser, namespace, value, option_string=None):
+         assert value is not None
+         if namespace.embedded:
+             embedded = [a for a in re.split("[:;,]", namespace.embedded) if a.strip()]
+         else:
+             embedded = []
+         if namespace.standalone:
+             standalone = [a for a in re.split("[:;,]", namespace.standalone) if a.strip()]
+         else:
+             standalone = []
+         vals = [a for a in re.split("[:;,]", value) if a.strip()]
+         for v in vals:
+             if v not in standalone_choices:
+                 raise argparse.ArgumentError("option %s: invalid choice: %r (choose from %s)"
+                                              % (self.dest, v, ", ".join(map(repr, standalone_choices))))
+             if v not in standalone:
+                 standalone.append(v)
+                 if v in embedded:
+                     del embedded[embedded.index(v)]
+                     pass
+         namespace.embedded = ",".join(embedded)
+         namespace.standalone = ",".join(standalone)
  
- def store_boolean (option, opt, value, parser, *args):
-     if isinstance(value, types.StringType):
-         try:
-             value_conv = booleans[value.strip().lower()]
-             for attribute in args:
-                 setattr(parser.values, attribute, value_conv)
-         except KeyError:
-             raise optparse.OptionValueError(
-                 "option %s: invalid boolean value: %s (choose from %s)"
-                 % (opt, value, boolean_choices))
-     else:
-         for attribute in args:
-             setattr(parser.values, attribute, value)
  
- def CreateOptionParser (theAdditionalOptions=None, exeName=None):
-     if theAdditionalOptions is None:
-         theAdditionalOptions = []
+ class StoreBooleanAction(argparse.Action):
+     def __call__(self, parser, namespace, value, option_string=None):
+         if isinstance(value, bytes):
+             value = value.decode()
+         if isinstance(value, str):
+             try:
+                 value_conv = booleans[value.strip().lower()]
+                 setattr(namespace, self.dest, value_conv)
+             except KeyError:
+                 raise argparse.ArgumentError(
+                     "option %s: invalid boolean value: %s (choose from %s)"
+                     % (self.dest, value, boolean_choices))
+         else:
+             setattr(namespace, self.dest, value)
+ def CreateOptionParser(exeName=None):
+     if not exeName:
+         exeName = "%(prog)s"
+     a_usage = """%s [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
+ Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,...
+ """ % exeName
+     version_str = "Salome %s" % version()
+     pars = argparse.ArgumentParser(usage=a_usage)
+     # Version
+     pars.add_argument('-v', '--version', action='version', version=version_str)
      # GUI/Terminal. Default: GUI
      help_str = "Launch without GUI (in the terminal mode)."
-     o_t = optparse.Option("-t",
-                           "--terminal",
-                           action="store_false",
-                           dest="gui",
-                           help=help_str)
+     pars.add_argument("-t",
+                       "--terminal",
+                       action="store_false",
+                       dest="gui",
+                       help=help_str)
  
      help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
-     o_b = optparse.Option("-b",
-                           "--batch",
-                           action="store_true",
-                           dest="batch",
-                           help=help_str)
+     pars.add_argument("-b",
+                       "--batch",
+                       action="store_true",
+                       dest="batch",
+                       help=help_str)
  
      help_str = "Launch in GUI mode [default]."
-     o_g = optparse.Option("-g",
-                           "--gui",
-                           action="store_true",
-                           dest="gui",
-                           help=help_str)
+     pars.add_argument("-g",
+                       "--gui",
+                       action="store_true",
+                       dest="gui",
+                       help=help_str)
  
 -    # Show Desktop (inly in GUI mode). Default: True
 +    # Show Desktop (only in GUI mode). Default: True
      help_str  = "1 to activate GUI desktop [default], "
      help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
      help_str += "Ignored in the terminal mode."
-     o_d = optparse.Option("-d",
-                           "--show-desktop",
-                           metavar="<1/0>",
-                           #type="choice", choices=boolean_choices,
-                           type="string",
-                           action="callback", callback=store_boolean, callback_args=('desktop',),
-                           dest="desktop",
-                           help=help_str)
+     pars.add_argument("-d",
+                       "--show-desktop",
+                       metavar="<1/0>",
+                       action=StoreBooleanAction,
+                       dest="desktop",
+                       help=help_str)
      help_str  = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
      help_str += "The same as --show-desktop=0."
-     o_o = optparse.Option("-o",
-                           "--hide-desktop",
-                           action="store_false",
-                           dest="desktop",
-                           help=help_str)
+     pars.add_argument("-o",
+                       "--hide-desktop",
+                       action="store_false",
+                       dest="desktop",
+                       help=help_str)
  
      # Use logger or log-file. Default: nothing.
      help_str = "Redirect messages to the CORBA collector."
-     #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
-     o_l = optparse.Option("-l",
-                           "--logger",
-                           action="store_const", const="CORBA",
-                           dest="log_file",
-                           help=help_str)
+     pars.add_argument("-l",
+                       "--logger",
+                       action="store_const", const="CORBA",
+                       dest="log_file",
+                       help=help_str)
      help_str = "Redirect messages to the <log-file>"
-     o_f = optparse.Option("-f",
-                           "--log-file",
-                           metavar="<log-file>",
-                           type="string",
-                           action="store",
-                           dest="log_file",
-                           help=help_str)
+     pars.add_argument("-f",
+                       "--log-file",
+                       metavar="<log-file>",
+                       dest="log_file",
+                       help=help_str)
  
      # Configuration XML file. Default: see defaultUserFile() function
-     help_str  = "Parse application settings from the <file> "
+     help_str = "Parse application settings from the <file> "
      help_str += "instead of default %s" % defaultUserFile()
-     o_r = optparse.Option("-r",
-                           "--resources",
-                           metavar="<file>",
-                           type="string",
-                           action="store",
-                           dest="resources",
-                           help=help_str)
+     pars.add_argument("-r",
+                       "--resources",
+                       metavar="<file>",
+                       dest="resources",
+                       help=help_str)
  
      # Use own xterm for each server. Default: False.
      help_str = "Launch each SALOME server in own xterm console"
-     o_x = optparse.Option("-x",
-                           "--xterm",
-                           action="store_true",
-                           dest="xterm",
-                           help=help_str)
+     pars.add_argument("-x",
+                       "--xterm",
+                       action="store_true",
+                       dest="xterm",
+                       help=help_str)
  
      # Modules. Default: Like in configuration files.
      help_str  = "SALOME modules list (where <module1>, <module2> are the names "
      help_str += "of SALOME modules which should be available in the SALOME session)"
-     o_m = optparse.Option("-m",
-                           "--modules",
-                           metavar="<module1,module2,...>",
-                           type="string",
-                           action="append",
-                           dest="modules",
-                           help=help_str)
+     pars.add_argument("-m",
+                       "--modules",
+                       metavar="<module1,module2,...>",
+                       action="append",
+                       dest="modules",
+                       help=help_str)
  
      # Embedded servers. Default: Like in configuration files.
      help_str  = "CORBA servers to be launched in the Session embedded mode. "
      help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
      help_str += "[by default the value from the configuration files is used]"
-     o_e = optparse.Option("-e",
-                           "--embedded",
-                           metavar="<server1,server2,...>",
-                           type="string",
-                           action="callback",
-                           dest="embedded",
-                           callback=check_embedded,
-                           help=help_str)
+     pars.add_argument("-e",
+                       "--embedded",
+                       metavar="<server1,server2,...>",
+                       action=CheckEmbeddedAction,
+                       dest="embedded",
+                       help=help_str)
  
      # Standalone servers. Default: Like in configuration files.
      help_str  = "CORBA servers to be launched in the standalone mode (as separate processes). "
      help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
      help_str += "[by default the value from the configuration files is used]"
-     o_s = optparse.Option("-s",
-                           "--standalone",
-                           metavar="<server1,server2,...>",
-                           type="string",
-                           action="callback",
-                           dest="standalone",
-                           callback=check_standalone,
-                           help=help_str)
+     pars.add_argument("-s",
+                       "--standalone",
+                       metavar="<server1,server2,...>",
+                       action=CheckStandaloneAction,
+                       dest="standalone",
+                       help=help_str)
  
      # Kill with port. Default: False.
      help_str = "Kill SALOME with the current port"
-     o_p = optparse.Option("-p",
-                           "--portkill",
-                           action="store_true",
-                           dest="portkill",
-                           help=help_str)
+     pars.add_argument("-p",
+                       "--portkill",
+                       action="store_true",
+                       dest="portkill",
+                       help=help_str)
  
      # Kill all. Default: False.
      help_str = "Kill all running SALOME sessions"
-     o_k = optparse.Option("-k",
-                           "--killall",
-                           action="store_true",
-                           dest="killall",
-                           help=help_str)
+     pars.add_argument("-k",
+                       "--killall",
+                       action="store_true",
+                       dest="killall",
+                       help=help_str)
  
      # Additional python interpreters. Default: 0.
      help_str  = "The number of additional external python interpreters to run. "
      help_str += "Each additional python interpreter is run in separate "
      help_str += "xterm session with properly set SALOME environment"
-     o_i = optparse.Option("-i",
-                           "--interp",
-                           metavar="<N>",
-                           type="int",
-                           action="store",
-                           dest="interp",
-                           help=help_str)
+     pars.add_argument("-i",
+                       "--interp",
+                       metavar="<N>",
+                       type=int,
+                       dest="interp",
+                       help=help_str)
  
      # Splash. Default: True.
      help_str  = "1 to display splash screen [default], "
      help_str += "0 to disable splash screen. "
      help_str += "This option is ignored in the terminal mode. "
      help_str += "It is also ignored if --show-desktop=0 option is used."
-     o_z = optparse.Option("-z",
-                           "--splash",
-                           metavar="<1/0>",
-                           #type="choice", choices=boolean_choices,
-                           type="string",
-                           action="callback", callback=store_boolean, callback_args=('splash',),
-                           dest="splash",
-                           help=help_str)
+     pars.add_argument("-z",
+                       "--splash",
+                       metavar="<1/0>",
+                       action=StoreBooleanAction,
+                       dest="splash",
+                       help=help_str)
  
      # Catch exceptions. Default: True.
      help_str  = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
      help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
-     o_c = optparse.Option("-c",
-                           "--catch-exceptions",
-                           metavar="<1/0>",
-                           #type="choice", choices=boolean_choices,
-                           type="string",
-                           action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
-                           dest="catch_exceptions",
-                           help=help_str)
+     pars.add_argument("-c",
+                       "--catch-exceptions",
+                       metavar="<1/0>",
+                       action=StoreBooleanAction,
+                       dest="catch_exceptions",
+                       help=help_str)
  
      # Print free port and exit
      help_str = "Print free port and exit"
-     o_a = optparse.Option("--print-port",
-                           action="store_true",
-                           dest="print_port", default=False,
-                           help=help_str)
+     pars.add_argument("--print-port",
+                       action="store_true",
+                       dest="print_port",
+                       help=help_str)
  
      # Do not relink ${HOME}/.omniORB_last.cfg
      help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
-     o_n = optparse.Option("--nosave-config",
-                           action="store_false",
-                           dest="save_config", default=True,
-                           help=help_str)
+     pars.add_argument("--nosave-config",
+                       action="store_false",
+                       dest="save_config",
+                       help=help_str)
  
      # Launch with interactive python console. Default: False.
      help_str = "Launch with interactive python console."
-     o_pi = optparse.Option("--pinter",
-                           action="store_true",
-                           dest="pinter",
-                           help=help_str)
+     pars.add_argument("--pinter",
+                       action="store_true",
+                       dest="pinter",
+                       help=help_str)
  
      # Print Naming service port into a user file. Default: False.
      help_str = "Print Naming Service Port into a user file."
-     o_nspl = optparse.Option("--ns-port-log",
-                              metavar="<ns_port_log_file>",
-                              type="string",
-                              action="store",
-                              dest="ns_port_log_file",
-                              help=help_str)
+     pars.add_argument("--ns-port-log",
+                       metavar="<ns_port_log_file>",
+                       dest="ns_port_log_file",
+                       help=help_str)
  
      # Write/read test script file with help of TestRecorder. Default: False.
      help_str = "Write/read test script file with help of TestRecorder."
-     o_test = optparse.Option("--test",
-                              metavar="<test_script_file>",
-                              type="string",
-                              action="store",
-                              dest="test_script_file",
-                              help=help_str)
+     pars.add_argument("--test",
+                       metavar="<test_script_file>",
+                       dest="test_script_file",
+                       help=help_str)
  
      # Reproducing test script with help of TestRecorder. Default: False.
      help_str = "Reproducing test script with help of TestRecorder."
-     o_play = optparse.Option("--play",
-                              metavar="<play_script_file>",
-                              type="string",
-                              action="store",
-                              dest="play_script_file",
-                              help=help_str)
+     pars.add_argument("--play",
+                       metavar="<play_script_file>",
+                       dest="play_script_file",
+                       help=help_str)
  
      # gdb session
      help_str = "Launch session with gdb"
-     o_gdb = optparse.Option("--gdb-session",
-                             action="store_true",
-                             dest="gdb_session", default=False,
-                             help=help_str)
+     pars.add_argument("--gdb-session",
+                       action="store_true",
+                       dest="gdb_session",
+                       help=help_str)
  
      # ddd session
      help_str = "Launch session with ddd"
-     o_ddd = optparse.Option("--ddd-session",
-                             action="store_true",
-                             dest="ddd_session", default=False,
-                             help=help_str)
+     pars.add_argument("--ddd-session",
+                       action="store_true",
+                       dest="ddd_session",
+                       help=help_str)
  
  
      # valgrind session
      help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
-     o_valgrind = optparse.Option("--valgrind-session",
-                                  action="store_true",
-                                  dest="valgrind_session", default=False,
-                                  help=help_str)
+     pars.add_argument("--valgrind-session",
+                       action="store_true",
+                       dest="valgrind_session",
+                       help=help_str)
  
      # shutdown-servers. Default: False.
      help_str  = "1 to shutdown standalone servers when leaving python interpreter, "
      help_str += "0 to keep the standalone servers as daemon [default]. "
      help_str += "This option is only useful in batchmode "
      help_str += "(terminal mode or without showing desktop)."
-     o_shutdown = optparse.Option("-w",
-                                  "--shutdown-servers",
-                                  metavar="<1/0>",
-                                  #type="choice", choices=boolean_choices,
-                                  type="string",
-                                  action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
-                                  dest="shutdown_servers",
-                                  help=help_str)
+     pars.add_argument("-w",
+                       "--shutdown-servers",
+                       metavar="<1/0>",
+                       action=StoreBooleanAction,
+                       dest="shutdown_servers",
+                       help=help_str)
  
      # foreground. Default: True.
      help_str  = "0 and runSalome exits after have launched the gui, "
      help_str += "1 to launch runSalome in foreground mode [default]."
-     o_foreground = optparse.Option("--foreground",
-                                    metavar="<1/0>",
-                                    #type="choice", choices=boolean_choices,
-                                    type="string",
-                                    action="callback", callback=store_boolean, callback_args=('foreground',),
-                                    dest="foreground",
-                                    help=help_str)
+     pars.add_argument("--foreground",
+                       metavar="<1/0>",
+                       action=StoreBooleanAction,
+                       dest="foreground",
+                       help=help_str)
  
      # wake up session
      help_str  = "Wake up a previously closed session. "
      help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
      help_str += "If this variable is not set, the last configuration is taken. "
-     o_wake_up = optparse.Option("--wake-up-session",
-                                 action="store_true",
-                                 dest="wake_up_session", default=False,
-                                 help=help_str)
+     pars.add_argument("--wake-up-session",
+                       action="store_true",
+                       dest="wake_up_session", default=False,
+                       help=help_str)
  
      # server launch mode
      help_str = "Mode used to launch server processes (daemon or fork)."
-     o_slm = optparse.Option("--server-launch-mode",
-                             metavar="<server_launch_mode>",
-                             type="choice",
-                             choices=["daemon","fork"],
-                             action="store",
-                             dest="server_launch_mode",
-                             help=help_str)
+     pars.add_argument("--server-launch-mode",
+                       metavar="<server_launch_mode>",
+                       choices=["daemon", "fork"],
+                       dest="server_launch_mode",
+                       help=help_str)
  
      # use port
      help_str  = "Preferable port SALOME to be started on. "
      help_str += "If specified port is not busy, SALOME session will start on it; "
      help_str += "otherwise, any available port will be searched and used."
-     o_port = optparse.Option("--port",
-                              metavar="<port>",
-                              type="int",
-                                    action="store",
-                              dest="use_port",
-                                    help=help_str)
+     pars.add_argument("--port",
+                       metavar="<port>",
+                       type=int,
+                       dest="use_port",
+                       help=help_str)
  
+     # Language
      help_str  = "Force application language. By default, a language specified in "
      help_str += "the user's preferences is used."
-     o_lang = optparse.Option("-a",
-                              "--language",
-                              action="store",
-                              dest="language",
-                              help=help_str)
-     # All options
-     opt_list = [o_t,o_g, # GUI/Terminal
-                 o_d,o_o, # Desktop
-                 o_b,     # Batch
-                 o_l,o_f, # Use logger or log-file
-                 o_r,     # Configuration XML file
-                 o_x,     # xterm
-                 o_m,     # Modules
-                 o_e,     # Embedded servers
-                 o_s,     # Standalone servers
-                 o_p,     # Kill with port
-                 o_k,     # Kill all
-                 o_i,     # Additional python interpreters
-                 o_z,     # Splash
-                 o_c,     # Catch exceptions
-                 o_a,     # Print free port and exit
-                 o_n,     # --nosave-config
-                 o_pi,    # Interactive python console
-                 o_nspl,
-                 o_test,  # Write/read test script file with help of TestRecorder
-                 o_play,  # Reproducing test script with help of TestRecorder
-                 o_gdb,
-                 o_ddd,
-                 o_valgrind,
-                 o_shutdown,
-                 o_foreground,
-                 o_wake_up,
-                 o_slm,   # Server launch mode
-                 o_port,  # Use port
-                 o_lang,  # Language
-                 ]
-     #std_options = ["gui", "desktop", "log_file", "resources",
-     #               "xterm", "modules", "embedded", "standalone",
-     #               "portkill", "killall", "interp", "splash",
-     #               "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
-     opt_list += theAdditionalOptions
-     if not exeName:
-       exeName = "%prog"
+     pars.add_argument("-a",
+                       "--language",
+                       dest="language",
+                       help=help_str)
  
-     a_usage = """%s [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
- Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,...
- """%exeName
-     version_str = "Salome %s" % version()
-     pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
+     # Positional arguments (hdf file, python file)
+     pars.add_argument("arguments", nargs=argparse.REMAINDER)
  
      return pars
  
  args = {}
  #def get_env():
  #args = []
- def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname, exeName=None):
+ def get_env(appname=salomeappname, cfgname=salomecfgname, exeName=None):
      ###
      # Collect launch configuration files:
      # - The environment variable "<appname>Config" (SalomeAppConfig) which can
      #   specified in configuration file(s)
      ###
  
-     if theAdditionalOptions is None:
-         theAdditionalOptions = []
      global args
      config_var = appname+'Config'
  
      # check KERNEL_ROOT_DIR
      kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
      if kernel_root_dir is None:
-         print """
+         print("""
          For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
          KERNEL_ROOT_DIR is mandatory.
-         """
+         """)
          sys.exit(1)
  
      ############################
      # parse command line options
-     pars = CreateOptionParser(theAdditionalOptions, exeName=exeName)
-     (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
+     pars = CreateOptionParser(exeName=exeName)
+     cmd_opts = pars.parse_args(sys.argv[1:])
      ############################
  
      # Process --print-port option
      if cmd_opts.print_port:
          from searchFreePort import searchFreePort
          searchFreePort({})
-         print "port:%s"%(os.environ['NSPORT'])
+         print("port:%s"%(os.environ['NSPORT']))
  
          try:
              import PortManager
      gui_available = False
      if os.getenv("GUI_ROOT_DIR"):
          gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui')
-         if os.path.isdir( gui_resources_dir ):
+         if os.path.isdir(gui_resources_dir):
              gui_available = True
              dirs.append(gui_resources_dir)
          pass
      _opts = {} # associative array of options to be filled
  
      # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
-     for dir in dirs:
-         filename = os.path.join(dir, appname+'.xml')
+     for directory in dirs:
+         filename = os.path.join(directory, appname + '.xml')
          if not os.path.exists(filename):
-             if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
+             if verbose(): print("Configure parser: Warning : can not find configuration file %s" % filename)
          else:
              try:
                  p = xml_parser(filename, _opts, [])
                  _opts = p.opts
              except:
-                 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
+                 if verbose(): print("Configure parser: Error : can not read configuration file %s" % filename)
              pass
  
      # parse user configuration file
      user_config = cmd_opts.resources
      if not user_config:
          user_config = userFile(appname, cfgname)
-         if verbose(): print "Configure parser: user configuration file is", user_config
+         if verbose(): print("Configure parser: user configuration file is", user_config)
      if not user_config or not os.path.exists(user_config):
-         if verbose(): print "Configure parser: Warning : can not find user configuration file"
+         if verbose(): print("Configure parser: Warning : can not find user configuration file")
      else:
          try:
              p = xml_parser(user_config, _opts, [])
              _opts = p.opts
          except:
-             if verbose(): print 'Configure parser: Error : can not read user configuration file'
+             if verbose(): print('Configure parser: Error : can not read user configuration file')
              user_config = ""
  
      args = _opts
  
      args['user_config'] = user_config
-     #print "User Configuration file: ", args['user_config']
+     # print("User Configuration file: ", args['user_config'])
  
      # set default values for options which are NOT set in config files
      for aKey in listKeys:
-         if not args.has_key( aKey ):
+         if aKey not in args:
              args[aKey] = []
  
      for aKey in boolKeys:
-         if not args.has_key( aKey ):
+         if aKey not in args:
              args[aKey] = 0
  
      if args[file_nam]:
-         afile=args[file_nam]
+         afile = args[file_nam]
          args[file_nam] = [afile]
  
      args[appname_nam] = appname
  
      # Naming Service port log file
      if cmd_opts.ns_port_log_file is not None:
-       args["ns_port_log_file"] = cmd_opts.ns_port_log_file
+         args["ns_port_log_file"] = cmd_opts.ns_port_log_file
  
      # Study files
-     for arg in cmd_args:
-         if arg[-4:] == ".hdf" and not args["study_hdf"]:
+     for arg in cmd_opts.arguments:
+         file_extension = os.path.splitext(arg)[-1]
+         if file_extension == ".hdf" and not args["study_hdf"]:
              args["study_hdf"] = arg
  
      # Python scripts
      from salomeContextUtils import getScriptsAndArgs, ScriptAndArgs
-     args[script_nam] = getScriptsAndArgs(cmd_args)
+     args[script_nam] = getScriptsAndArgs(cmd_opts.arguments)
      if args[gui_nam] and args["session_gui"]:
          new_args = []
-         for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects
+         for sa_obj in args[script_nam]:  # args[script_nam] is a list of ScriptAndArgs objects
              script = re.sub(r'^python.*\s+', r'', sa_obj.script)
              new_args.append(ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out))
          #
          args[script_nam] = new_args
  
      # xterm
-     if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
+     if cmd_opts.xterm is not None:
+         args[xterm_nam] = cmd_opts.xterm
  
      # Modules
      if cmd_opts.modules is not None:
  
      # Embedded
      if cmd_opts.embedded is not None:
-         args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
+         args[embedded_nam] = [a for a in re.split( "[:;,]", cmd_opts.embedded ) if a.strip()]
  
      # Standalone
      if cmd_opts.standalone is not None:
-         args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
+         args[standalone_nam] = [a for a in re.split( "[:;,]", cmd_opts.standalone ) if a.strip()]
  
      # Normalize the '--standalone' and '--embedded' parameters
      standalone, embedded = process_containers_params( args.get( standalone_nam ),
      if cmd_opts.wake_up_session is not None:
          args[wake_up_session_nam] = cmd_opts.wake_up_session
  
-     ####################################################
-     # Add <theAdditionalOptions> values to args
-     for add_opt in theAdditionalOptions:
-         cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest)
-         exec(cmd)
-     ####################################################
      # disable signals handling
      if args[except_nam] == 1:
          os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
              elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ):
                  dirs.append( d2 )
          else:
-             #print "* '"+m+"' should be deleted from ",args[modules_nam]
+             # print("* '"+m+"' should be deleted from ",args[modules_nam])
              pass
  
      # Test
      if cmd_opts.use_port is not None:
          min_port = 2810
          max_port = min_port + 100
-         if cmd_opts.use_port not in xrange(min_port, max_port+1):
-             print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
+         if cmd_opts.use_port not in range(min_port, max_port+1):
+             print("Error: port number should be in range [%d, %d])" % (min_port, max_port))
              sys.exit(1)
          args[useport_nam] = cmd_opts.use_port
  
      if cmd_opts.language is not None:
          langs = args["language_languages"] if "language_languages" in args else []
          if cmd_opts.language not in langs:
-             print "Error: unsupported language: %s" % cmd_opts.language
+             print("Error: unsupported language: %s" % cmd_opts.language)
              sys.exit(1)
          args[lang_nam] = cmd_opts.language
  
      # return arguments
      os.environ[config_var] = os.pathsep.join(dirs)
-     #print "Args: ", args
+     # print("Args: ", args)
      return args
index 0946fe371740172c82294740ce4284677b91aa22,24deed4111d47b32031ea73a31bde64692d08dda..30ec345667ed950c89c7137b417f6b084c32d6de
@@@ -38,14 -38,14 +38,14 @@@ def ImportComponentGUI(ComponentName)
      if IN_SALOME_GUI:
          libName = "lib" + ComponentName + "_Swig"
          command = "from " + libName + " import *"
-         exec ( command )
+         exec (command, globals())
          constructor = ComponentName + "_Swig()"
          command = "gui = " + constructor
-         exec ( command )
-         return gui
+         exec (command, globals())
+         return gui  # @UndefinedVariable
      else:
-         print "Warning: ImportComponentGUI(",ComponentName,") outside GUI !"
-         print "calls to GUI methods may crash..."
+         print("Warning: ImportComponentGUI(",ComponentName,") outside GUI !")
+         print("calls to GUI methods may crash...")
          return salome_ComponentGUI
  
      #--------------------------------------------------------------------------
@@@ -71,90 -71,85 +71,85 @@@ class SalomeOutsideGUI(object)
      Provides a replacement for class SalomeGUI outside GUI process.
      Do almost nothing
      """
-     global myStudyId, myStudyName
+     global myStudyName
      
      def hasDesktop(self):
          """Indicate if GUI is running"""
          return False
      
-     def updateObjBrowser(self, bid):
+     def updateObjBrowser(self):
          """update the GUI object browser"""
-         print "SalomeOutsideGUI: no objectBrowser update outside GUI"
+         print("SalomeOutsideGUI: no objectBrowser update outside GUI")
          pass
      
-     def getActiveStudyId(self):
-         """Get the active study id"""
-         print "SalomeOutsideGUI.getActiveStudyId: avoid use outside GUI"
-         return myStudyId
-     
-     def getActiveStudyName(self):
-         """Get the active study name"""
-         print "SalomeOutsideGUI.getActiveStudyName: avoid use outside GUI"
+     def getStudyName(self):
+         """Get the study name"""
+         print("SalomeOutsideGUI.getStudyName: avoid use outside GUI")
          return myStudyName
      
      def SelectedCount(self):
          """Get the number of active selections"""
-         print "SalomeOutsideGUI: no selection mechanism available outside GUI"
+         print("SalomeOutsideGUI: no selection mechanism available outside GUI")
          return 0
      
      def getSelected(self, i):
          """Get the selection number i """
-         print "SalomeOutsideGUI: no selection mechanism available outside GUI"
+         print("SalomeOutsideGUI: no selection mechanism available outside GUI")
          return none
      
      def AddIObject(self, Entry):
          """Add an entry"""
-         print "SalomeOutsideGUI.AddIOObject: not available outside GUI"
+         print("SalomeOutsideGUI.AddIOObject: not available outside GUI")
          pass
      
      def RemoveIObject(self, Entry):
          """Remove an entry"""
-         print "SalomeOutsideGUI.REmoveIOObject: not available outside GUI"
+         print("SalomeOutsideGUI.REmoveIOObject: not available outside GUI")
          pass
      
      def ClearIObjects(self):
          """Clear entries"""
-         print "SalomeOutsideGUI.ClearIOObject: not available outside GUI"
+         print("SalomeOutsideGUI.ClearIOObject: not available outside GUI")
          pass
      
      def Display(self, Entry):
          """Display an entry"""
-         print "SalomeOutsideGUI.Display: not available outside GUI"
+         print("SalomeOutsideGUI.Display: not available outside GUI")
          pass
      
      def DisplayOnly(self, Entry):
          """Display only an entry"""
-         print "SalomeOutsideGUI.DisplayOnly: not available outside GUI"
+         print("SalomeOutsideGUI.DisplayOnly: not available outside GUI")
          pass
      
      def Erase(self, Entry):
          """Erase en entry"""
-         print "SalomeOutsideGUI.Erase: not available outside GUI"
+         print("SalomeOutsideGUI.Erase: not available outside GUI")
          pass
      
      def DisplayAll(self):
          """Display all"""
-         print "SalomeOutsideGUI.Erase: not available outside GUI"
+         print("SalomeOutsideGUI.Erase: not available outside GUI")
          pass
      
      def EraseAll(self):
          """Erase all"""
-         print "SalomeOutsideGUI.EraseAll: not available outside GUI"
+         print("SalomeOutsideGUI.EraseAll: not available outside GUI")
          pass
  
      def IsInCurrentView(self, Entry):
          """Indicate if an entry is in current view"""
-         print "SalomeOutsideGUI.IsIncurrentView: not available outside GUI"
 -        print("SalomeOutsideGUI.IsIncurentView: not available outside GUI")
++        print("SalomeOutsideGUI.IsIncurrentView: not available outside GUI")
          return False
          
      def getComponentName(self, ComponentUserName ):
          """Get component name from component user name"""
-         print "SalomeOutsideGUI.getComponentName: not available outside GUI"
+         print("SalomeOutsideGUI.getComponentName: not available outside GUI")
          return ""
     
      def getComponentUserName( self, ComponentName ):
          """Get component user name from component name"""
-         print "SalomeOutsideGUI.getComponentUserName: not available outside GUI"
+         print("SalomeOutsideGUI.getComponentUserName: not available outside GUI")
          return ""
          
      #--------------------------------------------------------------------------
index 5087d66998bfffe149172b6e6522321616554604,41c2d079a41bb99831b336e928cdb2bfe9f0a5fc..339e4c8751b67e843c8e78a79a4528f7775544b5
@@@ -58,16 -58,9 +58,16 @@@ class TestCompo(unittest.TestCase)
        text = f.read()
        f.close()
        self.assertEqual(text, content)
-     except IOError,ex:
+     except IOError as ex:
        self.fail("IO exception:" + str(ex));
  
 +  def create_JobParameters(self):
 +    job_params = salome.JobParameters()
 +    job_params.wckey="P11U5:CARBONES" #needed by edf clusters
 +    job_params.resource_required = salome.ResourceParameters()
 +    job_params.resource_required.nb_proc = 1
 +    return job_params
 +
    ##############################
    # test of python_salome job
    ##############################
@@@ -103,16 -96,18 +103,16 @@@ f.close(
      f.close()
  
      local_result_dir = os.path.join(case_test_dir, "result_py_job-")
 -    job_params = salome.JobParameters()
 +    job_params = self.create_JobParameters()
      job_params.job_type = "python_salome"
      job_params.job_file = job_script_file
      job_params.in_files = []
      job_params.out_files = ["result.txt", "subdir"]
 -    job_params.resource_required = salome.ResourceParameters()
 -    job_params.resource_required.nb_proc = 1
  
      launcher = salome.naming_service.Resolve('/SalomeLauncher')
  
      for resource in self.ressources:
-       print "Testing python_salome job on ", resource
+       print("Testing python_salome job on ", resource)
        job_params.result_directory = local_result_dir + resource
        job_params.job_name = "PyJob" + resource
        job_params.resource_required.name = resource
        launcher.launchJob(job_id)
  
        jobState = launcher.getJobState(job_id)
-       print "Job %d state: %s" % (job_id,jobState)
+       print("Job %d state: %s" % (job_id,jobState))
        while jobState != "FINISHED" and jobState != "FAILED" :
          time.sleep(5)
          jobState = launcher.getJobState(job_id)
-         print "Job %d state: %s" % (job_id,jobState)
+         print("Job %d state: %s" % (job_id,jobState))
          pass
  
        self.assertEqual(jobState, "FINISHED")
@@@ -199,20 -194,22 +199,20 @@@ f.close(
  
      # job params
      local_result_dir = os.path.join(case_test_dir, "result_com_job-")
 -    job_params = salome.JobParameters()
 +    job_params = self.create_JobParameters()
      job_params.job_type = "command"
      job_params.job_file = script_file
      job_params.env_file = env_file
      job_params.in_files = [data_file]
      job_params.out_files = ["result.txt", "copie"]
      job_params.local_directory = case_test_dir
 -    job_params.resource_required = salome.ResourceParameters()
 -    job_params.resource_required.nb_proc = 1
  
      # create and launch the job
      launcher = salome.naming_service.Resolve('/SalomeLauncher')
      resManager= salome.lcc.getResourcesManager()
  
      for resource in self.ressources:
-       print "Testing command job on ", resource
+       print("Testing command job on ", resource)
        job_params.result_directory = local_result_dir + resource
        job_params.job_name = "CommandJob_" + resource
        job_params.resource_required.name = resource
        launcher.launchJob(job_id)
        # wait for the end of the job
        jobState = launcher.getJobState(job_id)
-       print "Job %d state: %s" % (job_id,jobState)
+       print("Job %d state: %s" % (job_id,jobState))
        while jobState != "FINISHED" and jobState != "FAILED" :
          time.sleep(3)
          jobState = launcher.getJobState(job_id)
-         print "Job %d state: %s" % (job_id,jobState)
+         print("Job %d state: %s" % (job_id,jobState))
          pass
  
        # verify the results
      # job script
      script_text = """<?xml version='1.0' encoding='iso-8859-1' ?>
  <proc name="newSchema_1">
-    <property name="DefaultStudyID" value="1"/>
     <container name="DefaultContainer">
        <property name="container_kind" value="Salome"/>
        <property name="attached_on_cloning" value="0"/>
@@@ -302,7 -298,7 +301,7 @@@ f.close(
      f.close()
  
      local_result_dir = os.path.join(case_test_dir, "result_yacs_job-")
 -    job_params = salome.JobParameters()
 +    job_params = self.create_JobParameters()
      job_params.job_type = "yacs_file"
      job_params.job_file = job_script_file
      job_params.env_file = os.path.join(case_test_dir,env_file)
      # define the interval between two YACS schema dumps (3 seconds)
      import Engines
      job_params.specific_parameters = [Engines.Parameter("EnableDumpYACS", "3")]
 -    job_params.resource_required = salome.ResourceParameters()
 -    job_params.resource_required.nb_proc = 1
  
      launcher = salome.naming_service.Resolve('/SalomeLauncher')
      resManager= salome.lcc.getResourcesManager()
  
      for resource in self.ressources:
-       print "Testing yacs job on ", resource
+       print("Testing yacs job on ", resource)
        job_params.result_directory = local_result_dir + resource
        job_params.job_name = "YacsJob_" + resource
        job_params.resource_required.name = resource
        jobState = launcher.getJobState(job_id)
  
        yacs_dump_success = False
-       print "Job %d state: %s" % (job_id,jobState)
+       print("Job %d state: %s" % (job_id,jobState))
        while jobState != "FINISHED" and jobState != "FAILED" :
          time.sleep(5)
          jobState = launcher.getJobState(job_id)
  #        yacs_dump_success = launcher.getJobWorkFile(job_id, "dumpState_mySchema.xml",
          yacs_dump_success = launcher.getJobDumpState(job_id,
                                                job_params.result_directory)
-         print "Job %d state: %s - dump: %s" % (job_id,jobState, yacs_dump_success)
+         print("Job %d state: %s - dump: %s" % (job_id,jobState, yacs_dump_success))
          pass
  
        self.assertEqual(jobState, "FINISHED")
      # job script
      script_text = """<?xml version='1.0' encoding='iso-8859-1' ?>
  <proc name="myschema">
-    <property name="DefaultStudyID" value="1"/>
     <type name="string" kind="string"/>
     <type name="bool" kind="bool"/>
     <type name="double" kind="double"/>
@@@ -413,9 -410,10 +411,9 @@@ f.close(
      f.close()
  
      local_result_dir = os.path.join(case_test_dir, "result_yacsopt_job-")
 -    job_params = salome.JobParameters()
 +    job_params = self.create_JobParameters()
      job_params.job_type = "yacs_file"
      job_params.job_file = job_script_file
 -    #job_params.env_file = os.path.join(case_test_dir,env_file)
      job_params.out_files = ["result.txt"]
  
      # define the interval between two YACS schema dumps (3 seconds)
      job_params.specific_parameters = [Engines.Parameter("YACSDriverOptions",
                 "-imynode.i=5 -imynode.d=3.7 -imynode.b=False -imynode.s=lili")]
      expected_result="i=5,d=3.7,b=False,s=lili"
 -    job_params.resource_required = salome.ResourceParameters()
 -    job_params.resource_required.nb_proc = 1
  
      launcher = salome.naming_service.Resolve('/SalomeLauncher')
      resManager= salome.lcc.getResourcesManager()
  
      for resource in self.ressources:
-       print "Testing yacs job with options on ", resource
+       print("Testing yacs job with options on ", resource)
        job_params.result_directory = local_result_dir + resource
        job_params.job_name = "YacsJobOpt_" + resource
        job_params.resource_required.name = resource
        jobState = launcher.getJobState(job_id)
  
        yacs_dump_success = False
-       print "Job %d state: %s" % (job_id,jobState)
+       print("Job %d state: %s" % (job_id,jobState))
        while jobState != "FINISHED" and jobState != "FAILED" :
          time.sleep(5)
          jobState = launcher.getJobState(job_id)
-         print "Job %d state: %s " % (job_id,jobState)
+         print("Job %d state: %s " % (job_id,jobState))
          pass
  
        self.assertEqual(jobState, "FINISHED")
        self.verifyFile(os.path.join(job_params.result_directory, "result.txt"),
                        expected_result)
  
 +  ############################################
 +  # test of command job type with pre_command
 +  ############################################
 +  def test_command_pre(self):
 +    case_test_dir = os.path.join(TestCompo.test_dir, "command_pre")
 +    mkdir_p(case_test_dir)
 +
 +    # command to be run before the job
 +    pre_command = "pre_command.sh"
 +    pre_command_text = "echo 'it works!' > in.txt"
 +    abs_pre_command_file = os.path.join(case_test_dir, pre_command)
 +    f = open(abs_pre_command_file, "w")
 +    f.write(pre_command_text)
 +    f.close()
 +    os.chmod(abs_pre_command_file, 0o755)
 +    
 +    # job script
 +    script_file = "myTestScript.py"
 +    script_text = """#! /usr/bin/env python
 +# -*- coding: utf-8 -*-
 +
 +in_f = open("in.txt", "r")
 +in_text = in_f.read()
 +in_f.close()
 +
 +f = open('result.txt', 'w')
 +f.write(in_text)
 +f.close()
 +"""
 +    abs_script_file = os.path.join(case_test_dir, script_file)
 +    f = open(abs_script_file, "w")
 +    f.write(script_text)
 +    f.close()
 +    os.chmod(abs_script_file, 0o755)
 +
 +    # job params
 +    local_result_dir = os.path.join(case_test_dir, "result_com_pre_job-")
 +    job_params = self.create_JobParameters()
 +    job_params.job_type = "command"
 +    job_params.job_file = script_file
 +    job_params.pre_command = pre_command
 +    job_params.in_files = []
 +    job_params.out_files = ["result.txt"]
 +    job_params.local_directory = case_test_dir
 +
 +    # create and launch the job
 +    launcher = salome.naming_service.Resolve('/SalomeLauncher')
 +    resManager= salome.lcc.getResourcesManager()
 +
 +    for resource in self.ressources:
 +      print "Testing command job on ", resource
 +      job_params.result_directory = local_result_dir + resource
 +      job_params.job_name = "CommandPreJob_" + resource
 +      job_params.resource_required.name = resource
 +
 +      # use the working directory of the resource
 +      resParams = resManager.GetResourceDefinition(resource)
 +      wd = os.path.join(resParams.working_directory,
 +                        "CommandPreJob" + self.suffix)
 +      job_params.work_directory = wd
 +
 +      job_id = launcher.createJob(job_params)
 +      launcher.launchJob(job_id)
 +      # wait for the end of the job
 +      jobState = launcher.getJobState(job_id)
 +      print "Job %d state: %s" % (job_id,jobState)
 +      while jobState != "FINISHED" and jobState != "FAILED" :
 +        time.sleep(3)
 +        jobState = launcher.getJobState(job_id)
 +        print "Job %d state: %s" % (job_id,jobState)
 +        pass
 +
 +      # verify the results
 +      self.assertEqual(jobState, "FINISHED")
 +      launcher.getJobResults(job_id, "")
 +      self.verifyFile(os.path.join(job_params.result_directory, "result.txt"),
 +                      "it works!\n")
 +
 +  #################################
 +  # test of command salome job type
 +  #################################
 +  def test_command_salome(self):
 +    case_test_dir = os.path.join(TestCompo.test_dir, "command_salome")
 +    mkdir_p(case_test_dir)
 +
 +    # job script
 +    data_file = "in.txt"
 +    script_file = "myEnvScript.py"
 +    script_text = """#! /usr/bin/env python
 +# -*- coding: utf-8 -*-
 +
 +import os,sys
 +# verify import salome
 +import salome
 +
 +text_result = os.getenv("ENV_TEST_VAR","")
 +
 +f = open('result.txt', 'w')
 +f.write(text_result)
 +f.close()
 +
 +in_f = open("in.txt", "r")
 +in_text = in_f.read()
 +in_f.close()
 +
 +os.mkdir("copie")
 +f = open(os.path.join("copie",'copie.txt'), 'w')
 +f.write(in_text)
 +f.close()
 +"""
 +    abs_script_file = os.path.join(case_test_dir, script_file)
 +    f = open(abs_script_file, "w")
 +    f.write(script_text)
 +    f.close()
 +    os.chmod(abs_script_file, 0o755)
 +
 +    #environment script
 +    env_file = "myEnv.sh"
 +    env_text = """export ENV_TEST_VAR="expected"
 +"""
 +    f = open(os.path.join(case_test_dir, env_file), "w")
 +    f.write(env_text)
 +    f.close()
 +
 +    # write data file
 +    f = open(os.path.join(case_test_dir, data_file), "w")
 +    f.write("to be copied")
 +    f.close()
 +
 +    # job params
 +    local_result_dir = os.path.join(case_test_dir, "result_comsalome_job-")
 +    job_params = self.create_JobParameters()
 +    job_params.job_type = "command_salome"
 +    job_params.job_file = script_file
 +    job_params.env_file = env_file
 +    job_params.in_files = [data_file]
 +    job_params.out_files = ["result.txt", "copie"]
 +    job_params.local_directory = case_test_dir
 +
 +    # create and launch the job
 +    launcher = salome.naming_service.Resolve('/SalomeLauncher')
 +    resManager= salome.lcc.getResourcesManager()
 +
 +    for resource in self.ressources:
 +      print "Testing command salome job on ", resource
 +      job_params.result_directory = local_result_dir + resource
 +      job_params.job_name = "CommandSalomeJob_" + resource
 +      job_params.resource_required.name = resource
 +
 +      # use the working directory of the resource
 +      resParams = resManager.GetResourceDefinition(resource)
 +      wd = os.path.join(resParams.working_directory,
 +                        "CommandSalomeJob" + self.suffix)
 +      job_params.work_directory = wd
 +
 +      job_id = launcher.createJob(job_params)
 +      launcher.launchJob(job_id)
 +      # wait for the end of the job
 +      jobState = launcher.getJobState(job_id)
 +      print "Job %d state: %s" % (job_id,jobState)
 +      while jobState != "FINISHED" and jobState != "FAILED" :
 +        time.sleep(3)
 +        jobState = launcher.getJobState(job_id)
 +        print "Job %d state: %s" % (job_id,jobState)
 +        pass
 +
 +      # verify the results
 +      self.assertEqual(jobState, "FINISHED")
 +      launcher.getJobResults(job_id, "")
 +      self.verifyFile(os.path.join(job_params.result_directory, "result.txt"),
 +                      "expected")
 +      self.verifyFile(os.path.join(job_params.result_directory,
 +                                   "copie",'copie.txt'),
 +                      "to be copied")
 +
 +      # verify getJobWorkFile
 +      mydir = os.path.join(case_test_dir, "work_dir" + resource)
 +      success = launcher.getJobWorkFile(job_id, "result.txt", mydir)
 +      self.assertEqual(success, True)
 +      self.verifyFile(os.path.join(mydir, "result.txt"), "expected")
 +
 +      success = launcher.getJobWorkFile(job_id, "copie", mydir)
 +      self.assertEqual(success, True)
 +      self.verifyFile(os.path.join(mydir, "copie", "copie.txt"),
 +                      "to be copied")
 +      pass
 +    pass
 +  pass
 +
  if __name__ == '__main__':
      # create study
      import salome
index e6313314bd9e929a7f93bddd525fa207f244d6a4,2d86b26de6f34157141879e41fcbb2e5891d8db9..b6fdf918b64c9ace47c92c61d044749ab10a8fd9
  //  $Header$
  //
  #include "SALOMEDS.hxx"
- #include "SALOMEDS_StudyManager.hxx"
  #include "SALOMEDS_Study.hxx"
+ #include "SALOMEDS_Study_i.hxx"
  #include "SALOMEDS_StudyBuilder.hxx"
  #include "SALOMEDS_SObject.hxx"
  #include "SALOMEDS_SComponent.hxx"
  #include "SALOMEDSClient.hxx"
  #include "SALOMEDSClient_IParameters.hxx"
  #include "SALOMEDS_IParameters.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
- #include "utilities.h"
  
  #include "SALOMEDS_Defines.hxx"
  
++#include <utilities.h>
++
  // IDL headers
  #include <SALOMEconfig.h>
  #include CORBA_SERVER_HEADER(SALOMEDS)
@@@ -63,12 -61,10 +63,10 @@@ void SALOMEDS::lock(
  
  void SALOMEDS::unlock()
  {
-       SALOMEDS::Locker::MutexDS.unlock();
+   SALOMEDS::Locker::MutexDS.unlock();
  }
  
- // srn: Added new library methods that create basic SALOMEDS objects (StudyManager, Study, SComponent, SObject)
+ // srn: Added new library methods that create basic SALOMEDS objects (Study, SComponent, SObject)
  
  //=============================================================================
  /*!
  
  extern "C"
  {
- SALOMEDS_EXPORT
-   SALOMEDSClient_StudyManager* StudyManagerFactory()
- {
-   return new SALOMEDS_StudyManager();
- }
- SALOMEDS_EXPORT
+   SALOMEDS_EXPORT
    SALOMEDSClient_Study* StudyFactory(SALOMEDS::Study_ptr theStudy)
- {
-   if(CORBA::is_nil(theStudy)) return NULL;
-   return new SALOMEDS_Study(theStudy);
- }
  {
+     if(CORBA::is_nil(theStudy)) return NULL;
+     return new SALOMEDS_Study(theStudy);
  }
  
- SALOMEDS_EXPORT
  SALOMEDS_EXPORT
    SALOMEDSClient_SObject* SObjectFactory(SALOMEDS::SObject_ptr theSObject)
- {
-   if(CORBA::is_nil(theSObject)) return NULL;
-   return new SALOMEDS_SObject(theSObject);
- }
  {
+     if(CORBA::is_nil(theSObject)) return NULL;
+     return new SALOMEDS_SObject(theSObject);
  }
  
- SALOMEDS_EXPORT
  SALOMEDS_EXPORT
    SALOMEDSClient_SComponent* SComponentFactory(SALOMEDS::SComponent_ptr theSComponent)
- {
-   if(CORBA::is_nil(theSComponent)) return NULL;
-   return new SALOMEDS_SComponent(theSComponent);
- }
  {
+     if(CORBA::is_nil(theSComponent)) return NULL;
+     return new SALOMEDS_SComponent(theSComponent);
  }
  
- SALOMEDS_EXPORT
  SALOMEDS_EXPORT
    SALOMEDSClient_StudyBuilder* BuilderFactory(SALOMEDS::StudyBuilder_ptr theBuilder)
- {
-   if(CORBA::is_nil(theBuilder)) return NULL;
-   return new SALOMEDS_StudyBuilder(theBuilder);
- }
  {
+     if(CORBA::is_nil(theBuilder)) return NULL;
+     return new SALOMEDS_StudyBuilder(theBuilder);
  }
  
- SALOMEDS_EXPORT
-   SALOMEDSClient_StudyManager* CreateStudyManager(CORBA::ORB_ptr orb, PortableServer::POA_ptr root_poa)
- {
-   SALOME_NamingService namingService(orb);
-   CORBA::Object_var obj = namingService.Resolve( "/myStudyManager" );
-   SALOMEDS::StudyManager_var theManager = SALOMEDS::StudyManager::_narrow( obj );
-   if( CORBA::is_nil(theManager) )
+   SALOMEDS_EXPORT
+   void CreateStudy(CORBA::ORB_ptr orb, PortableServer::POA_ptr root_poa)
    {
-     PortableServer::POAManager_var pman = root_poa->the_POAManager();
-     CORBA::PolicyList policies;
-     policies.length(2);
-     //PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL));
-     PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL));
-     PortableServer::ImplicitActivationPolicy_var implicitPol(root_poa->create_implicit_activation_policy(PortableServer::IMPLICIT_ACTIVATION));
-     policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
-     policies[1] = PortableServer::ImplicitActivationPolicy::_duplicate(implicitPol);
-     PortableServer::POA_var poa = root_poa->create_POA("KERNELStudySingleThreadPOA",pman,policies);
-     MESSAGE("CreateStudyManager: KERNELStudySingleThreadPOA: "<< poa);
-     threadPol->destroy();
-     SALOMEDS_StudyManager_i * aStudyManager_i = new  SALOMEDS_StudyManager_i(orb, poa);
-     // Activate the objects.  This tells the POA that the objects are ready to accept requests.
-     PortableServer::ObjectId_var aStudyManager_iid =  poa->activate_object(aStudyManager_i);
-     //give ownership to the poa : the object will be deleted by the poa
-     aStudyManager_i->_remove_ref();
-     aStudyManager_i->register_name((char*)"/myStudyManager");
+     SALOME_NamingService namingService(orb);
+     CORBA::Object_var obj = namingService.Resolve( "/Study" );
+     SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( obj );
+     if( CORBA::is_nil(aStudy) ) {
++      PortableServer::POAManager_var pman = root_poa->the_POAManager();
++      CORBA::PolicyList policies;
++      policies.length(2);
++      //PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL));
++      PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL));
++      PortableServer::ImplicitActivationPolicy_var implicitPol(root_poa->create_implicit_activation_policy(PortableServer::IMPLICIT_ACTIVATION));
++      policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
++      policies[1] = PortableServer::ImplicitActivationPolicy::_duplicate(implicitPol);
++      PortableServer::POA_var poa = root_poa->create_POA("KERNELStudySingleThreadPOA",pman,policies);
++      MESSAGE("CreateStudy: KERNELStudySingleThreadPOA: "<< poa);
++      threadPol->destroy();
++
++      SALOMEDS_Study_i::SetThePOA(poa);  
+       SALOMEDS_Study_i* aStudy_i = new SALOMEDS_Study_i(orb);
+       // Activate the objects.  This tells the POA that the objects are ready to accept requests.
+       PortableServer::ObjectId_var aStudy_iid =  root_poa->activate_object(aStudy_i);
+       aStudy = aStudy_i->_this();
+       namingService.Register(aStudy, "/Study");
+       aStudy_i->GetImpl()->GetDocument()->SetModified(false);
+       aStudy_i->_remove_ref();
+     }
    }
-   return new SALOMEDS_StudyManager();
- }
  
- SALOMEDS_EXPORT
  SALOMEDS_EXPORT
    SALOMEDSClient_IParameters* GetIParameters(const _PTR(AttributeParameter)& ap)
- {
-   return new SALOMEDS_IParameters(ap);
- }
  {
+     return new SALOMEDS_IParameters(ap);
  }
  
- SALOMEDS_EXPORT
  SALOMEDS_EXPORT
    SALOMEDS::SObject_ptr ConvertSObject(const _PTR(SObject)& theSObject)
- {
-   
-   SALOMEDS_SObject* so = _CAST(SObject, theSObject);
-   if(!theSObject || !so) return SALOMEDS::SObject::_nil();
-   return so->GetSObject();
- }
- SALOMEDS_EXPORT
-   SALOMEDS::Study_ptr ConvertStudy(const _PTR(Study)& theStudy)
- {
-   SALOMEDS_Study* study = _CAST(Study, theStudy);
-   if(!theStudy || !study) return SALOMEDS::Study::_nil();
-   return study->GetStudy();
- }
+   {
+     SALOMEDS_SObject* so = _CAST(SObject, theSObject);
+     if ( !theSObject || !so )
+       return SALOMEDS::SObject::_nil();
+     return so->GetSObject();
+   }
  
- SALOMEDS_EXPORT
  SALOMEDS_EXPORT
    SALOMEDS::StudyBuilder_ptr ConvertBuilder(const _PTR(StudyBuilder)& theBuilder)
- {
-   SALOMEDS_StudyBuilder* builder = _CAST(StudyBuilder, theBuilder);
-   if(!theBuilder || !builder) return SALOMEDS::StudyBuilder::_nil(); 
-   return builder->GetBuilder();
- }
+   {
+     SALOMEDS_StudyBuilder* builder = _CAST(StudyBuilder, theBuilder);
+     if ( !theBuilder || !builder )
+       return SALOMEDS::StudyBuilder::_nil();
+     return builder->GetBuilder();
+   }
  }
index 3a17656b00adfa1ffbe79ec56220d744c9b7d83b,e5c3ad9e1cfd6a876d7e323d9ae777ee50eb3d78..574cf45b04ee7caef4bec4116c0786d43517cbb3
@@@ -25,7 -25,6 +25,7 @@@
  //  Module : SALOME
  //
  #include "SALOMEDS_ChildIterator_i.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
++#include "SALOMEDS_Study_i.hxx"
  #include "SALOMEDS_SObject_i.hxx"
  #include "SALOMEDS.hxx"
  #include "SALOMEDSImpl_SObject.hxx"
@@@ -38,9 -37,8 +38,9 @@@
   */
  //============================================================================
  SALOMEDS_ChildIterator_i::SALOMEDS_ChildIterator_i(const SALOMEDSImpl_ChildIterator& theImpl,
 -                                                   CORBA::ORB_ptr orb) 
 -  : _it(theImpl.GetPersistentCopy())
 +                                                   CORBA::ORB_ptr orb)  :
-   GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA()),
++  GenericObj_i(SALOMEDS_Study_i::GetThePOA()),
 +  _it(theImpl.GetPersistentCopy())
  {
    SALOMEDS::Locker lock;
    _orb = CORBA::ORB::_duplicate(orb);
@@@ -56,23 -54,6 +56,23 @@@ SALOMEDS_ChildIterator_i::~SALOMEDS_Chi
      if(_it) delete _it;
  }
  
-   myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_ChildIterator_i::_default_POA()
 +{
++  myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
 +  //MESSAGE("SALOMEDS_ChildIterator_i::_default_POA: " << myPOA);
 +  return PortableServer::POA::_duplicate(myPOA);
 +}
 +
  //============================================================================
  /*! Function :Init
   * 
index 114c0a228986085e1c2988a4492d3f969219acfb,5b98df2db2e2ccf0f12c8a3a95db8ca5577eb3c6..7014f54c8c3f8f27d9f867eee6bdfc6095959be8
@@@ -26,7 -26,6 +26,7 @@@
  //
  #include "utilities.h"
  #include "SALOMEDS_GenericAttribute_i.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
++#include "SALOMEDS_Study_i.hxx"
  #include "SALOMEDS_Attributes.hxx"
  #include "SALOMEDS.hxx"
  #include "SALOMEDSImpl_SObject.hxx"
@@@ -44,8 -43,7 +44,8 @@@
  
  UNEXPECT_CATCH(GALockProtection, SALOMEDS::GenericAttribute::LockProtection);
  
 -SALOMEDS_GenericAttribute_i::SALOMEDS_GenericAttribute_i(DF_Attribute* theImpl, CORBA::ORB_ptr theOrb)
 +SALOMEDS_GenericAttribute_i::SALOMEDS_GenericAttribute_i(DF_Attribute* theImpl, CORBA::ORB_ptr theOrb) :
-   GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
++  GenericObj_i(SALOMEDS_Study_i::GetThePOA())
  {
    _orb = CORBA::ORB::_duplicate(theOrb);
    _impl = theImpl;
@@@ -55,23 -53,6 +55,23 @@@ SALOMEDS_GenericAttribute_i::~SALOMEDS_
  {
  }
  
-   myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_GenericAttribute_i::_default_POA()
 +{
++  myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
 +  //MESSAGE("SALOMEDS_GenericAttribute_i::_default_POA: " << myPOA);
 +  return PortableServer::POA::_duplicate(myPOA);
 +}
 +
  void SALOMEDS_GenericAttribute_i::CheckLocked() throw (SALOMEDS::GenericAttribute::LockProtection) 
  {
    SALOMEDS::Locker lock;
index 07b24a93cd3d2970de5914d5391e05a113ec445e,cc7d6700fda508498f90395d78f7f59796d68637..35b3b34fb62b664cd264b9417976ef49eb397d94
@@@ -27,8 -27,6 +27,8 @@@
  #include "SALOMEDS_SComponentIterator_i.hxx"
  #include "SALOMEDS.hxx"
  #include "SALOMEDSImpl_SComponent.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
++#include "SALOMEDS_Study_i.hxx"
 +#include "utilities.h"
  
  //============================================================================
  /*! Function : constructor
@@@ -37,8 -35,7 +37,8 @@@
  //============================================================================
  
  SALOMEDS_SComponentIterator_i::SALOMEDS_SComponentIterator_i(const SALOMEDSImpl_SComponentIterator& theImpl, 
 -                                                             CORBA::ORB_ptr orb) 
 +                                                             CORBA::ORB_ptr orb)  :
-   GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
++  GenericObj_i(SALOMEDS_Study_i::GetThePOA())
  {
    _orb = CORBA::ORB::_duplicate(orb);
    _impl = theImpl.GetPersistentCopy();
@@@ -54,23 -51,6 +54,23 @@@ SALOMEDS_SComponentIterator_i::~SALOMED
     if(_impl) delete _impl;
  }
  
-   myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_SComponentIterator_i::_default_POA()
 +{
++  myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
 +  MESSAGE("SALOMEDS_SComponentIterator_i::_default_POA: " << myPOA);
 +  return PortableServer::POA::_duplicate(myPOA);
 +}
 +
  //============================================================================
  /*! Function : Init
   * 
index 88aa17af3f6147437e7bf5fa313bd04f6f4c468d,6f3332f6b6314f60949f669231ae157572a38bba..db9ab6fd93e4c5cfd68576ff90e266b4f488c85a
@@@ -196,16 -196,6 +196,6 @@@ bool SALOMEDS_SObject::FindSubObject(in
    return ret;   
  }
  
- _PTR(Study) SALOMEDS_SObject::GetStudy()
- {
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     return _PTR(Study)(new SALOMEDS_Study(_local_impl->GetStudy()));
-   }
-   SALOMEDS::Study_var study=_corba_impl->GetStudy();
-   return _PTR(Study)(new SALOMEDS_Study(study));
- }
  std::string SALOMEDS_SObject::Name()
  {
    std::string aName;
@@@ -299,15 -289,6 +289,15 @@@ int SALOMEDS_SObject::Tag(
    return _corba_impl->Tag(); 
  }
  
 +int SALOMEDS_SObject::GetLastChildTag()
 +{
 +  if (_isLocal) {
 +    SALOMEDS::Locker lock;
 +    return _local_impl->GetLastChildTag();
 +  }
 +  return _corba_impl->GetLastChildTag(); 
 +}
 +
  int SALOMEDS_SObject::Depth()
  {
    if (_isLocal) {
index 6b77e485c4cc925bd2c800254cde0c9c7c978068,da8bf79fd699d81506be3bb164f74169187649bc..51c3638184b8b53f70305830f372edb1720e0407
@@@ -60,16 -60,14 +60,15 @@@ public
    virtual bool FindAttribute(_PTR(GenericAttribute)& anAttribute, const std::string& aTypeOfAttribute);
    virtual bool ReferencedObject(_PTR(SObject)& theObject);
    virtual bool FindSubObject(int theTag, _PTR(SObject)& theObject);
-   virtual _PTR(Study) GetStudy();
    virtual std::string Name();
    virtual void  Name(const std::string& theName);
    virtual std::vector<_PTR(GenericAttribute)> GetAllAttributes();
    virtual std::string GetName();
    virtual std::string GetComment();
    virtual std::string GetIOR();
 -  virtual void SetAttrString(const std::string& name, const std::string& value);
 +  virtual void SetAttrString(const std::string& theName, const std::string& theValue);
    virtual int   Tag();
 +  virtual int   GetLastChildTag();
    virtual int   Depth();
  
    CORBA::Object_ptr GetObject();
index bfff08d5ed4907cf8ada7e6bc1109ba553e62031,2cf28a4cc388ef647e5fb7b153f065dd9d8fcaf6..36e8cbb4c71a8d232a1344436c6b1f52131d20a4
@@@ -26,9 -26,8 +26,9 @@@
  //
  #include "utilities.h"
  #include "SALOMEDS_SObject_i.hxx"
++#include "SALOMEDS_Study_i.hxx"
  #include "SALOMEDS_SComponent_i.hxx"
  #include "SALOMEDS_GenericAttribute_i.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
  #include "SALOMEDS.hxx"
  #include "SALOMEDSImpl_GenericAttribute.hxx"
  #include "SALOMEDSImpl_SComponent.hxx"
@@@ -58,8 -57,7 +58,8 @@@ SALOMEDS::SObject_ptr SALOMEDS_SObject_
   *  Purpose  :
   */
  //============================================================================
 -SALOMEDS_SObject_i::SALOMEDS_SObject_i(const SALOMEDSImpl_SObject& impl, CORBA::ORB_ptr orb)
 +SALOMEDS_SObject_i::SALOMEDS_SObject_i(const SALOMEDSImpl_SObject& impl, CORBA::ORB_ptr orb) :
-   GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
++  GenericObj_i(SALOMEDS_Study_i::GetThePOA())
  {
    _impl = 0;
    if(!impl.IsNull()) {
@@@ -72,7 -70,6 +72,6 @@@
       }
    }
    _orb = CORBA::ORB::_duplicate(orb);
-    //SALOME::GenericObj_i::myPOA = SALOMEDS_StudyManager_i::GetPOA(GetStudy());
  }
  
  
@@@ -86,23 -83,6 +85,23 @@@ SALOMEDS_SObject_i::~SALOMEDS_SObject_i
     if(_impl) delete _impl;    
  }
  
-   myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_SObject_i::_default_POA()
 +{
++  myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
 +  //MESSAGE("SALOMEDS_SObject_i::_default_POA: " << myPOA);
 +  return PortableServer::POA::_duplicate(myPOA);
 +}
 +
  //================================================================================
  /*!
   * \brief Returns true if the %SObject does not belong to any %Study
@@@ -150,27 -130,6 +149,6 @@@ SALOMEDS::SObject_ptr SALOMEDS_SObject_
    return so._retn();
  }
  
- //============================================================================
- /*! Function :
-  *  Purpose  :
-  */
- //============================================================================
- SALOMEDS::Study_ptr SALOMEDS_SObject_i::GetStudy()
- {
-   SALOMEDS::Locker lock;
-   SALOMEDSImpl_Study* aStudy = _impl->GetStudy();
-   if(!aStudy) {
-     MESSAGE("Problem GetStudy");
-     return SALOMEDS::Study::_nil();
-   }
-   std::string IOR = aStudy->GetTransientReference();
-   CORBA::Object_var obj = _orb->string_to_object(IOR.c_str());
-   SALOMEDS::Study_var Study = SALOMEDS::Study::_narrow(obj) ;
-   ASSERT(!CORBA::is_nil(Study));
-   return SALOMEDS::Study::_duplicate(Study);
- }
  //============================================================================
  /*! Function : FindAttribute
   *  Purpose  : Find attribute of given type on this SObject
index 5c0bdc652ea52e0c570e2a79d1cd8e580c5d5074,fea6ecab604db64433dc9a35d6530332c6c23848..a4c68741c3c740bfeefd07f3603ec35eba94bdc4
@@@ -53,8 -53,6 +53,8 @@@ public
    SALOMEDS_SObject_i(const SALOMEDSImpl_SObject&, CORBA::ORB_ptr);
    
    virtual ~SALOMEDS_SObject_i();
 +
 +  virtual PortableServer::POA_ptr _default_POA();
    
    virtual CORBA::Boolean IsNull();
    virtual char* GetID();
@@@ -64,7 -62,6 +64,6 @@@
    virtual CORBA::Boolean ReferencedObject(SALOMEDS::SObject_out obj) ;
    virtual CORBA::Boolean FindSubObject(CORBA::Long atag, SALOMEDS::SObject_out obj );
  
-   virtual SALOMEDS::Study_ptr    GetStudy() ;
    virtual char* Name();
    virtual void  Name(const char*);
    virtual SALOMEDS::ListOfAttributes* GetAllAttributes();
index 26cce9bb7a608e6b9b2acd7a40a815463372dcfe,5116addc31956781377d778459d2347df34db8bb..7de665e28032a1f50b01016edc4bb36a38feddce
@@@ -30,7 -30,7 +30,7 @@@
  #include "Utils_SINGLETON.hxx"
  
  #include "SALOME_NamingService.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
+ #include "SALOMEDS_Study_i.hxx"
  
  #include <SALOMEconfig.h>
  #include CORBA_SERVER_HEADER(SALOMEDS)
@@@ -58,7 -58,8 +58,8 @@@ int main(int argc, char** argv
        CORBA::ORB_var orb = CORBA::ORB_init( argc, argv, "omniORB4" ) ;
  #else
        CORBA::ORB_var orb = CORBA::ORB_init( argc, argv, "omniORB3" );
- #endif      
+ #endif
+       SALOME_NamingService* NS = 0;
        // Obtain a reference to the root POA.
        long TIMESleep = 500000000;
        int NumberOfTries = 40;
@@@ -70,7 -71,6 +71,7 @@@
        ts_rem.tv_nsec=0;
        ts_rem.tv_sec=0;
        CosNaming::NamingContext_var inc;
 +      PortableServer::POA_var defaultPoa;
        PortableServer::POA_var poa;
        CORBA::Object_var theObj;
        CORBA::Object_var obj;
              { 
                obj = orb->resolve_initial_references("RootPOA");
                if(!CORBA::is_nil(obj))
 -                poa = PortableServer::POA::_narrow(obj);
 -              if(!CORBA::is_nil(poa))
 -                pman = poa->the_POAManager();
 +                defaultPoa = PortableServer::POA::_narrow(obj);
 +              if(!CORBA::is_nil(defaultPoa))
 +                pman = defaultPoa->the_POAManager();
 +
 +              PortableServer::POAManager_var pman = defaultPoa->the_POAManager();
 +              CORBA::PolicyList policies;
 +              policies.length(2);
 +              //PortableServer::ThreadPolicy_var threadPol(defaultPoa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL));
 +              PortableServer::ThreadPolicy_var threadPol(defaultPoa->create_thread_policy(PortableServer::ORB_CTRL_MODEL)); // default for all POAs
 +              PortableServer::ImplicitActivationPolicy_var implicitPol(defaultPoa->create_implicit_activation_policy(PortableServer::IMPLICIT_ACTIVATION)); // default for Root_POA, NO for others
 +              policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
 +              policies[1] = PortableServer::ImplicitActivationPolicy::_duplicate(implicitPol);
 +              poa = defaultPoa->create_POA("KERNELStandaloneStudySingleThreadPOA",pman,policies);
 +              threadPol->destroy();
 +
                if(!CORBA::is_nil(orb)) 
                  theObj = orb->resolve_initial_references("NameService"); 
                if (!CORBA::is_nil(theObj)){
                      if(EnvL==1)
                        {
                          CORBA::ORB_var orb1 = CORBA::ORB_init(argc,argv) ;
-                         SALOME_NamingService &NS = *SINGLETON_<SALOME_NamingService>::Instance() ;
-                         NS.init_orb( orb1 ) ;
+                         NS = SINGLETON_<SALOME_NamingService>::Instance() ;
+                         NS->init_orb( orb1 ) ;
                          for(int j=1; j<=NumberOfTries; j++)
                            {
                              if (j!=1) 
        // We allocate the objects on the heap.  Since these are reference
        // counted objects, they will be deleted by the POA when they are no
        // longer needed.    
-       SALOMEDS_StudyManager_i * myStudyManager_i = new  SALOMEDS_StudyManager_i(orb,poa);
+       SALOMEDS_Study_i * myStudy_i = new  SALOMEDS_Study_i(orb);
   
        // Activate the objects.  This tells the POA that the objects are
        // ready to accept requests.
-       PortableServer::ObjectId_var myStudyManager_iid = poa->activate_object(myStudyManager_i);
-       myStudyManager_i->register_name("/myStudyManager");
-       myStudyManager_i->_remove_ref();
+       PortableServer::ObjectId_var myStudy_iid = poa->activate_object(myStudy_i);
+       SALOMEDS::Study_var Study = myStudy_i->_this();
+       if (!NS)
+       {
+         NS = SINGLETON_<SALOME_NamingService>::Instance();
+         NS->init_orb( orb );
+       }
+       NS->Register(Study, "/Study");
+       myStudy_i->_remove_ref();
         
        // Obtain a POAManager, and tell the POA to start accepting
        // requests on its objects.
index 50d658b7d969fc876e8513f8d1832d2acfff069b,86629e27142cfb4d9cb0a410b318bbf2327ff5ff..f7ea3dc15b94d6e510a04c9e7d423f2b2125fd63
@@@ -48,6 -48,8 +48,8 @@@
  #include "SALOMEDSImpl_GenericVariable.hxx"
  #include "SALOMEDSImpl_UseCaseBuilder.hxx"
  
+ #include <SALOME_KernelServices.hxx>
  #include "SALOMEDS_Driver_i.hxx"
  #include "SALOMEDS_Study_i.hxx"
  
@@@ -68,10 -70,7 +70,10 @@@ SALOMEDS_Study::SALOMEDS_Study(SALOMEDS
    _isLocal = true;
    _local_impl = theStudy;
    _corba_impl = SALOMEDS::Study::_nil();
-   init_orb();
 +
 +  pthread_mutex_init( &SALOMEDS_StudyBuilder::_remoteBuilderMutex, 0 );
 +
+   InitORB();
  }
  
  SALOMEDS_Study::SALOMEDS_Study(SALOMEDS::Study_ptr theStudy)
@@@ -82,8 -81,6 +84,8 @@@
    long pid =  (long)getpid();
  #endif  
  
 +  pthread_mutex_init( &SALOMEDS_StudyBuilder::_remoteBuilderMutex, 0 );
 +
    long addr = theStudy->GetLocalImpl(Kernel_Utils::GetHostname().c_str(), pid, _isLocal);
    if(_isLocal) {
      _local_impl = reinterpret_cast<SALOMEDSImpl_Study*>(addr);
      _corba_impl = SALOMEDS::Study::_duplicate(theStudy);
    }
  
-   init_orb();
+   InitORB();
  }
  
  SALOMEDS_Study::~SALOMEDS_Study()
  {
  }
  
std::string SALOMEDS_Study::GetPersistentReference()
void SALOMEDS_Study::InitORB()
  {
-   std::string aRef;
+   ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
+   ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting());
+   _orb = init(0 , 0 ) ;
+ }
+ void SALOMEDS_Study::Init()
+ {
+   if(CORBA::is_nil(_corba_impl))
+     return;
+   _corba_impl->Init();
+ }
+ void SALOMEDS_Study::Clear()
+ {
+   if(CORBA::is_nil(_corba_impl))
+     return;
+   _corba_impl->Clear();
+ }
+ bool SALOMEDS_Study::Open(const std::string& theStudyUrl)
+ {
+   if(CORBA::is_nil(_corba_impl))
+     return false;
+   std::wstring wtheStudyUrl = std::wstring(theStudyUrl.begin(), theStudyUrl.end());
+   
+   if (!_corba_impl->Open( (wchar_t*)wtheStudyUrl.c_str() ) )
+     return false;
+   return true;
+ }
+ bool SALOMEDS_Study::Save(bool theMultiFile, bool theASCII)
+ {
+   if(CORBA::is_nil(_corba_impl))
+     return false;
+   return _corba_impl->Save(theMultiFile, theASCII);
+ }
+ bool SALOMEDS_Study::SaveAs(const std::string& theUrl, bool theMultiFile, bool theASCII)
+ {
+   if(CORBA::is_nil(_corba_impl))
+     return false;
+   return _corba_impl->SaveAs(Kernel_Utils::decode_s(theUrl), theMultiFile, theASCII);
+ }
+ SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb)
+ {
+   SALOMEDS_Driver_i* driver = NULL;
+   SALOMEDSImpl_SComponent aSCO = theObject.GetFatherComponent();
+   if(!aSCO.IsNull()) {
+     std::string IOREngine = aSCO.GetIOR();
+     if(!IOREngine.empty()) {
+       CORBA::Object_var obj = orb->string_to_object(IOREngine.c_str());
+       Engines::EngineComponent_var Engine = Engines::EngineComponent::_narrow(obj) ;
+       driver = new SALOMEDS_Driver_i(Engine, orb);
+     }
+   }
+   return driver;
+ }
+ bool SALOMEDS_Study::CanCopy(const _PTR(SObject)& theSO)
+ {
+   SALOMEDS_SObject* aSO = dynamic_cast<SALOMEDS_SObject*>(theSO.get());
+   bool ret;
    if (_isLocal) {
      SALOMEDS::Locker lock;
-     aRef = _local_impl->GetPersistentReference();
+     SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+     SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+     ret = _local_impl->CanCopy(aSO_impl, aDriver);
+     delete aDriver;
    }
-   else aRef = (CORBA::String_var)_corba_impl->GetPersistentReference();
-   return aRef;
+   else {
+     ret = _corba_impl->CanCopy(aSO->GetCORBAImpl());
+   }
+   return ret;
+ }
+ bool SALOMEDS_Study::Copy(const _PTR(SObject)& theSO)
+ {
+   SALOMEDS_SObject* aSO = dynamic_cast<SALOMEDS_SObject*>(theSO.get());
+   bool ret;
+   if (_isLocal) {
+     SALOMEDS::Locker lock;
+     SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+     SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+     ret = _local_impl->Copy(aSO_impl, aDriver);
+     delete aDriver;
+   }
+   else {
+     ret = _corba_impl->Copy(aSO->GetCORBAImpl());
+   }
+   return ret;
+ }
+ bool SALOMEDS_Study::CanPaste(const _PTR(SObject)& theSO)
+ {
+   SALOMEDS_SObject* aSO = dynamic_cast<SALOMEDS_SObject*>(theSO.get());
+   bool ret;
+   if (_isLocal) {
+     SALOMEDS::Locker lock;
+     SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+     SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+     ret = _local_impl->CanPaste(aSO_impl, aDriver);
+     delete aDriver;
+   }
+   else {
+     ret = _corba_impl->CanPaste(aSO->GetCORBAImpl());
+   }
+   return ret;
+ }
+ _PTR(SObject) SALOMEDS_Study::Paste(const _PTR(SObject)& theSO)
+ {
+   SALOMEDS_SObject* aSO = dynamic_cast<SALOMEDS_SObject*>(theSO.get());
+   SALOMEDSClient_SObject* aResult = NULL;
+   if (_isLocal) {
+     SALOMEDS::Locker lock;
+     SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+     SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+     SALOMEDSImpl_SObject aNewSO = _local_impl->Paste(aSO_impl, aDriver);
+     delete aDriver;
+     if(aNewSO.IsNull()) return _PTR(SObject)(aResult);
+     aResult = new SALOMEDS_SObject(aNewSO);
+   }
+   else {
+     SALOMEDS::SObject_ptr aNewSO = _corba_impl->Paste(aSO->GetCORBAImpl());
+     if(CORBA::is_nil(aNewSO)) return _PTR(SObject)(aResult);
+     aResult = new SALOMEDS_SObject(aNewSO);
+   }
+   return _PTR(SObject)(aResult);
  }
  
- std::string SALOMEDS_Study::GetTransientReference()
+ std::string SALOMEDS_Study::GetPersistentReference()
  {
    std::string aRef;
    if (_isLocal) {
      SALOMEDS::Locker lock;
-     aRef = _local_impl->GetTransientReference();
+     aRef = _local_impl->GetPersistentReference();
    }
-   else aRef = _corba_impl->GetTransientReference();
+   else aRef = (CORBA::String_var)_corba_impl->GetPersistentReference();
    return aRef;
  }
   
@@@ -304,91 -440,6 +445,6 @@@ std::string SALOMEDS_Study::GetObjectPa
    return aPath;
  }
  
- void SALOMEDS_Study::SetContext(const std::string& thePath)
- {
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     _local_impl->SetContext(thePath);
-   }
-   else _corba_impl->SetContext((char*)thePath.c_str());
- }
- std::string SALOMEDS_Study::GetContext()  
- {
-   std::string aPath;
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     aPath = _local_impl->GetContext();
-   }
-   else aPath = _corba_impl->GetContext();
-   return aPath;
- }
- std::vector<std::string> SALOMEDS_Study::GetObjectNames(const std::string& theContext)
- {
-   std::vector<std::string> aVector;
-   int aLength, i;
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     aVector = _local_impl->GetObjectNames(theContext);
-   }
-   else {
-     SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetObjectNames((char*)theContext.c_str());
-     aLength = aSeq->length();
-     for (i = 0; i < aLength; i++) aVector.push_back(std::string((std::string)aSeq[i].in()));
-   }
-   return aVector;
- }
-  
- std::vector<std::string> SALOMEDS_Study::GetDirectoryNames(const std::string& theContext)
- {
-   std::vector<std::string> aVector;
-   int aLength, i;
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     aVector = _local_impl->GetDirectoryNames(theContext);
-   }
-   else {
-     SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetDirectoryNames((char*)theContext.c_str());
-     aLength = aSeq->length();
-     for (i = 0; i < aLength; i++) aVector.push_back((char*)aSeq[i].in());
-   }
-   return aVector;
- }
-  
- std::vector<std::string> SALOMEDS_Study::GetFileNames(const std::string& theContext)
- {
-   std::vector<std::string> aVector;
-   int aLength, i;
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     aVector = _local_impl->GetFileNames(theContext);
-   }
-   else {
-     SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetFileNames((char*)theContext.c_str());
-     aLength = aSeq->length();
-     for (i = 0; i < aLength; i++) aVector.push_back((char*)aSeq[i].in());
-   }
-   return aVector;
- }
-  
- std::vector<std::string> SALOMEDS_Study::GetComponentNames(const std::string& theContext)
- {
-   std::vector<std::string> aVector;
-   int aLength, i;
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     aVector = _local_impl->GetComponentNames(theContext);
-   }
-   else {
-     SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetComponentNames((char*)theContext.c_str());
-     aLength = aSeq->length();
-     for (i = 0; i < aLength; i++) aVector.push_back((char*)aSeq[i].in());
-   }
-   return aVector;
- }
  _PTR(ChildIterator) SALOMEDS_Study::NewChildIterator(const _PTR(SObject)& theSO)
  {
    SALOMEDS_SObject* aSO = dynamic_cast<SALOMEDS_SObject*>(theSO.get());
@@@ -447,7 -498,7 +503,7 @@@ std::string SALOMEDS_Study::Name(
      SALOMEDS::Locker lock;
      aName = _local_impl->Name();
    }
-   else aName = _corba_impl->Name();
+   else aName = Kernel_Utils::encode_s(_corba_impl->Name());
    return aName;
  }
  
@@@ -457,7 -508,7 +513,7 @@@ void SALOMEDS_Study::Name(const std::st
      SALOMEDS::Locker lock;
      _local_impl->Name(theName);
    }
-   else _corba_impl->Name((char*)theName.c_str());
+   else _corba_impl->Name(Kernel_Utils::decode_s(theName));
  }
  
  bool SALOMEDS_Study::IsSaved()
@@@ -508,7 -559,8 +564,8 @@@ std::string SALOMEDS_Study::URL(
      SALOMEDS::Locker lock;
      aURL = _local_impl->URL();
    }
-   else aURL = _corba_impl->URL();
+   else 
+       aURL = Kernel_Utils::encode_s(_corba_impl->URL());
    return aURL;
  }
  
@@@ -518,27 -570,7 +575,7 @@@ void SALOMEDS_Study::URL(const std::str
      SALOMEDS::Locker lock;
      _local_impl->URL(url);
    }
-   else _corba_impl->URL((char*)url.c_str());
- }
- int SALOMEDS_Study::StudyId()
- {
-   int anID;
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     anID = _local_impl->StudyId();
-   }
-   else anID = _corba_impl->StudyId();
-   return anID;
- }
-  
- void SALOMEDS_Study::StudyId(int id) 
- {
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     _local_impl->StudyId(id);
-   }
-   else _corba_impl->StudyId(id);  
+   else _corba_impl->URL(Kernel_Utils::decode_s(url));
  }
  
  std::vector<_PTR(SObject)> SALOMEDS_Study::FindDependances(const _PTR(SObject)& theSO)
@@@ -619,15 -651,6 +656,6 @@@ _PTR(UseCaseBuilder) SALOMEDS_Study::Ge
    return _PTR(UseCaseBuilder)(aUB);
  }
  
- void SALOMEDS_Study::Close()
- {
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     _local_impl->Close();
-   }
-   else _corba_impl->Close();
- }
  void SALOMEDS_Study::EnableUseCaseAutoFilling(bool isEnabled)
  {
    if(_isLocal) _local_impl->EnableUseCaseAutoFilling(isEnabled);
@@@ -639,10 -662,10 +667,10 @@@ bool SALOMEDS_Study::DumpStudy(const st
                                 bool isPublished,
                                 bool isMultiFile)
  {
-   //SRN: Pure CORBA DumpStudy as it does more cleaning than the local one
-   if(CORBA::is_nil(_corba_impl)) GetStudy(); //If CORBA implementation is null then retrieve it
-   bool ret = _corba_impl->DumpStudy(thePath.c_str(), theBaseName.c_str(), isPublished, isMultiFile);
-   return ret;
+   if(CORBA::is_nil(_corba_impl))
+     return false;
+   return _corba_impl->DumpStudy(thePath.c_str(), theBaseName.c_str(), isPublished, isMultiFile);
  }     
  
  void SALOMEDS_Study::SetStudyLock(const std::string& theLockerID)
@@@ -943,40 -966,6 +971,6 @@@ CORBA::Object_ptr SALOMEDS_Study::Conve
    return _orb->string_to_object(theIOR.c_str()); 
  } 
  
- void SALOMEDS_Study::init_orb()
- {
-   ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
-   ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting()); 
-   _orb = init(0 , 0 ) ;     
- }
- SALOMEDS::Study_ptr SALOMEDS_Study::GetStudy()
- {
-   if (_isLocal) {
-     SALOMEDS::Locker lock;
-     if (!CORBA::is_nil(_corba_impl)) return SALOMEDS::Study::_duplicate(_corba_impl);
-     std::string anIOR = _local_impl->GetTransientReference();
-     SALOMEDS::Study_var aStudy;
-     if (!_local_impl->IsError() && anIOR != "") {
-       aStudy = SALOMEDS::Study::_narrow(_orb->string_to_object(anIOR.c_str()));
-     }
-     else {
-       SALOMEDS_Study_i *aStudy_servant = new SALOMEDS_Study_i(_local_impl, _orb);
-       aStudy = aStudy_servant->_this();
-       _local_impl->SetTransientReference(_orb->object_to_string(aStudy));
-     }
-     _corba_impl = SALOMEDS::Study::_duplicate(aStudy);
-     return aStudy._retn();
-   }
-   else {
-     return SALOMEDS::Study::_duplicate(_corba_impl);
-   }
-   return SALOMEDS::Study::_nil();
- }
  _PTR(AttributeParameter) SALOMEDS_Study::GetCommonParameters(const std::string& theID, int theSavePoint)
  {
    SALOMEDSClient_AttributeParameter* AP = NULL;
@@@ -1010,12 -999,16 +1004,16 @@@ _PTR(AttributeParameter) SALOMEDS_Study
  
  void SALOMEDS_Study::attach(SALOMEDS::Observer_ptr theObserver,bool modify)
  {
-   if(CORBA::is_nil(_corba_impl)) GetStudy(); //If CORBA implementation is null then retrieve it
+   if(CORBA::is_nil(_corba_impl))
+     return;
    _corba_impl->attach(theObserver,modify);
  }
  
  void SALOMEDS_Study::detach(SALOMEDS::Observer_ptr theObserver)
  {
-   if(CORBA::is_nil(_corba_impl)) GetStudy(); //If CORBA implementation is null then retrieve it
+   if(CORBA::is_nil(_corba_impl))
+     return;
    _corba_impl->detach(theObserver);
  }
index 8aeed232c52603500333f282389a497cf63501e2,c67b195731aa66b4007ec4254b339a8da8a76140..80477af72e63ddae7e854180955cadbc626a9c3a
@@@ -32,7 -32,6 +32,6 @@@
  #include "SALOMEDS_SObject.hxx"
  #include "SALOMEDS_SComponent.hxx"
  #include "SALOMEDS_GenericAttribute.hxx"
- #include "SALOMEDS_StudyManager.hxx"
  #include "SALOMEDS_StudyBuilder_i.hxx"
  
  #include "SALOMEDS_Driver_i.hxx"
@@@ -50,8 -49,6 +49,8 @@@
  #include "Utils_ORB_INIT.hxx" 
  #include "Utils_SINGLETON.hxx" 
  
 +pthread_mutex_t SALOMEDS_StudyBuilder::_remoteBuilderMutex;
 +
  SALOMEDS_StudyBuilder::SALOMEDS_StudyBuilder(SALOMEDSImpl_StudyBuilder* theBuilder)
  {
    _isLocal = true;
@@@ -63,7 -60,6 +62,7 @@@
  
  SALOMEDS_StudyBuilder::SALOMEDS_StudyBuilder(SALOMEDS::StudyBuilder_ptr theBuilder)
  {
 +  pthread_mutex_lock( &_remoteBuilderMutex );
    _isLocal = false;
    _local_impl = NULL;
    _corba_impl = SALOMEDS::StudyBuilder::_duplicate(theBuilder);
@@@ -73,7 -69,6 +72,7 @@@
  
  SALOMEDS_StudyBuilder::~SALOMEDS_StudyBuilder() 
  {
 +  if (!_isLocal) pthread_mutex_unlock( &_remoteBuilderMutex );
  }
  
  _PTR(SComponent) SALOMEDS_StudyBuilder::NewComponent(const std::string& ComponentDataType)
@@@ -175,23 -170,6 +174,6 @@@ _PTR(SObject) SALOMEDS_StudyBuilder::Ne
    return _PTR(SObject)(aSO);
  }
  
- void SALOMEDS_StudyBuilder::AddDirectory(const std::string& thePath)
- {
-   if (_isLocal) {
-     CheckLocked();
-     SALOMEDS::Locker lock;
-     _local_impl->AddDirectory((char*)thePath.c_str());
-     if (_local_impl->IsError()) {
-       std::string anErrorCode = _local_impl->GetErrorCode();
-       if (anErrorCode == "StudyNameAlreadyUsed")  throw SALOMEDS::Study::StudyNameAlreadyUsed(); 
-       if (anErrorCode == "StudyInvalidDirectory") throw SALOMEDS::Study::StudyInvalidDirectory(); 
-       if (anErrorCode == "StudyInvalidComponent") throw SALOMEDS::Study::StudyInvalidComponent();  
-     }
-   }
-   else _corba_impl->AddDirectory((char*)thePath.c_str());
- }
  void SALOMEDS_StudyBuilder::LoadWith(const _PTR(SComponent)& theSCO, const std::string& theIOR)
  {
    if(!theSCO) return;
index 37336327f261f75f283475ba2a2ff75d12713e13,a57ab0a516cffeb46f60e8c5b6b9a4964279f7fb..ebb138633caf72019d76494ed00543dea7a03b95
@@@ -31,7 -31,6 +31,7 @@@
  
  #include "SALOMEDSClient.hxx"
  #include "SALOMEDSImpl_StudyBuilder.hxx"
 +#include <pthread.h>
  
  // IDL headers
  #include <SALOMEconfig.h>
@@@ -45,9 -44,7 +45,9 @@@ private
    SALOMEDS::StudyBuilder_var        _corba_impl;
    CORBA::ORB_var                    _orb;
  
 +
  public:
 +  static pthread_mutex_t            _remoteBuilderMutex;
  
    SALOMEDS_StudyBuilder(SALOMEDSImpl_StudyBuilder* theBuilder);
    SALOMEDS_StudyBuilder(SALOMEDS::StudyBuilder_ptr theBuilder);
@@@ -58,7 -55,6 +58,6 @@@
    virtual void RemoveComponent(const _PTR(SComponent)& theSCO);
    virtual _PTR(SObject) NewObject(const _PTR(SObject)& theFatherObject);
    virtual _PTR(SObject) NewObjectToTag(const _PTR(SObject)& theFatherObject, int theTag);
-   virtual void AddDirectory(const std::string& thePath);
    virtual void LoadWith(const _PTR(SComponent)& theSCO, const std::string& theIOR);
    virtual void Load(const _PTR(SObject)& theSCO);
    virtual void RemoveObject(const _PTR(SObject)& theSO);
index e3013e714232005a8ed7d0a64bb483476e53ad74,9ba49a3264f4d9b015a836287f7dbbc6e50758ac..f9ecf67a23bc930bd33f4db95f94f2d6c3d8da27
@@@ -26,7 -26,6 +26,6 @@@
  //
  #include "utilities.h"
  #include "SALOMEDS_StudyBuilder_i.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
  #include "SALOMEDS_Study_i.hxx"
  #include "SALOMEDS_SObject_i.hxx"
  #include "SALOMEDS_SComponent_i.hxx"
@@@ -68,23 -67,6 +67,23 @@@ SALOMEDS_StudyBuilder_i::SALOMEDS_Study
  SALOMEDS_StudyBuilder_i::~SALOMEDS_StudyBuilder_i()
  {}
  
-   PortableServer::POA_ptr poa = SALOMEDS_StudyManager_i::GetThePOA();
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_StudyBuilder_i::_default_POA()
 +{
++  PortableServer::POA_ptr poa = SALOMEDS_Study_i::GetThePOA();
 +  MESSAGE("SALOMEDS_StudyBuilder_i::_default_POA: " << poa);
 +  return PortableServer::POA::_duplicate(poa);
 +}
 +
  //============================================================================
  /*! Function : NewComponent
   *  Purpose  : Create a new component (Scomponent)
@@@ -338,26 -320,6 +337,6 @@@ void SALOMEDS_StudyBuilder_i::RemoveRef
    _impl->RemoveReference(aSO);
  }
  
- //============================================================================
- /*! Function : AddDirectory
-  *  Purpose  : adds a new directory with a path = thePath
-  */
- //============================================================================
- void SALOMEDS_StudyBuilder_i::AddDirectory(const char* thePath) 
- {
-   SALOMEDS::Locker lock;
-   CheckLocked();
-   if(thePath == NULL || strlen(thePath) == 0) throw SALOMEDS::Study::StudyInvalidDirectory();
-   if(!_impl->AddDirectory(std::string(thePath))) {
-     std::string anErrorCode = _impl->GetErrorCode();
-     if(anErrorCode == "StudyNameAlreadyUsed") throw SALOMEDS::Study::StudyNameAlreadyUsed(); 
-     if(anErrorCode == "StudyInvalidDirectory") throw SALOMEDS::Study::StudyInvalidDirectory(); 
-     if(anErrorCode == "StudyInvalidComponent") throw SALOMEDS::Study::StudyInvalidComponent();  
-   }
- }
  //============================================================================
  /*! Function : SetGUID
   *  Purpose  : 
index 99b44a92c1d17c7a16787334dd56b9cae4ae1c9d,07778737b498e230e72c9719d97405aeec542992..cfaee100ef2d6d46accae6d07ec5d039d11fdc96
@@@ -48,8 -48,6 +48,8 @@@ public
  
    ~SALOMEDS_StudyBuilder_i();
  
 +  virtual PortableServer::POA_ptr _default_POA();
 +
    //! NewComponent
    /*!
      \param ComponentDataType    
    */
    virtual SALOMEDS::SObject_ptr NewObjectToTag(SALOMEDS::SObject_ptr theFatherObject, CORBA::Long atag);
  
-   /*!
-     The methods adds a new subdirectory, the path can be absolute or relative (then the current context is used)
-   */
-   virtual void AddDirectory(const char* thePath);
    virtual void LoadWith(SALOMEDS::SComponent_ptr sco, SALOMEDS::Driver_ptr Engine)
      throw(SALOME::SALOME_Exception);
    virtual void Load(SALOMEDS::SObject_ptr sco);
index 3d99e2b73925b3f4a428dc077152c8f4745c1d49,19abf1b64cd4e0a6278636dc4c9590f72c802073..050f925004414b04fecd526c907ebc85915ad283
@@@ -27,7 -27,6 +27,6 @@@
  #include "utilities.h"
  #include <sstream>
  #include "SALOMEDS_Study_i.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
  #include "SALOMEDS_UseCaseIterator_i.hxx"
  #include "SALOMEDS_GenericAttribute_i.hxx"
  #include "SALOMEDS_AttributeStudyProperties_i.hxx"
@@@ -48,6 -47,8 +47,8 @@@
  #include "DF_Label.hxx"
  #include "DF_Attribute.hxx"
  
+ #include "Utils_ExceptHandlers.hxx"
  #include "Basics_Utils.hxx"
  #include "SALOME_KernelServices.hxx"
  
  #include <unistd.h>
  #endif
  
+ UNEXPECT_CATCH(SalomeException,SALOME::SALOME_Exception);
+ UNEXPECT_CATCH(LockProtection, SALOMEDS::StudyBuilder::LockProtection);
+ static SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb);
++static  PortableServer::POA_ptr _poa;
++
  namespace SALOMEDS
  {
    class Notifier: public SALOMEDSImpl_AbstractCallback
      {
        for (ObsListIter it (myObservers.begin()); it != myObservers.end(); ++it)
        {
-       if ( it->first->_is_equivalent(theObs) ) {
-         myObservers.erase( it );
-         break;
-       }
+           if ( it->first->_is_equivalent(theObs) ) {
+             myObservers.erase( it );
+             break;
+           }
        }
      }
  
  
  } // namespace SALOMEDS
  
- std::map<SALOMEDSImpl_Study* , SALOMEDS_Study_i*> SALOMEDS_Study_i::_mapOfStudies;
  //============================================================================
  /*! Function : SALOMEDS_Study_i
   *  Purpose  : SALOMEDS_Study_i constructor
   */
  //============================================================================
- SALOMEDS_Study_i::SALOMEDS_Study_i(SALOMEDSImpl_Study* theImpl,
-                                    CORBA::ORB_ptr      orb)
+ SALOMEDS_Study_i::SALOMEDS_Study_i(CORBA::ORB_ptr orb)
+ {
+   _orb     = CORBA::ORB::_duplicate(orb);
+   _impl    = new SALOMEDSImpl_Study();
+   _factory = new SALOMEDS_DriverFactory_i(_orb);
+   _closed  = true;
+   Init();
+ }
+ //============================================================================
+ /*! Function : ~SALOMEDS_Study_i
+  *  Purpose  : SALOMEDS_Study_i destructor
+  */
+ //============================================================================
+ SALOMEDS_Study_i::~SALOMEDS_Study_i()
+ {
+   Clear();
+   delete _factory;
+   delete _impl;
+ }
+ //============================================================================
+ /*! Function : Init
+  *  Purpose  : Initialize study components
+  */
+ //============================================================================
+ void SALOMEDS_Study_i::Init()
  {
-   _orb            = CORBA::ORB::_duplicate(orb);
-   _impl           = theImpl;
+   if (!_closed)
+     throw SALOMEDS::Study::StudyInvalidReference();
+   SALOMEDS::Locker lock;
+   
+   if ( !_impl->GetDocument() )
+     _impl->Init();
    _builder        = new SALOMEDS_StudyBuilder_i(_impl->NewBuilder(), _orb);  
    _notifier       = new SALOMEDS::Notifier(_orb);
    _genObjRegister = new SALOMEDS::GenObjRegister(_orb);
    _closed         = false;
  
-   theImpl->setNotifier(_notifier);
-   theImpl->setGenObjRegister( _genObjRegister );
+   _impl->setNotifier(_notifier);
+   _impl->setGenObjRegister( _genObjRegister );
+   // update desktop title with new study name
+   NameChanged();
  
    // Notify GUI that study was created
    SALOME_NamingService *aNamingService = KERNEL::getNamingService();
    SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
    if ( !CORBA::is_nil(aSession) ) {
      std::stringstream ss;
-     ss << "studyCreated:" << theImpl->StudyId();
+     ss << "studyCreated";
      std::string str = ss.str();
      SALOMEDS::unlock();
      aSession->emitMessageOneWay(str.c_str());
      SALOMEDS::lock();
    }
  }
-   
  //============================================================================
- /*! Function : ~SALOMEDS_Study_i
-  *  Purpose  : SALOMEDS_Study_i destructor
+ /*! Function : Clear
+  *  Purpose  : Clear study components
   */
  //============================================================================
SALOMEDS_Study_i::~SALOMEDS_Study_i()
void SALOMEDS_Study_i::Clear()
  {
+   if (_closed)
+     return;
+   SALOMEDS::Locker lock;
    //delete the builder servant
--  PortableServer::POA_var poa=_builder->_default_POA();
++  PortableServer::POA_var poa=_default_POA();
    PortableServer::ObjectId_var anObjectId = poa->servant_to_id(_builder);
    poa->deactivate_object(anObjectId.in());
    _builder->_remove_ref();
-   
+   RemovePostponed(-1);
+   if (_impl->GetDocument()) {
+     SALOMEDS::SComponentIterator_var itcomponent = NewComponentIterator();
+     for (; itcomponent->More(); itcomponent->Next()) {
+       SALOMEDS::SComponent_var sco = itcomponent->Value();
+       CORBA::String_var compodatatype=sco->ComponentDataType();
+       MESSAGE ( "Look for an engine for data type :"<< compodatatype);
+       // if there is an associated Engine call its method for closing
+       CORBA::String_var IOREngine;
+       if (sco->ComponentIOR(IOREngine)) {
+         // we have found the associated engine to write the data
+         MESSAGE ( "We have found an engine for data type :"<< compodatatype);
+         //_narrow can throw a corba exception
+         try {
+             CORBA::Object_var obj = _orb->string_to_object(IOREngine);
+             if (!CORBA::is_nil(obj)) {
+               SALOMEDS::Driver_var anEngine = SALOMEDS::Driver::_narrow(obj) ;
+               if (!anEngine->_is_nil())  {
+                 SALOMEDS::unlock();
+                 anEngine->Close(sco);
+                 SALOMEDS::lock();
+               }
+             }
+         }
+         catch (CORBA::Exception&) {
+         }
+       }
+       sco->UnRegister();
+     }
+     //Does not need any more this iterator
+     itcomponent->UnRegister();
+   }
+   // Notify GUI that study is cleared
+   SALOME_NamingService *aNamingService = KERNEL::getNamingService();
+   CORBA::Object_ptr obj = aNamingService->Resolve("/Kernel/Session");
+   SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
+   if ( !CORBA::is_nil(aSession) ) {
+     std::stringstream ss;
+     ss << "studyCleared";
+     std::string str = ss.str();
+     SALOMEDS::unlock();
+     aSession->emitMessageOneWay(str.c_str());
+     SALOMEDS::lock();
+   }
+   _impl->Clear();
    _impl->setNotifier(0);
    delete _notifier;
    delete _genObjRegister;
-   //delete implementation
-   delete _impl;
-   _mapOfStudies.erase(_impl);
- }  
+   _notifier = NULL;
+   _closed = true;
+ }
  
-   PortableServer::POA_ptr poa = SALOMEDS_StudyManager_i::GetThePOA();
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_Study_i::_default_POA()
 +{
++  PortableServer::POA_ptr poa = GetThePOA();
 +  MESSAGE("SALOMEDS_Study_i::_default_POA: " << poa);
 +  return PortableServer::POA::_duplicate(poa);
 +}
 +
  //============================================================================
- /*! Function : GetPersistentReference
-  *  Purpose  : Get persistent reference of study (idem URL())
+ /*! Function : Open
+  *  Purpose  : Open a Study from it's persistent reference
   */
  //============================================================================
- char* SALOMEDS_Study_i::GetPersistentReference()
+ bool SALOMEDS_Study_i::Open(const wchar_t* aWUrl)
+   throw(SALOME::SALOME_Exception)
  {
-   SALOMEDS::Locker lock; 
+   if (!_closed)
+     Clear();
+   Init();
+   SALOMEDS::Locker lock;
+   Unexpect aCatch(SalomeException);
+   MESSAGE("Begin of SALOMEDS_Study_i::Open");
+   
+   std::string aUrl = Kernel_Utils::encode_s(aWUrl);
+   bool res = _impl->Open(std::string(aUrl));
+   // update desktop title with new study name
+   NameChanged();
+   if ( !res )
+     THROW_SALOME_CORBA_EXCEPTION("Impossible to Open study from file", SALOME::BAD_PARAM)
+   return res;
+ }
++PortableServer::POA_ptr SALOMEDS_Study_i::GetThePOA()
++{
++  return _poa;
++}
++
++void SALOMEDS_Study_i::SetThePOA(PortableServer::POA_ptr thePOA)
++{
++  _poa = PortableServer::POA::_duplicate(thePOA);
++}
++
+ //============================================================================
+ /*! Function : Save
+  *  Purpose  : Save a Study to it's persistent reference
+  */
+ //============================================================================
+ CORBA::Boolean SALOMEDS_Study_i::Save(CORBA::Boolean theMultiFile, CORBA::Boolean theASCII)
+ {
+   SALOMEDS::Locker lock;
    if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   return CORBA::string_dup(_impl->GetPersistentReference().c_str());
+     throw SALOMEDS::Study::StudyInvalidReference();
+   return _impl->Save(_factory, theMultiFile, theASCII);
+ }
+ //=============================================================================
+ /*! Function : SaveAs
+  *  Purpose  : Save a study to the persistent reference aUrl
+  */
+ //============================================================================
+ CORBA::Boolean SALOMEDS_Study_i::SaveAs(const wchar_t* aWUrl, CORBA::Boolean theMultiFile, CORBA::Boolean theASCII)
+ {
+   SALOMEDS::Locker lock;
+   if (_closed)
+     throw SALOMEDS::Study::StudyInvalidReference();
+   
+   std::string aUrl = Kernel_Utils::encode_s(aWUrl);
+   return _impl->SaveAs(std::string(aUrl), _factory, theMultiFile, theASCII);
+ }
+ //============================================================================
+ /*! Function : CanCopy
+  *  Purpose  :
+  */
+ //============================================================================
+ CORBA::Boolean SALOMEDS_Study_i::CanCopy(SALOMEDS::SObject_ptr theObject)
+ {
+   SALOMEDS::Locker lock;
+   if (_closed)
+     throw SALOMEDS::Study::StudyInvalidReference();
+   CORBA::String_var anID = theObject->GetID();
+   SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+   SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+   bool ret = _impl->CanCopy(anObject, aDriver);
+   delete aDriver;
+   return ret;
+ }
+ //============================================================================
+ /*! Function : Copy
+  *  Purpose  :
+  */
+ //============================================================================
+ CORBA::Boolean SALOMEDS_Study_i::Copy(SALOMEDS::SObject_ptr theObject)
+ {
+   SALOMEDS::Locker lock;
+   if (_closed)
+     throw SALOMEDS::Study::StudyInvalidReference();
+   CORBA::String_var anID = theObject->GetID();
+   SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+   SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+   bool ret = _impl->Copy(anObject, aDriver);
+   delete aDriver;
+   return ret;
+ }
+ //============================================================================
+ /*! Function : CanPaste
+  *  Purpose  :
+  */
+ //============================================================================
+ CORBA::Boolean SALOMEDS_Study_i::CanPaste(SALOMEDS::SObject_ptr theObject)
+ {
+   SALOMEDS::Locker lock;
+   if (_closed)
+     throw SALOMEDS::Study::StudyInvalidReference();
+   CORBA::String_var anID = theObject->GetID();
+   SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+   SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+   bool ret = _impl->CanPaste(anObject, aDriver);
+   delete aDriver;
+   return ret;
+ }
+ //============================================================================
+ /*! Function : Paste
+  *  Purpose  :
+  */
+ //============================================================================
+ SALOMEDS::SObject_ptr SALOMEDS_Study_i::Paste(SALOMEDS::SObject_ptr theObject)
+      throw(SALOMEDS::StudyBuilder::LockProtection)
+ {
+   SALOMEDS::Locker lock;
+   Unexpect aCatch(LockProtection);
+   CORBA::String_var anID = theObject->GetID();
+   SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+   SALOMEDSImpl_SObject aNewSO;
+   try {
+     SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+     aNewSO =  _impl->Paste(anObject, aDriver);
+     delete aDriver;
+   }
+   catch (...) {
+     throw SALOMEDS::StudyBuilder::LockProtection();
+   }
+   SALOMEDS::SObject_var so = SALOMEDS_SObject_i::New (aNewSO, _orb);
+   return so._retn();
  }
+ SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb)
+ {
+   SALOMEDS_Driver_i* driver = NULL;
+   SALOMEDSImpl_SComponent aSCO = theObject.GetFatherComponent();
+   if(!aSCO.IsNull()) {
+     std::string IOREngine = aSCO.GetIOR();
+     if(!IOREngine.empty()) {
+       CORBA::Object_var obj = orb->string_to_object(IOREngine.c_str());
+       Engines::EngineComponent_var Engine = Engines::EngineComponent::_narrow(obj) ;
+       driver = new SALOMEDS_Driver_i(Engine, orb);
+     }
+   }
+   return driver;
+ }
  //============================================================================
- /*! Function : GetTransientReference
-  *  Purpose  : Get IOR of the Study (registered in OCAF document in doc->Root)
+ /*! Function : GetPersistentReference
+  *  Purpose  : Get persistent reference of study (idem URL())
   */
  //============================================================================
- char* SALOMEDS_Study_i::GetTransientReference()
+ char* SALOMEDS_Study_i::GetPersistentReference()
  {
    SALOMEDS::Locker lock; 
    if (_closed)
      throw SALOMEDS::Study::StudyInvalidReference();  
-   return CORBA::string_dup(_impl->GetTransientReference().c_str());
+   return CORBA::string_dup(_impl->GetPersistentReference().c_str());
  }
  
  //============================================================================
@@@ -546,157 -771,6 +800,6 @@@ char* SALOMEDS_Study_i::GetObjectPath(C
    return CORBA::string_dup(aPath.c_str());
  }
  
- //============================================================================
- /*! Function : SetContext
-  *  Purpose  : Sets the current context
-  */
- //============================================================================
- void SALOMEDS_Study_i::SetContext(const char* thePath) 
- {
-   SALOMEDS::Locker lock; 
-   if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   _impl->SetContext(std::string((char*)thePath));
-   if (_impl->IsError() && _impl->GetErrorCode() == "InvalidContext") 
-     throw SALOMEDS::Study::StudyInvalidContext();  
- }
- //============================================================================
- /*! Function : GetContext
-  *  Purpose  : Gets the current context
-  */
- //============================================================================
- char* SALOMEDS_Study_i::GetContext() 
- {
-   SALOMEDS::Locker lock; 
-   
-   if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   if (!_impl->HasCurrentContext()) throw SALOMEDS::Study::StudyInvalidContext();
-   return CORBA::string_dup(_impl->GetContext().c_str());
- }
- //============================================================================
- /*! Function : GetObjectNames
-  *  Purpose  : method to get all object names in the given context (or in the current context, if 'theContext' is empty)
-  */
- //============================================================================
- SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetObjectNames(const char* theContext) 
- {
-   SALOMEDS::Locker lock; 
-   if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-   if (strlen(theContext) == 0 && !_impl->HasCurrentContext())
-     throw SALOMEDS::Study::StudyInvalidContext();
-   
-   std::vector<std::string> aSeq = _impl->GetObjectNames(std::string((char*)theContext));
-   if (_impl->GetErrorCode() == "InvalidContext")
-     throw SALOMEDS::Study::StudyInvalidContext();
-   int aLength = aSeq.size();
-   aResult->length(aLength);
-   for (int anIndex = 0; anIndex < aLength; anIndex++) {
-     aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
-   }
-   return aResult._retn();
- }
- //============================================================================
- /*! Function : GetDirectoryNames
-  *  Purpose  : method to get all directory names in the given context (or in the current context, if 'theContext' is empty)
-  */
- //============================================================================
- SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetDirectoryNames(const char* theContext) 
- {
-   SALOMEDS::Locker lock; 
-   if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-   if (strlen(theContext) == 0 && !_impl->HasCurrentContext())
-     throw SALOMEDS::Study::StudyInvalidContext();
-   
-   std::vector<std::string> aSeq = _impl->GetDirectoryNames(std::string((char*)theContext));
-   if (_impl->GetErrorCode() == "InvalidContext")
-     throw SALOMEDS::Study::StudyInvalidContext();
-   int aLength = aSeq.size();
-   aResult->length(aLength);
-   for (int anIndex = 0; anIndex < aLength; anIndex++) {
-     aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
-   }
-   
-   return aResult._retn();
- }
- //============================================================================
- /*! Function : GetFileNames
-  *  Purpose  : method to get all file names in the given context (or in the current context, if 'theContext' is empty)
-  */
- //============================================================================
- SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetFileNames(const char* theContext) 
- {
-   SALOMEDS::Locker lock; 
-   if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-   if (strlen(theContext) == 0 && !_impl->HasCurrentContext())
-     throw SALOMEDS::Study::StudyInvalidContext();
-   
-   std::vector<std::string> aSeq = _impl->GetFileNames(std::string((char*)theContext));
-   if (_impl->GetErrorCode() == "InvalidContext")
-     throw SALOMEDS::Study::StudyInvalidContext();
-   int aLength = aSeq.size();
-   aResult->length(aLength);
-   for (int anIndex = 0; anIndex < aLength; anIndex++) {
-     aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
-   }
-   return aResult._retn();
- }
- //============================================================================
- /*! Function : GetComponentNames
-  *  Purpose  : method to get all components names
-  *  SRN:       Note, theContext can be any, it doesn't matter
-  */
- //============================================================================
- SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetComponentNames(const char* theContext) 
- {
-   SALOMEDS::Locker lock; 
-   if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-   std::vector<std::string> aSeq = _impl->GetComponentNames(std::string((char*)theContext));
-   int aLength = aSeq.size();
-   aResult->length(aLength);
-   for(int anIndex = 0; anIndex < aLength; anIndex++) {
-     aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
-   }
-   return aResult._retn();
- }
  //============================================================================
  /*! Function : NewChildIterator
   *  Purpose  : Create a ChildIterator from an SObject
@@@ -761,11 -835,11 +864,11 @@@ SALOMEDS::StudyBuilder_ptr SALOMEDS_Stu
   *  Purpose  : get study name
   */
  //============================================================================
char* SALOMEDS_Study_i::Name()
wchar_t* SALOMEDS_Study_i::Name()
  {
    SALOMEDS::Locker lock; 
    // Name is specified as IDL attribute: user exception cannot be raised
-   return CORBA::string_dup(_impl->Name().c_str());
+   return CORBA::wstring_dup(Kernel_Utils::decode_s(_impl->Name()));
  }
  
  //============================================================================
   *  Purpose  : set study name
   */
  //============================================================================
- void SALOMEDS_Study_i::Name(const char* name)
+ void SALOMEDS_Study_i::Name(const wchar_t* wname)
  {
-   SALOMEDS::Locker lock;  
+   SALOMEDS::Locker lock;
    // Name is specified as IDL attribute: user exception cannot be raised
-   _impl->Name(std::string(name));
+   _impl->Name(Kernel_Utils::encode_s(wname));
  }
  
  //============================================================================
@@@ -840,11 -914,11 +943,11 @@@ void SALOMEDS_Study_i::Modified(
   *  Purpose  : get URL of the study (persistent reference of the study)
   */
  //============================================================================
char* SALOMEDS_Study_i::URL()
wchar_t* SALOMEDS_Study_i::URL()
  {
-   SALOMEDS::Locker lock; 
+   SALOMEDS::Locker lock;
    // URL is specified as IDL attribute: user exception cannot be raised
-   return CORBA::string_dup(_impl->URL().c_str());
+   return CORBA::wstring_dup(Kernel_Utils::decode_s(_impl->URL()));
  }
  
  //============================================================================
   *  Purpose  : set URL of the study (persistent reference of the study)
   */
  //============================================================================
- void SALOMEDS_Study_i::URL(const char* url)
+ void SALOMEDS_Study_i::URL(const wchar_t* wurl)
  {
    SALOMEDS::Locker lock; 
    // URL is specified as IDL attribute: user exception cannot be raised
-   _impl->URL(std::string((char*)url));
- }
+   _impl->URL(Kernel_Utils::encode_s(wurl));
  
- CORBA::Short SALOMEDS_Study_i::StudyId()
- {
-   SALOMEDS::Locker lock; 
-   // StudyId is specified as IDL attribute: user exception cannot be raised
-   return _impl->StudyId();
- }
- void SALOMEDS_Study_i::StudyId(CORBA::Short id)
- { 
-   SALOMEDS::Locker lock; 
-   // StudyId is specified as IDL attribute: user exception cannot be raised
-   _impl->StudyId(id);
+   // update desktop title with new study name
+   NameChanged();
  }
  
  void SALOMEDS_Study_i::UpdateIORLabelMap(const char* anIOR, const char* anEntry) 
    _impl->UpdateIORLabelMap(std::string((char*)anIOR), std::string((char*)anEntry));
  }
  
- SALOMEDS::Study_ptr SALOMEDS_Study_i::GetStudy(const DF_Label& theLabel, CORBA::ORB_ptr orb) 
- {
-   SALOMEDS::Locker lock; 
-   SALOMEDSImpl_AttributeIOR* Att = NULL;
-   if ((Att=(SALOMEDSImpl_AttributeIOR*)theLabel.Root().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))){
-     char* IOR = CORBA::string_dup(Att->Value().c_str());
-     CORBA::Object_var obj = orb->string_to_object(IOR);
-     SALOMEDS::Study_ptr aStudy = SALOMEDS::Study::_narrow(obj) ;
-     ASSERT(!CORBA::is_nil(aStudy));
-     return SALOMEDS::Study::_duplicate(aStudy);
-   } else {
-     MESSAGE("GetStudy: Problem to get study");
-   }
-   return SALOMEDS::Study::_nil();
- }
- SALOMEDS_Study_i* SALOMEDS_Study_i::GetStudyServant(SALOMEDSImpl_Study* aStudyImpl, CORBA::ORB_ptr orb)
- {
-   if (_mapOfStudies.find(aStudyImpl) != _mapOfStudies.end()) 
-     return _mapOfStudies[aStudyImpl];
-   else
-   {
-     SALOMEDS_Study_i *Study_servant = new SALOMEDS_Study_i(aStudyImpl, orb);
-     _mapOfStudies[aStudyImpl]=Study_servant;
-     return Study_servant;
-   }
- }
  void SALOMEDS_Study_i::IORUpdated(SALOMEDSImpl_AttributeIOR* theAttribute) 
  {
    SALOMEDS::Locker lock; 
@@@ -995,69 -1029,6 +1058,6 @@@ SALOMEDS::UseCaseBuilder_ptr SALOMEDS_S
    return uc._retn();
  }
  
- //============================================================================
- /*! Function : Close
-  *  Purpose  : 
-  */
- //============================================================================
- void SALOMEDS_Study_i::Close()
- {
-   SALOMEDS::Locker lock; 
-   if (_closed)
-     throw SALOMEDS::Study::StudyInvalidReference();  
-   RemovePostponed(-1);
-   
-   SALOMEDS::SComponentIterator_var itcomponent = NewComponentIterator();
-   for (; itcomponent->More(); itcomponent->Next()) {
-     SALOMEDS::SComponent_var sco = itcomponent->Value();
-     CORBA::String_var compodatatype=sco->ComponentDataType();
-     MESSAGE ( "Look for an engine for data type :"<< compodatatype);
-     // if there is an associated Engine call its method for closing
-     CORBA::String_var IOREngine;
-     if (sco->ComponentIOR(IOREngine)) {
-       // we have found the associated engine to write the data 
-       MESSAGE ( "We have found an engine for data type :"<< compodatatype);
-       //_narrow can throw a corba exception
-       try {
-       CORBA::Object_var obj = _orb->string_to_object(IOREngine);
-       if (!CORBA::is_nil(obj)) {
-         SALOMEDS::Driver_var anEngine = SALOMEDS::Driver::_narrow(obj) ;
-         if (!anEngine->_is_nil())  { 
-           SALOMEDS::unlock();
-           anEngine->Close(sco);
-           SALOMEDS::lock();
-         }
-       }
-       } 
-       catch (CORBA::Exception&) {
-       }
-     }
-     sco->UnRegister();
-   }
-   
-   //Does not need any more this iterator
-   itcomponent->UnRegister();
-   
-   // Notify GUI that study is closed
-   SALOME_NamingService *aNamingService = KERNEL::getNamingService();
-   CORBA::Object_ptr obj = aNamingService->Resolve("/Kernel/Session");
-   SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
-   if ( !CORBA::is_nil(aSession) ) {
-     std::stringstream ss;
-     ss << "studyClosed:" << _impl->StudyId();
-     std::string str = ss.str();
-     SALOMEDS::unlock();
-     aSession->emitMessageOneWay(str.c_str());
-     SALOMEDS::lock();
-   }
-   
-   _impl->Close();
-   _closed = true;
- }
  //============================================================================
  /*! Function : AddPostponed
   *  Purpose  : 
@@@ -1597,6 -1568,27 +1597,27 @@@ void SALOMEDS_Study_i::EnableUseCaseAut
    }
  }
  
+ CORBA::Long SALOMEDS_Study_i::getPID()
+ {
+ #ifdef WIN32
+   return (CORBA::Long)_getpid();
+ #else
+   return (CORBA::Long)getpid();
+ #endif
+ }
+ void SALOMEDS_Study_i::ShutdownWithExit()
+ {
+   exit( EXIT_SUCCESS );
+ }
+ void SALOMEDS_Study_i::Shutdown()
+ {
+   if(!CORBA::is_nil(_orb))
+     _orb->shutdown(0);
+ }
  //============================================================================
  /*! Function : attach
   *  Purpose  : This function attach an observer to the study
@@@ -1633,3 -1625,19 +1654,19 @@@ CORBA::LongLong SALOMEDS_Study_i::GetLo
    isLocal = (strcmp(theHostname, Kernel_Utils::GetHostname().c_str()) == 0 && pid == thePID)?1:0;
    return reinterpret_cast<CORBA::LongLong>(_impl);
  }
+ void SALOMEDS_Study_i::NameChanged()
+ {
+   // Notify GUI that the name of study was changed
+   SALOME_NamingService *aNamingService = KERNEL::getNamingService();
+   CORBA::Object_var obj = aNamingService->Resolve("/Kernel/Session");
+   SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
+   if ( !CORBA::is_nil(aSession) ) {
+     std::stringstream ss;
+     ss << "studyNameChanged";
+     std::string str = ss.str();
+     SALOMEDS::unlock();
+     aSession->emitMessageOneWay(str.c_str());
+     SALOMEDS::lock();
+   }
+ }
index 59fed56643c5fbd007b6f4515525ae3b4dff9e1f,d1c3d7f22eb546f915d980acaa785fa7aba609cb..f77d1e2c594ed81f4dc7f08ff5dde5b913d8dca7
  #include <stdio.h>
  
  //SALOMEDS headers
- #include "SALOMEDS_StudyManager_i.hxx"
  #include "SALOMEDS_SComponentIterator_i.hxx"
  #include "SALOMEDS_StudyBuilder_i.hxx"
  #include "SALOMEDS_SObject_i.hxx"
  #include "SALOMEDS_UseCaseBuilder_i.hxx"
+ #include "SALOMEDS_Driver_i.hxx"
  
  #include "SALOMEDSImpl_Study.hxx"
  #include "SALOMEDSImpl_AttributeIOR.hxx"
  class Standard_EXPORT SALOMEDS_Study_i: public POA_SALOMEDS::Study
  {
  private:
+   void                            NameChanged();
    CORBA::ORB_var                 _orb;
    SALOMEDSImpl_Study*            _impl;  
    SALOMEDS_StudyBuilder_i*       _builder;    
-   static std::map<SALOMEDSImpl_Study*, SALOMEDS_Study_i*> _mapOfStudies;
    SALOMEDSImpl_AbstractCallback* _notifier;
    SALOMEDSImpl_AbstractCallback* _genObjRegister;
+   SALOMEDS_DriverFactory_i*      _factory;
    bool                           _closed;
  
  public:
  
    //! standard constructor
-   SALOMEDS_Study_i(SALOMEDSImpl_Study*, CORBA::ORB_ptr);
+   SALOMEDS_Study_i(CORBA::ORB_ptr);
    
    //! standard destructor
-   virtual ~SALOMEDS_Study_i(); 
++
+   virtual ~SALOMEDS_Study_i();
 -  
 +
 +  virtual PortableServer::POA_ptr _default_POA();
-   
++
+   virtual void Init();
+   virtual void Clear();
+   //! method to Open a Study
+   /*!
+     \param char* arguments, the study URL
+     \return Study_ptr arguments
+   */
+   virtual bool Open(const wchar_t* aStudyUrl) throw (SALOME::SALOME_Exception);
+   //! method to save a Study
+   virtual CORBA::Boolean Save(CORBA::Boolean theMultiFile, CORBA::Boolean theASCII);
+   //! method to save a Study to the persistent reference aUrl
+   /*!
+     \param char* arguments, the new URL of the study
+   */
+   virtual CORBA::Boolean SaveAs(const wchar_t* aUrl, CORBA::Boolean theMultiFile, CORBA::Boolean theASCII);
+   //! method to copy the object
+   /*!
+     \param theObject object to copy
+   */
+   virtual CORBA::Boolean Copy(SALOMEDS::SObject_ptr theObject);
+   virtual CORBA::Boolean CanCopy(SALOMEDS::SObject_ptr theObject);
+   //! method to paste the object in study
+   /*!
+     \param theObject object to paste
+   */
+   virtual SALOMEDS::SObject_ptr Paste(SALOMEDS::SObject_ptr theObject) throw(SALOMEDS::StudyBuilder::LockProtection);
+   virtual CORBA::Boolean CanPaste(SALOMEDS::SObject_ptr theObject);
    //! method to Get persistent reference of study (idem URL())
    /*!
      \sa URL()
    */  
    virtual char* GetPersistentReference();
  
-   //! method to Get transient reference of study
-   /*!
-     \return char* arguments, the transient reference of the study
-   */  
-   virtual char* GetTransientReference();
    //! method to detect if a study is empty
    /*!
      \return bool arguments, true if study is empty
    */
    virtual char* GetObjectPath(CORBA::Object_ptr theObject);
  
-   //! method to set a context: root ('/') is UserData component
-   /*!
-   */
-   virtual void SetContext(const char* thePath);
-   //! method to get a context
-   /*!
-   */
-   virtual char* GetContext();  
-   //! method to get all object names in the given context (or in the current context, if 'theContext' is empty)
-   /*!
-   */
-   virtual SALOMEDS::ListOfStrings* GetObjectNames(const char* theContext);
-   //! method to get all directory names in the given context (or in the current context, if 'theContext' is empty)
-   /*!
-   */
-   virtual SALOMEDS::ListOfStrings* GetDirectoryNames(const char* theContext);
-   //! method to get all file names in the given context (or in the current context, if 'theContext' is empty)
-   /*!
-   */
-   virtual SALOMEDS::ListOfStrings* GetFileNames(const char* theContext);
-   //! method to get all components names
-   /*!
-   */
-   virtual SALOMEDS::ListOfStrings* GetComponentNames(const char* theContext);
    //! method to Create a ChildIterator from an SObject 
    /*!
      \param aSO  SObject_ptr arguments
    /*!
      \return char* arguments, the study name
    */
-   virtual char* Name();
+   virtual wchar_t* Name();
  
    //! method to set study name
    /*!
      \param name char* arguments, the study name
    */
-   virtual void  Name(const char* name);
+   virtual void Name(const wchar_t* name);
  
    //! method to get if study has been saved
    /*!
    /*!
      \return char* arguments, the study URL 
    */
-   virtual char* URL();
+   virtual wchar_t* URL();
  
   //! method to set URL of the study
    /*!
      \param url char* arguments, the study URL
    */
-   virtual void  URL(const char* url);
-   virtual CORBA::Short StudyId();
-   virtual void  StudyId(CORBA::Short id);
-   static SALOMEDS::Study_ptr GetStudy(const DF_Label& theLabel, CORBA::ORB_ptr orb);
-   static SALOMEDS_Study_i* GetStudyServant(SALOMEDSImpl_Study*, CORBA::ORB_ptr orb);
+   virtual void URL(const wchar_t* url);
  
    static void IORUpdated(SALOMEDSImpl_AttributeIOR* theAttribute);
  
  
    virtual SALOMEDS::UseCaseBuilder_ptr GetUseCaseBuilder();
  
-   virtual void Close();
    void EnableUseCaseAutoFilling(CORBA::Boolean isEnabled); 
  
    // postponed destroying of CORBA object functionality
  
    virtual CORBA::LongLong GetLocalImpl(const char* theHostname, CORBA::Long thePID, CORBA::Boolean& isLocal);
  
++  static void SetThePOA(PortableServer::POA_ptr);
++  static PortableServer::POA_ptr GetThePOA();
++
+   void ping(){};
+   CORBA::Long getPID();
+   void ShutdownWithExit();
+   void Shutdown();
    virtual void attach(SALOMEDS::Observer_ptr theObs, CORBA::Boolean modify);
    virtual void detach(SALOMEDS::Observer_ptr theObs);
  };
index 4c4d3fdd4fb8138b9abc1e0e46800259cecc7ac6,118ab2d8120f3b5123ea895c448899ad04c7187b..5726f6b607d13dd155d55fab793aed4ba59ca31b
@@@ -27,8 -27,7 +27,8 @@@
  #include "SALOMEDS_UseCaseBuilder_i.hxx"
  #include "SALOMEDS_UseCaseIterator_i.hxx"
  #include "SALOMEDS_SObject_i.hxx"  
++#include "SALOMEDS_Study_i.hxx"
  #include "SALOMEDS.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
  
  #include "utilities.h"
  
@@@ -38,8 -37,7 +38,8 @@@
   */
  //============================================================================
  SALOMEDS_UseCaseBuilder_i::SALOMEDS_UseCaseBuilder_i(SALOMEDSImpl_UseCaseBuilder* theImpl,
 -                                                     CORBA::ORB_ptr orb)
 +                                                     CORBA::ORB_ptr orb) :
-   GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
++  GenericObj_i(SALOMEDS_Study_i::GetThePOA())
  {
    _orb = CORBA::ORB::_duplicate(orb);
    _impl = theImpl;
@@@ -54,23 -52,6 +54,23 @@@ SALOMEDS_UseCaseBuilder_i::~SALOMEDS_Us
  {
  }
  
-   myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_UseCaseBuilder_i::_default_POA()
 +{
++  myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
 +  //MESSAGE("SALOMEDS_UseCaseBuilder_i::_default_POA: " << myPOA);
 +  return PortableServer::POA::_duplicate(myPOA);
 +}
 +
  
  //============================================================================
  /*! Function : Append
index dd34e11b7ed7cb7c2d14bcd1e4246debb45b98dd,cb3babe7672d7a2567f8d13d58f880bdc6b8d180..eb6a1ab8919408ccde333b5f9669b487299c043f
@@@ -26,8 -26,7 +26,8 @@@
  //
  #include "SALOMEDS_UseCaseIterator_i.hxx"
  #include "SALOMEDS_SObject_i.hxx"
++#include "SALOMEDS_Study_i.hxx"
  #include "SALOMEDS.hxx"
- #include "SALOMEDS_StudyManager_i.hxx"
  
  #include "SALOMEDSImpl_SObject.hxx"
  #include "utilities.h"
@@@ -38,8 -37,7 +38,8 @@@
   */
  //============================================================================
  SALOMEDS_UseCaseIterator_i::SALOMEDS_UseCaseIterator_i(const SALOMEDSImpl_UseCaseIterator& theImpl, 
 -                                                       CORBA::ORB_ptr orb)
 +                                                       CORBA::ORB_ptr orb) :
-   GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
++  GenericObj_i(SALOMEDS_Study_i::GetThePOA())
  {
    _orb = CORBA::ORB::_duplicate(orb);
    _impl = theImpl.GetPersistentCopy();
@@@ -55,23 -53,6 +55,23 @@@ SALOMEDS_UseCaseIterator_i::~SALOMEDS_U
      if(_impl) delete _impl;
  }
  
-   myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
 +//============================================================================
 +/*!
 +  \brief Get default POA for the servant object.
 +
 +  This function is implicitly called from "_this()" function.
 +  Default POA can be set via the constructor.
 +
 +  \return reference to the default POA for the servant
 +*/
 +//============================================================================
 +PortableServer::POA_ptr SALOMEDS_UseCaseIterator_i::_default_POA()
 +{
++  myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
 +  //MESSAGE("SALOMEDS_UseCaseIterator_i::_default_POA: " << myPOA);
 +  return PortableServer::POA::_duplicate(myPOA);
 +}
 +
  //============================================================================
  /*! Function :Init
   * 
index 686f3ea5bfca36ae5b7d97c7fa29267d6910962d,29840b7f39252b99b81270218b49c40f15cd13e2..abb180c201425c3329301c285a873c377854890d
@@@ -43,23 -43,20 +43,22 @@@ public
    virtual ~SALOMEDSClient_SObject() {}
  
    virtual bool IsNull() const = 0;
 -  virtual std::string GetID()  = 0;
 +  virtual std::string GetID() = 0;
    virtual _PTR(SComponent) GetFatherComponent() = 0;
 -  virtual _PTR(SObject)    GetFather() = 0;
 -  virtual bool FindAttribute(_PTR(GenericAttribute)& anAttribute, const std::string& aTypeOfAttribute) = 0;
 -  virtual bool ReferencedObject(_PTR(SObject)& theObject) = 0;
 -  virtual bool FindSubObject(int theTag, _PTR(SObject)& theObject) = 0;
 +  virtual _PTR(SObject) GetFather() = 0;
 +  virtual bool FindAttribute(_PTR(GenericAttribute)& attribute, const std::string& type) = 0;
 +  virtual bool ReferencedObject(_PTR(SObject)& object) = 0;
 +  virtual bool FindSubObject(int tag, _PTR(SObject)& object) = 0;
-   virtual _PTR(Study) GetStudy() = 0;
    virtual std::string Name() = 0;
 -  virtual void  Name(const std::string& theName)  = 0;
 +  virtual void Name(const std::string& name) = 0;
    virtual std::vector<_PTR(GenericAttribute)> GetAllAttributes() = 0;
    virtual std::string GetName() = 0;
    virtual std::string GetComment() = 0;
    virtual std::string GetIOR() = 0;
 -  virtual int   Tag() = 0;
 -  virtual int   Depth() = 0;
 +  virtual void SetAttrString(const std::string& name, const std::string& value) = 0;
 +  virtual int Tag() = 0;
 +  virtual int GetLastChildTag() = 0;
 +  virtual int Depth() = 0;
  };
  
  #endif