Example #1
0
def setup(self):
    """Sets up ICE"""
    if self.config.mumble:
        slicefile = self.config.mumble.slice
        icesecret = self.config.mumble.secret
    else:
        slicefile = self.config.mumble_slice
        icesecret = self.config.mumble_secret

    Ice.loadSlice('', ['-I' + Ice.getSliceDir(), slicefile ] )
    prop = Ice.createProperties([])
    prop.setProperty('Ice.Default.EncodingVersion', '1.0')
    prop.setProperty("Ice.ImplicitContext", "Shared")
    prop.setProperty("Ice.MessageSizeMax",  "65535")

    idd = Ice.InitializationData()
    idd.properties = prop
    global ice
    ice = Ice.initialize(idd)
    ice.getImplicitContext().put("secret", icesecret.encode("utf-8"))
    global Murmur
    import Murmur
    ## Set up threaded checker
    print "set up and now starting timer thread"
    t = threading.Timer(20.0, mumble_auto_loop, [self])
    t.start()
Example #2
0
    def run(self, args):

        properties = self.createTestProperties(args)
        #
        # This test kills connections, so we don't want warnings.
        #
        properties.setProperty("Ice.Warn.Connections", "0")

        #
        # Limit the recv buffer size, this test relies on the socket
        # send() blocking after sending a given amount of data.
        #
        properties.setProperty("Ice.TCP.RcvSize", "50000")

        with self.initialize(properties=properties) as communicator:

            communicator.getProperties().setProperty("TestAdapter.Endpoints", self.getTestEndpoint())
            communicator.getProperties().setProperty("ControllerAdapter.Endpoints", self.getTestEndpoint(num=1))
            communicator.getProperties().setProperty("ControllerAdapter.ThreadPool.Size", "1")

            adapter = communicator.createObjectAdapter("TestAdapter")
            adapter2 = communicator.createObjectAdapter("ControllerAdapter")

            testController = TestI.TestIntfControllerI(adapter)

            adapter.add(TestI.TestIntfI(), Ice.stringToIdentity("test"))
            adapter.add(TestI.TestIntfII(), Ice.stringToIdentity("test2"))
            adapter.activate()

            adapter2.add(testController, Ice.stringToIdentity("testController"))
            adapter2.activate()

            communicator.waitForShutdown()
Example #3
0
    def createCommunicator(self, props, current=None):
        #
        # Prepare the property set using the given properties.
        #
        init = Ice.InitializationData()
        init.properties = Ice.createProperties()
        for k, v in props.items():
            init.properties.setProperty(k, v)

        #
        # Initialize a new communicator.
        #
        communicator = Ice.initialize(init)

        #
        # Install a custom admin facet.
        #
        communicator.addAdminFacet(TestFacetI(), "TestFacet")

        #
        # The RemoteCommunicator servant also implements PropertiesAdminUpdateCallback.
        # Set the callback on the admin facet.
        #
        servant = RemoteCommunicatorI(communicator)
        admin = communicator.findAdminFacet("Properties")
        if admin != None:
            admin.addUpdateCallback(servant)

        proxy = current.adapter.addWithUUID(servant)
        return Test.RemoteCommunicatorPrx.uncheckedCast(proxy)
Example #4
0
 def __init__(self,slice = "Murmur.ice",proxy = "Meta:tcp -h 127.0.0.1 -p 6502"):
     Ice.loadSlice(slice)
     import Murmur
     ice = Ice.initialize()
     prx = ice.stringToProxy(proxy)
     self.murmur = Murmur.MetaPrx.checkedCast(prx)
     self.Murmur = Murmur
Example #5
0
def connect():
	# setup
	iceslice = os.environ.get('iceslice', '/usr/share/slice/Murmur.ice')
	iceincpath = os.environ.get('iceincpath', '/usr/share/Ice/slice')
	port = int(os.environ.get('port', '6502'))
	secret = os.environ.get('secret', '')
	messagemax = os.environ.get('messagemax', '65535')
	# open
	import Ice, sys
	Ice.loadSlice('--all -I%s %s' % (iceincpath, iceslice))
	props = Ice.createProperties([])
	props.setProperty('Ice.MessageSizeMax', str(messagemax))
	props.setProperty('Ice.ImplicitContext', 'Shared')
	id = Ice.InitializationData()
	id.properties = props
	ice = Ice.initialize(id)
	ice.getImplicitContext().put('secret', secret)
	# init
	import Murmur
	meta = Murmur.MetaPrx.checkedCast(ice.stringToProxy('Meta:tcp -h 127.0.0.1 -p %s' % (port)))
	try:
		server = meta.getServer(1)
	except Murmur.InvalidSecretException:
		print 'Incorrect secret!'
		ice.shutdown()
		sys.exit(1)
	return server
def load(target):
    """
    uses __import__ followed by Ice.updateModules if available.

    """
    __import__(target)
    Ice.updateModules()
Example #7
0
    def run(self,req):

        try:
            props = Ice.createProperties(sys.argv)
            props.setProperty("Ice.MessageSizeMax", "20480")
            id = Ice.InitializationData()
            id.properties = props
            ic = Ice.initialize(id)
            twoway = ESUN.EASPrx.checkedCast(ic.stringToProxy(self.connect))
            if not twoway:
                print ": invalid proxy"
                return 1    
            starttime=time.time()
            ID = self.ID
            ret = twoway.invoke(ID, req, req)
            usetime = time.time()-starttime
            mark = True
            sret = json.dumps(ret,ensure_ascii=False).decode('gbk').encode('utf-8')
            ssret = json.loads(sret)
            #print sret
            return mark,ssret
        except Ice.Exception, ex:
            mark = False
            #print ex
            return mark,ex
Example #8
0
    def run(self, args):
        properties = self.createTestProperties(args)
        properties.setProperty("Ice.Warn.Dispatch", "0")
        properties.setProperty("Ice.Warn.Connections", "0")
        properties.setProperty("Ice.MessageSizeMax", "10")

        with self.initialize(properties=properties) as communicator:
            communicator.getProperties().setProperty("TestAdapter.Endpoints", self.getTestEndpoint(num=0))
            communicator.getProperties().setProperty("Ice.MessageSizeMax", "10")
            communicator.getProperties().setProperty("TestAdapter2.Endpoints", self.getTestEndpoint(num=1))
            communicator.getProperties().setProperty("TestAdapter2.MessageSizeMax", "0")
            communicator.getProperties().setProperty("TestAdapter3.Endpoints", self.getTestEndpoint(num=2))
            communicator.getProperties().setProperty("TestAdapter3.MessageSizeMax", "1")

            adapter = communicator.createObjectAdapter("TestAdapter")
            adapter2 = communicator.createObjectAdapter("TestAdapter2")
            adapter3 = communicator.createObjectAdapter("TestAdapter3")
            object = TestI.ThrowerI()
            adapter.add(object, Ice.stringToIdentity("thrower"))
            adapter2.add(object, Ice.stringToIdentity("thrower"))
            adapter3.add(object, Ice.stringToIdentity("thrower"))
            adapter.activate()
            adapter2.activate()
            adapter3.activate()
            communicator.waitForShutdown()
Example #9
0
    def startServer(self, current=None):
      
        #
        # Simulate a server: create a new communicator and object
        # adapter. The object adapter is started on a system allocated
        # port. The configuration used here contains the Ice.Locator
        # configuration variable. The new object adapter will register
        # its endpoints with the locator and create references containing
        # the adapter id instead of the endpoints.
        #
        serverCommunicator = Ice.initialize(data=initData)
        self._communicators.append(serverCommunicator)
        adapter = serverCommunicator.createObjectAdapter("TestAdapter")

        adapter2 = serverCommunicator.createObjectAdapter("TestAdapter2")

        locator = serverCommunicator.stringToProxy("locator:default -p 12010")
        adapter.setLocator(Ice.LocatorPrx.uncheckedCast(locator))
        adapter2.setLocator(Ice.LocatorPrx.uncheckedCast(locator))

        object = TestI(adapter, adapter2, self._registry)
        self._registry.addObject(adapter.add(object, Ice.stringToIdentity("test")))
        self._registry.addObject(adapter.add(object, Ice.stringToIdentity("test2")))
        adapter.add(object, Ice.stringToIdentity("test3"))

        adapter.activate()
        adapter2.activate()
Example #10
0
def run(args, communicator, initData):
    #
    # Register the server manager. The server manager creates a new
    # 'server' (a server isn't a different process, it's just a new
    # communicator and object adapter).
    #
    properties = communicator.getProperties()
    properties.setProperty("Ice.ThreadPool.Server.Size", "2")
    properties.setProperty("ServerManager.Endpoints", "default -p 12010:udp")

    adapter = communicator.createObjectAdapter("ServerManager")

    #
    # We also register a sample server locator which implements the
    # locator interface, this locator is used by the clients and the
    # 'servers' created with the server manager interface.
    #
    registry = ServerLocatorRegistry()
    registry.addObject(adapter.createProxy(Ice.stringToIdentity("ServerManager")))
    object = ServerManagerI(registry, initData)
    adapter.add(object, Ice.stringToIdentity("ServerManager"))

    registryPrx = Ice.LocatorRegistryPrx.uncheckedCast(adapter.add(registry, Ice.stringToIdentity("registry")))

    locator = ServerLocator(registry, registryPrx)
    adapter.add(locator, Ice.stringToIdentity("locator"))

    adapter.activate()
    communicator.waitForShutdown()

    return True
Example #11
0
def setup(bot):
    global _server,_meta
    bot.config.module_config('mumble_host',[None,'Host for mumble server'])
    bot.config.module_config('mumble_port',[0,'Port for mumble server'])
    bot.config.module_config('mumble_secret',[None,'Secret for mumble server'])

    if not bot.config.mumble_host or not bot.config.mumble_port:
        return
    prxstr = "s/1 -t:tcp -h %s -p %d -t 1000" % (bot.config.mumble_host,bot.config.mumble_port)
    meta_prxstr = "Meta:tcp -h %s -p %d -t 1000" % (bot.config.mumble_host,bot.config.mumble_port)
    props = Ice.createProperties()
    props.setProperty("Ice.ImplicitContext", "Shared")
    idata = Ice.InitializationData()
    idata.properties = props
    ice = Ice.initialize(idata)
    prx = ice.stringToProxy(str(prxstr))
    prx_meta = ice.stringToProxy(str(meta_prxstr))
    try:
        slice = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent, Ice.OperationMode.Idempotent, True, (), (), (), IcePy._t_string, ()).invoke(prx_meta, ((), None))
        (dynslicefiledesc, dynslicefilepath)  = tempfile.mkstemp(suffix = '.ice')
        dynslicefile = os.fdopen(dynslicefiledesc, 'w')
        dynslicefile.write(slice)
        dynslicefile.flush()
        Ice.loadSlice('', ['-I' + Ice.getSliceDir(), dynslicefilepath])
        dynslicefile.close()
        os.remove(dynslicefilepath)

        import Murmur
        if bot.config.mumble_secret:
            ice.getImplicitContext().put("secret", str(bot.config.mumble_secret))
        _server = Murmur.ServerPrx.checkedCast(prx)
        _meta = Murmur.MetaPrx.checkedCast(prx_meta)
        bot.mumbleannounce = lambda msg: _server.sendMessageChannel(0,True,msg)
    except Exception, e:
        print str(e)
Example #12
0
def connect():
    global status
    global ic
    global impl

    print "Connecting.."
    status = 0
    try:
        # Reading configuration info 
        configPath = os.environ.get("INTROOT")
        #print configPath
        #configPath = configPath + "/config/API-client.config"
        configPath = "./API-client.config"
        initData = Ice.InitializationData()
        initData.properties = Ice.createProperties()
        initData.properties.load(configPath)
        ic = Ice.initialize(sys.argv, initData)

        # Create proxy
        properties = ic.getProperties();
        proxyProperty = "APIAdapter.Proxy"
        proxy = properties.getProperty(proxyProperty);
        print "proxy=" + proxy
        obj = ic.stringToProxy(proxy);
        impl = ARIAPI.APIPrx.checkedCast(obj)
        print "Connected to ARI API Server"
        if not impl:
            raise RuntimeError("Invalid proxy")
    except:
       traceback.print_exc()
       status = 1
       sys.exit(status)
Example #13
0
    def connect(self, host = "127.0.0.1", port = 6502, secret = None, prxstr = None):
        if self.__ice:
            self.__log.warning("Connection attempt with tainted object, disconnect first")
            return True
        
        if not prxstr:
            prxstr = "Meta:tcp -h %s -p %d -t 1000" % (host, port)
        
        self.__log.info("Connecting to proxy: %s", prxstr)
            
        props = Ice.createProperties(sys.argv)
        props.setProperty("Ice.ImplicitContext", "Shared")
        
        idata = Ice.InitializationData()
        idata.properties = props
        
        ice = Ice.initialize(idata)
        self.__ice = ice

        if secret:
            ice.getImplicitContext().put("secret", secret)
            
        prx = ice.stringToProxy(prxstr)
        self.__prx = prx
        
        self.__log.debug("Retrieve version from target host")
        try:
            version = IcePy.Operation('getVersion', Ice.OperationMode.Idempotent, Ice.OperationMode.Idempotent, True, (), (), (((), IcePy._t_int), ((), IcePy._t_int), ((), IcePy._t_int), ((), IcePy._t_string)), None, ()).invoke(prx, ((), None))
            major, minor, patch, text = version
            self.__log.debug("Server version is %s", str(version))
        except Exception, e:
            self.__log.critical("Failed to retrieve version from target host")
            self.__log.exception(e)
            return False
Example #14
0
 def _setup_communicator(self, host, port):
     init = Ice.InitializationData()
     init.properties = Ice.createProperties()
     loc = "IceGrid/Locator:tcp -h "+ host + " -p " + str(port)
     init.properties.setProperty('Ice.Default.Locator', loc)
     init.properties.setProperty('Ice.IPv6', '0')
     return Ice.initialize(init)
Example #15
0
File: user.py Project: pedia/stuff
def init_oce_communicator():
    """ default client communicator """
    initData = Ice.InitializationData()
    initData.properties = Ice.createProperties(None, initData.properties)

    kv = [
        ("Ice.Override.ConnectTimeout", "300"),
        # ("IceGrid.InstanceName", "XiaoNei"),
        ("Ice.ThreadPool.Client.StackSize", "65535"),
        # ("Ice.ThreadPool.Server.StackSize", "65535"),
        ("Ice.MessageSizeMax", "20480"),
        # ("Ice.Trace.Network", "5"),
        # ("Ice.Trace.Location", "5"),
        # ("Ice.Trace.Locator", "5"),
        # ("Ice.Trace.Protocol", "5"),
        # ("Ice.Trace.GC", "5"),
        # TODO: ("Ice.Default.Host", ''),
        (
            "Ice.Default.Locator",
            "XiaoNei/Locator:default -h XiaoNeiRegistry -p 12000:default -h XiaoNeiRegistryReplica1 -p 12001:default -h XiaoNeiRegistryReplica2 -p 12002",
        ),
    ]
    for k, v in kv:
        initData.properties.setProperty(k, v)

    oce_ic = Ice.initialize(None, initData)
    return oce_ic
Example #16
0
	def connect(self):
		#client connection routine to server
		#global statusIC
		#global ic
		#global controller
		self.statusIC = 0
		try:
			# Reading configuration info
			#configPath = os.environ.get("SWROOT")
			#configPath = configPath + "/config/LCU-config"
			initData = Ice.InitializationData()
			initData.properties = Ice.createProperties()
			#initData.properties.load('IceConfig')
			self.ic = Ice.initialize(sys.argv, initData)
			# Create proxy
			#base = ic.stringToProxy("SRTController:default -h 192.168.0.6 -p 10000")
			base = self.ic.stringToProxy(self.IP_string)
			self.controller = SRTControl.telescopePrx.checkedCast(base)
			self.controller.begin_message("connected to controller", self.genericCB, self.failureCB);
			self.controller.begin_SRTGetName(self.getNameCB, self.failureCB)
			print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())+" " +"Connecting to SRTController"
			self.controller.begin_serverState(self.serverCB, self.failureCB);
			Status_Thread = threading.Thread(target = self.status_thread, name='status')
			print "starting status thread"
			Status_Thread.start()
			self.disableSpectrum()
			if not self.controller:
				raise RuntimeError("Invalid proxy")
		except:
			traceback.print_exc()
			self.statusIC = 1
			sys.exit(self.statusIC)
		return
Example #17
0
	def __init__(self, slicePath, sliceOpts=''):
		self.slicePath = slicePath
		self.sliceOpts = sliceOpts
		self.RoboComps = dict()

		loadCommand = self.sliceOpts+' '+self.slicePath
		print 'Loading SLICE file: "'+loadCommand+'"'
		print '1'
		modulesA = [ module for module in sys.modules ]
		print '2'
		try:
			print '3', loadCommand
			Ice.loadSlice(loadCommand)
			print '4'

			modulesB = [ module for module in sys.modules ]
			newModules = [ module for module in modulesB if not module in modulesA ]

			for newModule in newModules:
				print '  New module: ' + newModule
				self.RoboComps[str(newModule)] = __import__(newModule)
			try:
				global global_ic
				global_ic = Ice.initialize(sys.argv)
			except:
				print '  global_ic'
		except:
			traceback.print_exc(file=sys.stdout)
			print 'Error loading ' + loadCommand + '.'
		finally:
			print 'Done loading ' + self.slicePath + '.'
Example #18
0
 def __init__(self):
     try:
         Ice.loadSlice(self.settings['ice_file'])
         import Murmur
         self.mur = Murmur
     except:
         pass
Example #19
0
	def connect(self, IP):
		""" Connects to Observing Mode server
		IP: is the Observing Mode server IP and port
		example: connect(‘192.168.3.100 -p 10015’)
		"""
		#clcdient connection routine to server
		#global statusIC
		#global ic
		#global controller
		statusIC = 0
		try:
			# Reading configuration info
			#configPath = os.environ.get("SWROOT")
			#configPath = configPath + "/config/LCU-config"
			initData = Ice.InitializationData()
			initData.properties = Ice.createProperties()
			#initData.properties.load('IceConfig')
			self.ic = Ice.initialize(sys.argv, initData)
			# Create proxy
			#base = ic.stringToProxy("SRTController:default -h 192.168.0.6 -p 10000")
			IP_string = "ARIAPI:default -h " + IP
			base = self.ic.stringToProxy(IP_string)
			self.controller = ARIAPI.APIPrx.checkedCast(base)
			self.controller.begin_testConn("connected to observing mode server", self.connectCB, self.failureCB);
			print "Connecting to ARIAPI"
			#self.controller.begin_serverState(self.serverCB, self.failureCB);
			if not self.controller:
				raise RuntimeError("Invalid proxy")
		except:
			traceback.print_exc()
			self.statusIC = 1
			sys.exit(statusIC)
		return
Example #20
0
File: main.py Project: copton/lethe
    def run(self, argv):
        properties = self.communicator().getProperties()
        path = properties.getProperty("Breeze.Path")
        filename = properties.getProperty("Breeze.FileName")
        extension = properties.getProperty("Breeze.FileExtension")
        theLogger = logger.Logger(path, filename, extension)

        publish = logger.Publish(theLogger)
        lastlog = logger.Lastlog(theLogger)

        adapter = self.communicator().createObjectAdapter("BreezeAdapter")
        
        publishId = Ice.stringToIdentity("Publish")
        lastlogId = Ice.stringToIdentity("Lastlog")
        
        adapter.add(publish, publishId)
        adapter.add(lastlog, lastlogId)

        publishPrx = adapter.createDirectProxy(publishId)
        lastlogPrx = adapter.createDirectProxy(lastlogId)
        
        adapter.activate()

        text = "server started\n%s\n%s" % (publishPrx.ice_toString(), lastlogPrx.ice_toString())
        publish.log(text)
        self.communicator().waitForShutdown()
        publish.log("server shutting down")
 def __hash__(self):
     _h = 0
     _h = 5 * _h + Ice.getHash(self.interest)
     _h = 5 * _h + Ice.getHash(self.moneyProvided)
     _h = 5 * _h + Ice.getHash(self.moneyEarned)
     _h = 5 * _h + Ice.getHash(self.monthsLeft)
     return _h % 0x7fffffff
 def __hash__(self):
     _h = 0
     _h = 5 * _h + Ice.getHash(self.firstName)
     _h = 5 * _h + Ice.getHash(self.lastName)
     _h = 5 * _h + Ice.getHash(self.nationality)
     _h = 5 * _h + Ice.getHash(self.nationalIDNumber)
     return _h % 0x7fffffff
Example #23
0
 def connect(self):
     # client connection routine to server
     global status
     global ic
     global controller
     status = 0
     try:
         # Reading configuration info
         # configPath = os.environ.get("SWROOT")
         # configPath = configPath + "/config/LCU-config"
         initData = Ice.InitializationData()
         initData.properties = Ice.createProperties()
         initData.properties.load("IceConfig")
         ic = Ice.initialize(sys.argv, initData)
         # Create proxy
         # base = ic.stringToProxy("SHController:default -h 192.168.0.6 -p 10002")
         base = ic.stringToProxy(self.IP_string)
         controller = SHControl.SignalHoundPrx.checkedCast(base)
         controller.begin_message("connected to controller", self.genericCB, self.failureCB)
         print "Connecting to SHController"
         # controller.begin_serverState(self.serverCB, self.failureCB);
         if not controller:
             raise RuntimeError("Invalid proxy")
     except:
         traceback.print_exc()
         status = 1
         sys.exit(status)
     return
 def __hash__(self):
     _h = 0
     _h = 5 * _h + Ice.getHash(self.interest)
     _h = 5 * _h + Ice.getHash(self.paid)
     _h = 5 * _h + Ice.getHash(self.toPay)
     _h = 5 * _h + Ice.getHash(self.monthsLeft)
     return _h % 0x7fffffff
Example #25
0
def load_slice_files(icedir=os.path.normpath("../../Ice")):
    """
    Load slice files. This can be done dynamically in Python. Note that this requires
    the ICEROOT environment variable to be (correctly) set.
    """
    import Ice;
    
    # The following line throws an exception if ICEROOT is not an environment variable:
    iceroot = os.environ["ICEROOT"];
    if not iceroot:
        print "WARNING: ICEROOT is not defined! It's required to load slice files dynamically!";
    
    def create_load_string(target_file):
        """
        Create a string which loads Slice definition files.
        @param target_file File to load.
        @return Formatted string.
        """
        return "-I\"%s/slice\" -I\"%s\" --all %s/%s" % (
            iceroot, icedir, icedir, target_file);
    
    ice_files = [ file for file in os.listdir(icedir) if file.endswith(".ice") ];
    for file in ice_files:
        debug_reporter("Loading %s..." % file);
        Ice.loadSlice(create_load_string(file));
Example #26
0
    def run(self, args):
        properties = self.createTestProperties(args)
        properties.setProperty("Ice.Warn.Connections", "0")

        #
        # The client sends large messages to cause the transport
        # buffers to fill up.
        #
        properties.setProperty("Ice.MessageSizeMax", "10000")

        #
        # Limit the recv buffer size, this test relies on the socket
        # send() blocking after sending a given amount of data.
        #
        properties.setProperty("Ice.TCP.RcvSize", "50000")

        with self.initialize(properties=properties) as communicator:
            communicator.getProperties().setProperty("TestAdapter.Endpoints", self.getTestEndpoint())
            communicator.getProperties().setProperty("ControllerAdapter.Endpoints", self.getTestEndpoint(num=1))
            communicator.getProperties().setProperty("ControllerAdapter.ThreadPool.Size", "1")

            adapter = communicator.createObjectAdapter("TestAdapter")
            adapter.add(TimeoutI(), Ice.stringToIdentity("timeout"))
            adapter.activate()

            controllerAdapter = communicator.createObjectAdapter("ControllerAdapter")
            controllerAdapter.add(ControllerI(adapter), Ice.stringToIdentity("controller"))
            controllerAdapter.activate()

            communicator.waitForShutdown()
Example #27
0
    def run(self, args):

        initData = Ice.InitializationData()
        initData.properties = self.createTestProperties(args)

        with self.initialize(initData=initData) as communicator:
            #
            # Register the server manager. The server manager creates a new
            # 'server' (a server isn't a different process, it's just a new
            # communicator and object adapter).
            #
            communicator.getProperties().setProperty("Ice.ThreadPool.Server.Size", "2")
            communicator.getProperties().setProperty("ServerManager.Endpoints", self.getTestEndpoint())

            adapter = communicator.createObjectAdapter("ServerManager")

            #
            # We also register a sample server locator which implements the
            # locator interface, this locator is used by the clients and the
            # 'servers' created with the server manager interface.
            #
            registry = ServerLocatorRegistry()
            registry.addObject(adapter.createProxy(Ice.stringToIdentity("ServerManager")))
            adapter.add(ServerManagerI(registry, initData, self), Ice.stringToIdentity("ServerManager"))

            registryPrx = Ice.LocatorRegistryPrx.uncheckedCast(adapter.add(registry, Ice.stringToIdentity("registry")))

            locator = ServerLocator(registry, registryPrx)
            adapter.add(locator, Ice.stringToIdentity("locator"))

            adapter.activate()
            communicator.waitForShutdown()
Example #28
0
	def connect(self, IP):
		#client connection routine to server
		#global statusIC
		#global ic
		#global controller
		statusIC = 0
		try:
			# Reading configuration info
			#configPath = os.environ.get("SWROOT")
			#configPath = configPath + "/config/LCU-config"
			initData = Ice.InitializationData()
			initData.properties = Ice.createProperties()
			#initData.properties.load('IceConfig')
			ic = Ice.initialize(sys.argv, initData)
			# Create proxy
			#base = ic.stringToProxy("SRTController:default -h 192.168.0.6 -p 10000")
			IP_string = "SRTClient:default -h " + IP
			base = ic.stringToProxy(IP_string)
			controller = SRTClient.ClientPrx.checkedCast(base)
			controller.begin_message("connected to client", self.genericCB, self.failureCB);
			print "Connecting to SRTClient"
			#self.controller.begin_serverState(self.serverCB, self.failureCB);
			if not controller:
				raise RuntimeError("Invalid proxy")
		except:
			traceback.print_exc()
			self.statusIC = 1
			sys.exit(statusIC)
		return controller
Example #29
0
 def run(self, args):
     with self.initialize(args=args) as communicator:
         communicator.getProperties().setProperty("TestAdapter.Endpoints", self.getTestEndpoint())
         adapter = communicator.createObjectAdapter("TestAdapter")
         adapter.add(CustomI(), Ice.stringToIdentity("test"))
         if hasNumPy:
             adapter.add(NumPyCustomI(), Ice.stringToIdentity("test.numpy"))
         adapter.activate()
         communicator.waitForShutdown()
Example #30
0
    def run(sef, args):
        sys.stdout.write("testing load properties from UTF-8 path... ")
        sys.stdout.flush()
        properties = Ice.createProperties()
        properties.load("./config/中国_client.config")
        test(properties.getProperty("Ice.Trace.Network") == "1")
        test(properties.getProperty("Ice.Trace.Protocol") == "1")
        test(properties.getProperty("Config.Path") == "./config/中国_client.config")
        test(properties.getProperty("Ice.ProgramName") == "PropertiesClient")
        print("ok")

        sys.stdout.write("testing load properties from UTF-8 path using Ice::Application... ")
        sys.stdout.flush()
        app = App()
        app.main(args, "./config/中国_client.config")
        print("ok")

        sys.stdout.write("testing using Ice.Config with multiple config files... ")
        sys.stdout.flush()
        properties = Ice.createProperties(["--Ice.Config=config/config.1, config/config.2, config/config.3"])
        test(properties.getProperty("Config1") == "Config1")
        test(properties.getProperty("Config2") == "Config2")
        test(properties.getProperty("Config3") == "Config3")
        print("ok")

        sys.stdout.write("testing configuration file escapes... ")
        sys.stdout.flush()
        properties = Ice.createProperties(["--Ice.Config=config/escapes.cfg"])

        props = {
            "Foo\tBar": "3",
            "Foo\\tBar": "4",
            "Escape\\ Space": "2",
            "Prop1": "1",
            "Prop2": "2",
            "Prop3": "3",
            "My Prop1": "1",
            "My Prop2": "2",
            "My.Prop1": "a property",
            "My.Prop2": "a     property",
            "My.Prop3": "  a     property  ",
            "My.Prop4": "  a     property  ",
            "My.Prop5": "a \\ property",
            "foo=bar": "1",
            "foo#bar": "2",
            "foo bar": "3",
            "A": "1",
            "B": "2 3 4",
            "C": "5=#6",
            "AServer": "\\\\server\\dir",
            "BServer": "\\server\\dir"
        }

        for k in props.keys():
            test(properties.getProperty(k) == props[k])
        print("ok")
Example #31
0
 def getObject(self, id):
     if id not in self._objects:
         raise Ice.ObjectNotFoundException()
     return self._objects[id]
Example #32
0
 def iGetIdentity(self):
     _id = Ice.Identity()
     _id.name = self._uuid
     _id.category = self._category
     return _id
Example #33
0
 def __init__(self):
     self.delegate = Ice.initialize()
     for of in ObjectFactories.values():
         of.register(self.delegate)  # Columns
Example #34
0
#!/usr/bin/env python
#
# Copyright (c) ZeroC, Inc. All rights reserved.
#

import sys
import Ice

slice_dir = Ice.getSliceDir()
if not slice_dir:
    print(sys.argv[0] + ': Slice directory not found.')
    sys.exit(1)

Ice.loadSlice("'-I" + slice_dir + "' Props.ice")
import Demo


def run(communicator):
    props = Demo.PropsPrx.checkedCast(
        communicator.propertyToProxy("Props.Proxy"))
    if props is None:
        print("invalid proxy")
        return 1

    admin = Ice.PropertiesAdminPrx.checkedCast(
        communicator.propertyToProxy("Admin.Proxy"))

    batch1 = {}
    batch1["Demo.Prop1"] = "1"
    batch1["Demo.Prop2"] = "2"
    batch1["Demo.Prop3"] = "3"
Example #35
0
#    You should have received a copy of the GNU General Public License
#    along with RoboComp.  If not, see <http://www.gnu.org/licenses/>.
import sys, Ice, os
from PySide2 import QtWidgets, QtCore

ROBOCOMP = ''
try:
    ROBOCOMP = os.environ['ROBOCOMP']
except KeyError:
    print(
        '$ROBOCOMP environment variable not set, using the default value /opt/robocomp'
    )
    ROBOCOMP = '/opt/robocomp'

preStr = "-I/opt/robocomp/interfaces/ -I" + ROBOCOMP + "/interfaces/ --all /opt/robocomp/interfaces/"
Ice.loadSlice(preStr + "CommonBehavior.ice")
import RoboCompCommonBehavior

additionalPathStr = ''
icePaths = ['/opt/robocomp/interfaces']
try:
    SLICE_PATH = os.environ['SLICE_PATH'].split(':')
    for p in SLICE_PATH:
        icePaths.append(p)
        additionalPathStr += ' -I' + p + ' '
    icePaths.append('/opt/robocomp/interfaces')
except:
    print(
        'SLICE_PATH environment variable was not exported. Using only the default paths'
    )
    pass
Example #36
0
 def __init__(self, adapter, adapter2, registry):
     self._adapter1 = adapter
     self._adapter2 = adapter2
     self._registry = registry
     self._registry.addObject(
         self._adapter1.add(HelloI(), Ice.stringToIdentity("hello")))
Example #37
0
#
#    You should have received a copy of the GNU General Public License
#    along with RoboComp.  If not, see <http://www.gnu.org/licenses/>.

import sys, Ice, os
from PySide import *

ROBOCOMP = ''
try:
    ROBOCOMP = os.environ['ROBOCOMP']
except KeyError:
    print '$ROBOCOMP environment variable not set, using the default value /opt/robocomp'
    ROBOCOMP = '/opt/robocomp'

preStr = "-I/opt/robocomp/interfaces/ -I" + ROBOCOMP + "/interfaces/ --all /opt/robocomp/interfaces/"
Ice.loadSlice(preStr + "CommonBehavior.ice")
import RoboCompCommonBehavior

preStr = "-I/opt/robocomp/interfaces/ -I" + ROBOCOMP + "/interfaces/ --all /opt/robocomp/interfaces/"
Ice.loadSlice(preStr + "TripodController.ice")
from RoboCompTripController import *
preStr = "-I/opt/robocomp/interfaces/ -I" + ROBOCOMP + "/interfaces/ --all /opt/robocomp/interfaces/"
Ice.loadSlice(preStr + "JointMotor.ice")
from RoboCompJointMotor import *

from tripodcontrollerI import *


class GenericWorker(QtCore.QObject):
    kill = QtCore.Signal()
Example #38
0
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************

import os, sys, traceback

import Ice
Ice.loadSlice('Test.ice')
import Test, AllTests


def run(args, communicator):
    custom = AllTests.allTests(communicator)
    custom.shutdown()
    return True


try:
    with Ice.initialize(sys.argv) as communicator:
        status = run(sys.argv, communicator)
except:
    traceback.print_exc()
    status = False

sys.exit(not status)
   /*
   **   Generated by blitz/resources/templates/combined.vm
   **
   **   Copyright 2007, 2008 Glencoe Software, Inc. All rights reserved.
   **   Use is subject to license terms supplied in LICENSE.txt
   **
   */
"""
import Ice
import IceImport
import omero
IceImport.load("omero_model_DetailsI")
IceImport.load("omero_model_Namespace_ice")
from omero.rtypes import rlong
from collections import namedtuple
_omero = Ice.openModule("omero")
_omero_model = Ice.openModule("omero.model")
__name__ = "omero.model"


class NamespaceI(_omero_model.Namespace):

    # Property Metadata
    _field_info_data = namedtuple("FieldData", ["wrapper", "nullable"])
    _field_info_type = namedtuple("FieldInfo", [
        "keywords",
        "multivalued",
        "display",
        "displayName",
        "annotationLinks",
        "name",
Example #40
0
            oldIc = self.__ic
            self.__ic = None

            # Only possible if improperly configured.
            if not oldIc:
                return

            if oldOa:
                try:
                    oldOa.deactivate()
                except Exception, e:
                    self.__logger.warning("While deactivating adapter: " +
                                          str(e.message))

            self.__previous = Ice.InitializationData()
            self.__previous.properties = oldIc.getProperties().clone()

            try:
                try:
                    self.getRouter(oldIc).destroySession()
                except Glacier2.SessionNotExistException:
                    # ok. We don't want it to exist
                    pass
                except Ice.ConnectionLostException:
                    # ok. Exception will always be thrown
                    pass
                except Ice.ConnectionRefusedException:
                    # ok. Server probably went down
                    pass
                except Ice.ConnectTimeoutException:
Example #41
0
# Generated by slice2py - DO NOT EDIT!
#

import Ice
Ice.updateModule("org")

# Modules:
import service_ice

# Submodules:
Example #42
0
    def _initData(self, id):
        """
        Initializes the current client via an Ice.InitializationData
        instance. This is called by all of the constructors, but may
        also be called on createSession(name, pass) if a previous
        call to closeSession() has nulled the Ice.Communicator.
        """

        if not id:
            raise omero.ClientError("No initialization data provided.")

        # Strictly necessary for this class to work
        self._optSetProp(id, "Ice.ImplicitContext", "Shared")
        if Ice.intVersion() >= 30600:
            self._optSetProp(id, "Ice.ACM.Client.Timeout",
                             str(omero.constants.ACMCLIENTTIMEOUT))
            self._optSetProp(id, "Ice.ACM.Client.Heartbeat",
                             str(omero.constants.ACMCLIENTHEARTBEAT))
        else:
            self._optSetProp(id, "Ice.ACM.Client", "0")
        self._optSetProp(id, "Ice.CacheMessageBuffers", "0")
        self._optSetProp(id, "Ice.RetryIntervals", "-1")
        self._optSetProp(id, "Ice.Default.EndpointSelection", "Ordered")
        self._optSetProp(id, "Ice.Default.PreferSecure", "1")
        self._optSetProp(id, "Ice.Plugin.IceSSL", "IceSSL:createIceSSL")

        if Ice.intVersion() >= 30600:
            if sys.platform == "darwin":
                self._optSetProp(id, "IceSSL.Ciphers", "NONE (DH_anon.*AES)")
            else:
                self._optSetProp(id, "IceSSL.Ciphers", "ADH")
        else:
            self._optSetProp(id, "IceSSL.Ciphers", "ADH")
        self._optSetProp(id, "IceSSL.VerifyPeer", "0")
        self._optSetProp(id, "IceSSL.Protocols", "tls1")

        # Setting block size
        self._optSetProp(id, "omero.block_size",
                         str(omero.constants.DEFAULTBLOCKSIZE))

        # Set the default encoding if this is Ice 3.5 or later
        # and none is set.
        if Ice.intVersion() >= 30500:
            self._optSetProp(id, "Ice.Default.EncodingVersion", "1.0")

        # Setting MessageSizeMax
        self._optSetProp(id, "Ice.MessageSizeMax",
                         str(omero.constants.MESSAGESIZEMAX))

        # Setting ConnectTimeout
        self.parseAndSetInt(id, "Ice.Override.ConnectTimeout",
                            omero.constants.CONNECTTIMEOUT)

        # Set large thread pool max values for all communicators
        for x in ("Client", "Server"):
            sizemax = id.properties.getProperty("Ice.ThreadPool.%s.SizeMax" %
                                                x)
            if not sizemax or len(sizemax) == 0:
                id.properties.setProperty("Ice.ThreadPool.%s.SizeMax" % x,
                                          "50")

        # Port, setting to default if not present
        port = self.parseAndSetInt(id, "omero.port",
                                   omero.constants.GLACIER2PORT)

        # Default Router, set a default and then replace
        router = id.properties.getProperty("Ice.Default.Router")
        if not router or len(router) == 0:
            router = str(omero.constants.DEFAULTROUTER)
        host = id.properties.getPropertyWithDefault(
            "omero.host", """<"omero.host" not set>""")
        router = router.replace("@omero.port@", str(port))
        router = router.replace("@omero.host@", str(host))
        id.properties.setProperty("Ice.Default.Router", router)

        # Dump properties
        dump = id.properties.getProperty("omero.dump")
        if len(dump) > 0:
            m = self.getPropertyMap(id.properties)
            keys = list(m.keys())
            keys.sort()
            for key in keys:
                print "%s=%s" % (key, m[key])

        self.__lock.acquire()
        try:
            if self.__ic:
                raise omero.ClientError("Client already initialized")

            try:
                self.__ic = Ice.initialize(id)
            except Ice.EndpointParseException:
                msg = "No host specified. "
                msg += "Use omero.client(HOSTNAME), ICE_CONFIG, or similar."
                raise omero.ClientError(msg)

            if not self.__ic:
                raise omero.ClientError("Improper initialization")

            # Register Object Factory
            import ObjectFactoryRegistrar as ofr
            ofr.registerObjectFactory(self.__ic, self)

            for of in omero.rtypes.ObjectFactories.values():
                of.register(self.__ic)

            # Define our unique identifier (used during close/detach)
            self.__uuid = str(uuid.uuid4())
            ctx = self.__ic.getImplicitContext()
            if not ctx:
                raise omero.ClientError(
                    "Ice.ImplicitContext not set to Shared")
            ctx.put(omero.constants.CLIENTUUID, self.__uuid)

            # ticket:2951 - sending user group
            group = id.properties.getPropertyWithDefault("omero.group", "")
            if group:
                ctx.put("omero.group", group)

        finally:
            self.__lock.release()
Example #43
0
    def __init__(self, args=None, id=None, host=None, port=None, pmap=None):
        """
        Constructor which takes one sys.argv-style list, one initialization
        data, one host string, one port integer, and one properties map, in
        that order. *However*, to simplify use, we reassign values based on
        their type with a warning printed. A cleaner approach is to use named
        parameters.
        ::
            c1 = omero.client(None, None, "host", myPort)   # Correct
            c2 = omero.client(host = "host", port = myPort) # Correct
            # Works with warning
            c3 = omero.client("host", myPort)

        Both "Ice" and "omero" prefixed properties will be parsed.

        Defines the state variables::
            __previous : InitializationData from any previous communicator, if
                         any. Used to re-initialization the client
                         post-closeSession()

            __ic       : communicator. Nullness => init() needed on
                         createSession()

            __sf       : current session. Nullness => createSession() needed.

            __resources: if non-null, hs access to this client instance and
                         will periodically call sf.keepAlive(None) in order to
                         keep any session alive. This can be enabled either
                         via the omero.keep_alive configuration property, or
                         by calling the enableKeepAlive() method.
                         Once enabled, the period cannot be adjusted during a
                         single session.

        Modifying these variables outside of the accessors can lead to
        undefined behavior.

        Equivalent to all OmeroJava and OmeroCpp constructors
        """

        # Setting all protected values to prevent AttributeError
        self.__agent = "OMERO.py"  #: See setAgent
        self.__ip = None  #: See setIP
        self.__insecure = False
        self.__previous = None
        self.__ic = None
        self.__oa = None
        self.__cb = None
        self.__sf = None
        self.__uuid = None
        self.__resources = None
        self.__lock = threading.RLock()

        # Logging
        self.__logger = logging.getLogger("omero.client")
        logging.basicConfig()  # Does nothing if already configured

        # Reassigning based on argument type

        args, id, host, port, pmap = self._repair(args, id, host, port, pmap)

        # Copying args since we don't really want them edited
        if not args:
            args = []
        else:
            # See ticket:5516 To prevent issues on systems where the base
            # class of path.path is unicode, we will encode all unicode
            # strings here.
            for idx, arg in enumerate(args):
                if isinstance(arg, unicode):
                    arg = arg.encode("utf-8")
                args[idx] = arg

        # Equiv to multiple constructors. #######################
        if id is None:
            id = Ice.InitializationData()

        if id.properties is None:
            id.properties = Ice.createProperties(args)

        id.properties.parseCommandLineOptions("omero", args)
        if host:
            id.properties.setProperty("omero.host", str(host))
        if not port:
            port = id.properties.getPropertyWithDefault(
                "omero.port", str(omero.constants.GLACIER2PORT))
        id.properties.setProperty("omero.port", str(port))
        if pmap:
            for k, v in pmap.items():
                id.properties.setProperty(str(k), str(v))

        self._initData(id)
Example #44
0
    def createSession(self, username=None, password=None):
        """
        Performs the actual logic of logging in, which is done via the
        getRouter(). Disallows an extant ServiceFactoryPrx, and
        tries to re-create a null Ice.Communicator. A null or empty
        username will throw an exception, but an empty password is allowed.
        """
        import omero

        self.__lock.acquire()
        try:

            # Checking state

            if self.__sf:
                raise omero.ClientError(
                    "Session already active. "
                    "Create a new omero.client or closeSession()")

            if not self.__ic:
                if not self.__previous:
                    raise omero.ClientError(
                        "No previous data to recreate communicator.")
                self._initData(self.__previous)
                self.__previous = None

            # Check the required properties

            if not username:
                username = self.getProperty("omero.user")
            elif isinstance(username, omero.RString):
                username = username.val

            if not username or len(username) == 0:
                raise omero.ClientError("No username specified")

            if not password:
                password = self.getProperty("omero.pass")
            elif isinstance(password, omero.RString):
                password = password.val

            if not password:
                raise omero.ClientError("No password specified")

            # Acquire router and get the proxy
            prx = None
            retries = 0
            while retries < 3:
                reason = None
                if retries > 0:
                    self.__logger.warning("%s - createSession retry: %s" %
                                          (reason, retries))
                try:
                    ctx = self.getContext()
                    ctx[omero.constants.AGENT] = self.__agent
                    if self.__ip is not None:
                        ctx[omero.constants.IP] = self.__ip
                    rtr = self.getRouter(self.__ic)
                    prx = rtr.createSession(username, password, ctx)

                    # Create the adapter
                    self.__oa = self.__ic.createObjectAdapterWithRouter(
                        "omero.ClientCallback", rtr)
                    self.__oa.activate()

                    id = Ice.Identity()
                    id.name = self.__uuid
                    id.category = rtr.getCategoryForClient()

                    self.__cb = BaseClient.CallbackI(self.__ic, self.__oa, id)
                    self.__oa.add(self.__cb, id)

                    break
                except omero.WrappedCreateSessionException, wrapped:
                    if not wrapped.concurrency:
                        raise wrapped  # We only retry concurrency issues.
                    reason = "%s:%s" % (wrapped.type, wrapped.reason)
                    retries = retries + 1
                except Ice.ConnectTimeoutException, cte:
                    reason = "Ice.ConnectTimeoutException:%s" % str(cte)
                    retries = retries + 1
Example #45
0
 def getAdapter(self, adapter):
     if adapter not in self._adapters:
         raise Ice.AdapterNotFoundException()
     return self._adapters[adapter]
Example #46
0
 def asyncException_async(self, cb, current=None):
     cb.ice_exception(Test.TestIntfUserException())
     raise Ice.ObjectNotExistException()
Example #47
0
 def getReplicatedHello(self, current=None):
     return Test.HelloPrx.uncheckedCast(
         self._adapter1.createProxy(Ice.stringToIdentity("hello")))
Example #48
0
 def asyncResponse_async(self, cb, current=None):
     cb.ice_response()
     raise Ice.ObjectNotExistException()
Example #49
0
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************

import os, sys, traceback

import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
    print(sys.argv[0] + ': Slice directory not found.')
    sys.exit(1)

Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
import Test


class ServerLocatorRegistry(Test.TestLocatorRegistry):
    def __init__(self):
        self._adapters = {}
        self._objects = {}

    def setAdapterDirectProxy(self, adapter, obj, current=None):
        if obj:
            self._adapters[adapter] = obj
        else:
Example #50
0
 def unknownExceptionWithServantException_async(self, cb, current=None):
     cb.ice_exception(Ice.ObjectNotExistException())
Example #51
0
import sys, traceback, Ice
import Demo

status = 0
ic = None

try:
    ic = Ice.initialize(sys.argv)
    base = ic.stringToProxy("SimplePrinter:default -p 10000")
    printer = Demo.PrinterPrx.checkedCast(base)
    if not printer:
        raise RuntimeError("Invalid proxy")
    printer.printString("Hello, World!")
except:
    traceback.print_exc()
    status = 1

if ic:
    try:
        ic.destroy()
    except:
        traceback.print_exc()
        status = 1

sys.exit(status)
# Ice version 3.6.1
#
# <auto-generated>
#
# Generated from file `PermissionsVerifier.ice'
#
# Warning: do not edit this file.
#
# </auto-generated>
#

import Ice, IcePy
import Glacier2_SSLInfo_ice

# Included module Ice
_M_Ice = Ice.openModule('Ice')

# Included module Glacier2
_M_Glacier2 = Ice.openModule('Glacier2')

# Start of module Glacier2
__name__ = 'Glacier2'

if 'PermissionDeniedException' not in _M_Glacier2.__dict__:
    _M_Glacier2.PermissionDeniedException = Ice.createTempClass()

    class PermissionDeniedException(Ice.UserException):
        '''This exception is raised if a client is denied the ability to create
a session with the router.'''
        def __init__(self, reason=''):
            self.reason = reason
Example #53
0
#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-

import sys
import Ice

Ice.loadSlice('./factorial.ice')
import Example


def factorial(n):
    if n == 0:
        return 1

    return n * factorial(n - 1)


class MathI(Example.Math):
    def factorial(self, n, current=None):
        return factorial(n)


class Server(Ice.Application):
    def run(self, argv):
        broker = self.communicator()

        adapter = broker.createObjectAdapter("MathAdapter")
        math = adapter.add(MathI(), broker.stringToIdentity("math1"))

        print math
Example #54
0
def batchOneways(p):

    if sys.version_info[0] == 2:
        bs1 = []
        bs1[0:10 * 1024] = range(0, 10 * 1024)  # add 100,000 entries.
        bs1 = ['\x00' for x in bs1]  # set them all to \x00
        bs1 = ''.join(bs1)  # make into a byte array
    else:
        bs1 = bytes([0 for x in range(0, 10 * 1024)])

    try:
        p.opByteSOneway(bs1)
    except Ice.MemoryLimitException:
        test(False)

    batch = Test.MyClassPrx.uncheckedCast(p.ice_batchOneway())

    batch.ice_flushBatchRequests()  # Empty flush
    if batch.ice_getConnection():
        batch.ice_getConnection().flushBatchRequests(
            Ice.CompressBatch.BasedOnProxy)
    batch.ice_getCommunicator().flushBatchRequests(
        Ice.CompressBatch.BasedOnProxy)

    p.opByteSOnewayCallCount()  # Reset the call count

    for i in range(30):
        batch.opByteSOneway(bs1)

    count = 0
    while count < 27:  # 3 * 9 requests auto-flushed.
        count += p.opByteSOnewayCallCount()
        time.sleep(0.01)

    if p.ice_getConnection():
        batch1 = Test.MyClassPrx.uncheckedCast(p.ice_batchOneway())
        batch2 = Test.MyClassPrx.uncheckedCast(p.ice_batchOneway())

        batch1.ice_ping()
        batch2.ice_ping()
        batch1.ice_flushBatchRequests()
        batch1.ice_getConnection().close(
            Ice.ConnectionClose.GracefullyWithWait)
        batch1.ice_ping()
        batch2.ice_ping()

        batch1.ice_getConnection()
        batch2.ice_getConnection()

        batch1.ice_ping()
        batch1.ice_getConnection().close(
            Ice.ConnectionClose.GracefullyWithWait)

        batch1.ice_ping()
        batch2.ice_ping()

    identity = Ice.Identity()
    identity.name = "invalid"
    batch3 = batch.ice_identity(identity)
    batch3.ice_ping()
    batch3.ice_flushBatchRequests()

    # Make sure that a bogus batch request doesn't cause troubles to other ones.
    batch3.ice_ping()
    batch.ice_ping()
    batch.ice_flushBatchRequests()
    batch.ice_ping()

    if batch.ice_getConnection():
        initData = Ice.InitializationData()
        initData.properties = p.ice_getCommunicator().getProperties().clone()
        interceptor = BatchRequestInterceptorI()
        initData.batchRequestInterceptor = interceptor

        ic = Ice.initialize(data=initData)

        batch = Test.MyClassPrx.uncheckedCast(
            ic.stringToProxy(p.ice_toString())).ice_batchOneway()

        test(interceptor.count() == 0)
        batch.ice_ping()
        batch.ice_ping()
        batch.ice_ping()
        test(interceptor.count() == 0)

        interceptor.setEnabled(True)
        batch.ice_ping()
        batch.ice_ping()
        batch.ice_ping()
        test(interceptor.count() == 3)

        batch.ice_flushBatchRequests()
        batch.ice_ping()
        test(interceptor.count() == 1)

        batch.opByteSOneway(bs1)
        test(interceptor.count() == 2)
        batch.opByteSOneway(bs1)
        test(interceptor.count() == 3)

        batch.opByteSOneway(bs1)  # This should trigger the flush
        batch.ice_ping()
        test(interceptor.count() == 2)

        ic.destroy()
Example #55
0
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************

import sys, os, traceback, threading, Ice

Ice.loadSlice('Hello.ice')
import Demo


class CallbackEntry(object):
    def __init__(self, cb, delay):
        self.cb = cb
        self.delay = delay


class WorkQueue(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._callbacks = []
        self._done = False
        self._cond = threading.Condition()

    def run(self):
        self._cond.acquire()
Example #56
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# **********************************************************************
#
# Authors: Cristian Gómez Portes, Pedro Gómez Martín
#
# **********************************************************************

import Ice
Ice.loadSlice('services.ice --all -I .')
import services
import drobots
import sys, time, random


class PlayerApp(Ice.Application):
    def run(self, argv):

        broker = self.communicator()

        #well-known object
        container_proxy = broker.stringToProxy('container')
        container = services.ContainerPrx.checkedCast(container_proxy)

        adapter = broker.createObjectAdapter('PlayerAdapter')
        adapter.activate()

        player_servant = PlayerI(broker, adapter, container)
        proxy_player = adapter.addWithUUID(player_servant)
        print('Proxy player: ' + str(proxy_player))
        direct_player = adapter.createDirectProxy(
Example #57
0
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
#
# **********************************************************************

import sys, traceback, Ice

Ice.loadSlice('Printer.ice')
import Demo


class PrinterI(Demo.Printer):
    def printString(self, s, current=None):
        print(s)


status = 0
ice = None
try:
    ic = Ice.initialize(sys.argv)
    adapter = ic.createObjectAdapterWithEndpoints(
        "SimplePrinterAdapter", "default -h localhost -p 10000")
    object = PrinterI()
    adapter.add(object, Ice.stringToIdentity("SimplePrinter"))
    adapter.activate()
    ic.waitForShutdown()
except:
    traceback.print_exc()
    status = 1
Example #58
0
#    along with RoboComp.  If not, see <http://www.gnu.org/licenses/>.
#
#

#
# CODE BEGINS
#
import sys, time, traceback, os, math, random, threading, time
import Ice

from PyQt4 import QtCore, QtGui, Qt
from ui_formManager import Ui_Form

import rcmanagerConfig

global_ic = Ice.initialize(sys.argv)

# Ctrl+c handling
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

dict = rcmanagerConfig.getDefaultValues()
initDir = os.getcwd()

sys.path.append('.')
sys.path.append('/opt/robocomp/bin')

import rcmanagerEditor


# CommandDialog class: It's the dialog sending "up()/down() component X signal to the main
 def __init__(self):
     if Ice.getType(self) == _M_Glacier2.PermissionsVerifier:
         raise RuntimeError(
             'Glacier2.PermissionsVerifier is an abstract class')
Example #60
0
#
# <auto-generated>
#
# Generated from file `SSLInfo.ice'
#
# Warning: do not edit this file.
#
# </auto-generated>
#

from sys import version_info as _version_info_
import Ice, IcePy
import Ice.BuiltinSequences_ice

# Included module Ice
_M_Ice = Ice.openModule('Ice')

# Start of module Glacier2
_M_Glacier2 = Ice.openModule('Glacier2')
__name__ = 'Glacier2'

if 'SSLInfo' not in _M_Glacier2.__dict__:
    _M_Glacier2.SSLInfo = Ice.createTempClass()

    class SSLInfo(object):
        """
        Information taken from an SSL connection used for permissions
        verification.
        Members:
        remoteHost -- The remote host.
        remotePort -- The remote port.