def setUp(self): self.ic = Ice.initialize() self.current = Ice.Current() self.current.adapter = MockAdapter(self.ic) for of in omero.columns.ObjectFactories.values(): of.register(self.ic)
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()
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 LSDindex(request): try: communicator=Ice.initialize() ServerDetect=Vistek.Device.DeviceWatchServicePrx.checkedCast(communicator.stringToProxy("DeviceWatching:tcp -h 172.16.0.122 -p 50001")) if not ServerDetect: raise RuntimeError("Invalid proxy") physicinfo=ServerDetect.GetPhysicInfo() # ServiceStatus=ServerDetect.isDeviceServiceOk() for info in physicinfo: cpu_Count=info.cpuinfovalue.cpuCount cpu_UseRate=info.cpuinfovalue.cpuUseRate physic_CpuCount=info.cpuinfovalue.physicCpuCount mem_Size=info.meminfovalue.memSize use_Mem=info.meminfovalue.useMem aviable_MemSize=info.meminfovalue.aviableMemSize mem_UseRate=info.meminfovalue.memUseRate register_SuccessCount=info.registerinfovalue.registerSuccessCount register_FailCount=info.registerinfovalue.registerFailCount register_SuccessDeviceList=info.registerinfovalue.registerSucccessDeviceList register_FaildDeviceList=info.registerinfovalue.registerFailDeviceList service_ID=info.serviceID print(service_ID) print(dir(physicinfo)) except: traceback.print_exc() sys.exit(1)
def status(self, args, node_only = False): self.check_node(args) command = self._cmd("-e","node ping master") #3141, TODO should be configurable self.ctx.rv = self.ctx.popen(command).wait() # popen # node_only implies that "up" need not check for all # of blitz to be accessible but just that if the node # is running. if not node_only: node_only = getattr(args, "nodeonly", False) if self.ctx.rv == 0 and not node_only: try: import Ice import omero_ServerErrors_ice ic = Ice.initialize([self._intcfg()]) try: sm = self.session_manager(ic) try: sm.create("####### STATUS CHECK ########", None) # Not adding "omero.client.uuid" except omero.WrappedCreateSessionException, wcse: # Only the server will throw one of these self.ctx.dbg("Server reachable") self.ctx.rv = 0 finally: ic.destroy() except exceptions.Exception, exc: self.ctx.rv = 1 self.ctx.dbg("Server not reachable: "+str(exc))
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
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)
def ice_server(): status = 0 ic = None try: ic = Ice.initialize(sys.argv) for adapter_point in IceAdapters: conn_params = IceAdapters[adapter_point]['conn'] adapter = ic.createObjectAdapterWithEndpoints( adapter_point, conn_params ) for meth in IceAdapters[adapter_point]['reg']: cls_, cls_str = meth adapter.add(cls_(), ic.stringToIdentity(cls_str)) adapter.activate() ic.waitForShutdown() except: traceback.print_exc() status = 1 if ic: try: ic.destroy() except: traceback.print_exc() status = 1 sys.exit(status)
def __init__(self, endpoint, modules): QWidget.__init__(self) self.ic = Ice.initialize(sys.argv) self.mods = modules self.prx = self.ic.stringToProxy(endpoint) self.proxy = self.mods['RoboCompDifferentialRobot'].DifferentialRobotPrx.checkedCast(self.prx) self.speedLabel = QLabel("Speed", self) self.speedLabel.show() self.speedLabel.move(5,8) self.steerLabel = QLabel('Steer', self) self.steerLabel.show() self.steerLabel.move(5,33) self.speed = QSpinBox(self) self.speed.setMaximum(1000) self.speed.setMinimum(-1000) self.speed.show() self.speed.setValue(0) self.speed.setSingleStep(25) self.speed.move(50,5) self.steer = QDoubleSpinBox(self) self.steer.setMaximum(3.14*10) self.steer.setMinimum(-3.14*10) self.steer.setSingleStep(0.05) self.steer.setValue(0) self.steer.move(50,30) self.steer.show() self.resetButton = QPushButton("reset", self) self.resetButton.move(5,55) self.resetButton.show() self.connect(self.resetButton, SIGNAL('clicked()'), self.reset) self.show() self.cmdSteer = 0. self.cmdSpeed = 0.
def __init__(self, endpoint, modules): QWidget.__init__(self) self.ic = Ice.initialize(sys.argv) self.mods = modules self.prx = self.ic.stringToProxy(endpoint) self.proxy = self.mods['RoboCompCubafeatures'].CubafeaturesPrx.checkedCast(self.prx) self.job()
def FrontendCalc(self, cmd, current=None): rtn = "" try: username = cmd.split(':')[1] try: server = self.unmap[username] except KeyError: return "Please login" ic = Ice.initialize(sys.argv) bebase = ic.stringToProxy("Parser:tcp -h "+server[0: server.find(":")]+".csc.ncsu.edu -p 10001") parser = Matcloud.ParserPrx.checkedCast(bebase) if not parser: raise RuntimeError("Invalid proxy") rtn = parser.command(cmd) print "received return string %s " % rtn except: traceback.print_exc() status = 1 if ic: try: ic.destroy() except: traceback.print_exc() return "Internal Error" return rtn
def openExtraChannel(): status = 0 ic = None Extra2Tx = ExtraI() try: ic = Ice.initialize(sys.argv) adapter = ic.createObjectAdapterWithEndpoints("ExtraAdapter", "default -p 9002") object = Extra2Tx adapter.add(object, ic.stringToIdentity("Extra")) adapter.activate() ic.waitForShutdown() except: traceback.print_exc() status = 1 if ic: # Clean up try: ic.destroy() except: traceback.print_exc() status = 1 sys.exit(status)
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, communicator.stringToIdentity("test"))) self._registry.addObject(adapter.add(object, communicator.stringToIdentity("test2"))) adapter.add(object, communicator.stringToIdentity("test3")) adapter.activate() adapter2.activate()
def __init__(self, endpoint, modules): QWidget.__init__(self) print "init" self.ui = Ui_HeadT2PDlg() self.ui.setupUi(self) self.t = 0. self.ic = Ice.initialize(sys.argv) self.mods = modules print "init2" self.prx = self.ic.stringToProxy(endpoint) print endpoint self.proxy = self.mods['RoboCompHeadT2P'].HeadT2PPrx.checkedCast(self.prx) print "init3" self.show() print "init4" #Init spinboxes values map = self.proxy.getHeadState() self.ui.sbLeftPan.setValue(map.motorsState["leftPan"].pos) self.ui.sbRightPan.setValue(map.motorsState["rightPan"].pos) self.ui.sbTilt.setValue(map.motorsState["tilt"].pos) self.connect( self.ui.pbSaccadic2DLeft, SIGNAL('clicked()'), self.doSaccadic2DLeft ) self.connect( self.ui.pbSaccadic2DRight, SIGNAL('clicked()'), self.doSaccadic2DRight ) self.connect( self.ui.pbSaccadic3D, SIGNAL('clicked()'), self.doSaccadic3D ) self.connect( self.ui.pbReset, SIGNAL('clicked()'), self.doReset ); self.job()
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
def __init__(self, endpoint, modules): print modules.keys() QWidget.__init__(self) print "init" self.ui = Ui_KinectDlg() self.ui.setupUi(self) #hide kinect interface options self.ui.sbTilt.hide() self.ui.pbSetLed.hide() self.ui.label_4.hide() self.ui.cbLedOpt.hide() self.t = 0. arg = sys.argv arg.append("--Ice.MessageSizeMax=2000000") self.ic = Ice.initialize(arg) self.mods = modules self.prx = self.ic.stringToProxy(endpoint) print "endpoint", endpoint print "prx", self.prx print self.mods.keys() print "ya" self.proxy = self.mods['RoboCompRGBD'].RGBDPrx.checkedCast(self.prx) print "yaya" self.show() self.lalala = 0 self.maxDepth = 9.0 self.job()
def connectToProxys(self): self.ic = Ice.initialize(sys.argv) # Contact to Motors Motors = self.ic.propertyToProxy('automata.Motors.Proxy') if(not Motors): raise Exception('could not create proxy with Motors') self.MotorsPrx = MotorsPrx.checkedCast(Motors) if(not self.MotorsPrx): raise Exception('invalid proxy automata.Motors.Proxy') print 'Motors connected' # Contact to Pose3D Pose3D = self.ic.propertyToProxy('automata.Pose3D.Proxy') if(not Pose3D): raise Exception('could not create proxy with Pose3D') self.Pose3DPrx = Pose3DPrx.checkedCast(Pose3D) if(not self.Pose3DPrx): raise Exception('invalid proxy automata.Pose3D.Proxy') print 'Pose3D connected' # Contact to Laser Laser = self.ic.propertyToProxy('automata.Laser.Proxy') if(not Laser): raise Exception('could not create proxy with Laser') self.LaserPrx = LaserPrx.checkedCast(Laser) if(not self.LaserPrx): raise Exception('invalid proxy automata.Laser.Proxy') print 'Laser connected'
def __init__(self, endpoint, modules): QWidget.__init__(self) self.Lista=list(); self.ic = Ice.initialize(sys.argv) self.mods = modules self.prx = self.ic.stringToProxy(endpoint) self.proxy = self.mods['RoboCompInnerModelManager'].InnerModelManagerPrx.checkedCast(self.prx) self.a = 0. self.check = QCheckBox("move", self) self.check.show() print "creation" first = 0 pose = self.mods['RoboCompInnerModelManager'].Pose3D() pose.x = 0 pose.y = 0 pose.z = 1000 self.proxy.addTransform("test_T", "static", "sensor_transform", pose); pose.x = 0 pose.y = 0 pose.z = 0 pose.rx = 1.57 mesh = self.mods['RoboCompInnerModelManager'].meshType() mesh.pose = pose mesh.scaleX = 100 mesh.scaleY = 100 mesh.scaleZ = 100; mesh.render = 0 mesh.meshPath = "/home/robocomp/robocomp/Files/osgModels/mobiliario/taza.osg"; self.proxy.addMesh("test", "test_T", mesh); self.show()
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)
def __init__(self): status = 0 ic = None # Initializing the Ice run-time. ic = Ice.initialize(sys.argv) properties = ic.getProperties() print properties print (".-------------------------------------------------") self.lock = threading.Lock() try: obj = ic.propertyToProxy("DetectorSSD.Camera.Proxy") print obj self.camera = jderobot.CameraPrx.checkedCast(obj) Labels = properties.getProperty("DetectorSSD.Labels") print Labels if self.camera: self.image = self.camera.getImageData("RGB8") self.height= self.image.description.height self.width = self.image.description.width else: print 'Interface camera not connected' except: traceback.print_exc() exit() status = 1 caffe.set_mode_cpu()
def openCMDVelChannel(CMDVel): status = 0 ic = None CMDVel2Rx = CMDVel #CMDVel.getCMDVelData() try: ic = Ice.initialize(sys.argv) adapter = ic.createObjectAdapterWithEndpoints("CMDVelAdapter", "default -p 9999") object = CMDVel2Rx print CMDVel2Rx adapter.add(object, ic.stringToIdentity("CMDVel")) adapter.activate() ic.waitForShutdown() except: traceback.print_exc() status = 1 if ic: # Clean up try: ic.destroy() except: traceback.print_exc() status = 1 sys.exit(status)
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 openPose3DChannel(Pose3D): status = 0 ic = None Pose2Tx = Pose3D #Pose3D.getPose3DData() try: ic = Ice.initialize(sys.argv) adapter = ic.createObjectAdapterWithEndpoints("Pose3DAdapter", "default -p 9998") object = Pose2Tx #print object.getPose3DData() adapter.add(object, ic.stringToIdentity("Pose3D")) adapter.activate() ic.waitForShutdown() except: traceback.print_exc() status = 1 if ic: # Clean up try: ic.destroy() except: traceback.print_exc() status = 1 sys.exit(status)
def get_context_data(self,**kwargs): context=super(IndexView,self).get_context_data(**kwargs) try: ResultType=Vistek.Perf.ResponseStringType.rstXml communicator=Ice.initialize() ServerDetect=Vistek.Perf.ServicePerfPrx.checkedCast(communicator.stringToProxy("DeviceServicePerf:tcp -h 172.16.0.20 -p 54321")) #ServerDetect=Vistek.Device.DeviceWatchServicePrx.checkedCast(communicator.stringToProxy("DeviceWatching:tcp -h 172.16.0.122 -p 50000")) if not ServerDetect: raise RuntimeError("Invalid proxy") result=ServerDetect.GetSumRate(ResultType) #result=ServerDetect.GetServiceRunningInfo() client_list=ServerDetect.GetAllClients() info="" for client in client_list: info += str(client.IP) info +=" " info += str(client.port) info += " " context['Result']=result context['info']=info communicator.destroy() except: traceback.print_exc() return context
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)
def run(self): # Thread.run # LOGGER.log("Starting CCastSlave") if self._ic != None: LOGGER.warn("... Warning: communicator already created.") return -1 status = 0 try: self._ic = Ice.initialize([]) # no sys.argv adapter = self._ic.createObjectAdapterWithEndpoints(self.name + "Adapter", self.address) obj = CAgentI(self.manager, self.options) adapter.add(obj, self._ic.stringToIdentity(self.name)) adapter.activate() self._ic.waitForShutdown() # No event loop here, just waiting for shutdown() except: LOGGER.error(traceback.format_exc(20)) status = 1 # Clean up try: if self._ic != None: self._ic.destroy() self._ic = None except: LOGGER.error(traceback.format_exc(20)) status = 1 return status
def __init__(self, cfg, deps): core.Subsystem.__init__(self, cfg.get('name', 'RemoteAi'), deps) self._connections = [] self.qeventHub = core.Subsystem.getSubsystemOfType(core.QueuedEventHub, deps) if self.qeventHub is None: raise Exception("Could not find QueuedEventHub in" " the dependencies.") conn = self.qeventHub.subscribeToType( ram.ai.state.Machine.STATE_ENTERED, self._onEntered) self._connections.append(conn) conn = self.qeventHub.subscribeToType( ram.ai.state.Machine.STATE_EXITED, self._onExited) self._connections.append(conn) self._eventList = [] self._firstRun = True self.ic = None try: self.ic = Ice.initialize(sys.argv) adapter = self.ic.createObjectAdapterWithEndpoints( "RemoteAi", "default -p 10000") self._obj = AiInformationImpl() adapter.add(self._obj, self.ic.stringToIdentity("AiInfo")) adapter.activate() except: traceback.print_exc()
def connectToProxys(self): self.ic = Ice.initialize(sys.argv) # Contact to Extra Extra = self.ic.propertyToProxy('automata.ArDroneExtra.Proxy') if(not Extra): raise Exception('could not create proxy with Extra') self.ExtraPrx = ArDroneExtraPrx.checkedCast(Extra) if(not self.ExtraPrx): raise Exception('invalid proxy automata.ArDroneExtra.Proxy') print 'Extra connected' # Contact to CMDVel CMDVel = self.ic.propertyToProxy('automata.CMDVel.Proxy') if(not CMDVel): raise Exception('could not create proxy with CMDVel') self.CMDVelPrx = CMDVelPrx.checkedCast(CMDVel) if(not self.CMDVelPrx): raise Exception('invalid proxy automata.CMDVel.Proxy') print 'CMDVel connected' # Contact to Camera Camera = self.ic.propertyToProxy('automata.Camera.Proxy') if(not Camera): raise Exception('could not create proxy with Camera') self.CameraPrx = CameraPrx.checkedCast(Camera) if(not self.CameraPrx): raise Exception('invalid proxy automata.Camera.Proxy') print 'Camera connected'
def __init__(self, config, name='Python client', exclusive=False): # TODO: use Ice configuration? port = int(config.get('Server', 'port')) hostname = config.get('Server', 'hostname') # Get SessionFactory to get Session, to get Manager self.ic = Ice.initialize(sys.argv) base = self.ic.stringToProxy("SessionFactory:default -h %s -p %d" % \ (hostname, port)) self.sessionFactory = SenStore.SessionFactoryPrx.checkedCast(base) if exclusive: self.session = self.sessionFactory.createSessionExclusive(name) else: self.session = self.sessionFactory.createSession(name) self.mngr = self.session.getManager() if not self.mngr: raise RuntimeError("Invalid manager proxy") base = self.ic.stringToProxy("Inspector:default -h %s -p %d" % \ (hostname, port)) # Get Inspector self.inspector = SenStore.Info.InspectorPrx.checkedCast(base) if not self.inspector: raise RuntimeError("Invalid inspector proxy") self.refresher = SessionRefresher(self.session) self.refresher.start()
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)
def allTests(communicator): sys.stdout.write("testing stringToProxy... ") sys.stdout.flush() base = communicator.stringToProxy("test:default -p 12010") test(base) print("ok") sys.stdout.write("testing checked cast... ") sys.stdout.flush() obj = Test.TestIntfPrx.checkedCast(base) test(obj) test(obj == base) print("ok") sys.stdout.write("creating/destroying/recreating object adapter... ") sys.stdout.flush() adapter = communicator.createObjectAdapterWithEndpoints( "TransientTestAdapter", "default") try: communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default") test(False) except Ice.LocalException: pass adapter.destroy() adapter = communicator.createObjectAdapterWithEndpoints( "TransientTestAdapter", "default") adapter.destroy() print("ok") sys.stdout.write( "creating/activating/deactivating object adapter in one operation... ") sys.stdout.flush() obj.transient() print("ok") sys.stdout.write("deactivating object adapter in the server... ") sys.stdout.flush() obj.deactivate() print("ok") sys.stdout.write("testing connection closure... ") sys.stdout.flush() for x in range(10): initData = Ice.InitializationData() initData.properties = communicator.getProperties().clone() comm = Ice.initialize(initData) comm.stringToProxy("test:default -p 12010").ice_pingAsync() comm.destroy() print("ok") sys.stdout.write("testing whether server is gone... ") sys.stdout.flush() try: obj.ice_ping() test(False) except Ice.LocalException: print("ok") return obj
elif c == '?': menu() else: print("unknown command `" + c + "'") menu() except EOFError: return 1 except KeyboardInterrupt: return 1 return 0 def menu(): print(""" usage: t: send greeting as twoway s: shutdown server x: exit ?: help """) status = 0 with Ice.initialize(sys.argv, "config.client") as communicator: if len(sys.argv) > 1: print(sys.argv[0] + ": too many arguments") status = 1 else: status = run(communicator) sys.exit(status)
def supportsCsharpSerializable(self, current=None): return Ice.Future.completed(False) def supportsCppStringView(self, current=None): return Ice.Future.completed(False) def supportsNullOptional(self, current=None): return Ice.Future.completed(True) def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") initial = InitialI() adapter.add(initial, Ice.stringToIdentity("initial")) adapter.activate() communicator.waitForShutdown() 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)
import sys import Ice import Bank from Bank import * if __name__ == '__main__': if len(sys.argv) < 2: print("Program needs port number as parameter\n", file=sys.stderr) exit(1) else: with Ice.initialize() as communicator: try: base = communicator.stringToProxy( "factory/factory:tcp -h localhost -p {}:udp -h localhost -p {}" .format(sys.argv[1], sys.argv[1])) account_factory = Bank.AccountFactoryPrx.checkedCast(base) except Ice.EndpointParseException: print("Incorrect port", file=sys.stderr) exit(1) if not account_factory: print("Invalid proxy", file=sys.stderr) exit(1) while True: cmd = input( "Please input 'login' for logging in, 'create' for account creation or 'x' to exit\n" ) if cmd == 'x': break if cmd == 'login':
def sessionDestroyed(self): self._destroyed = True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.Default.Router", "Glacier2/router:default -p 12060") app = Application() status = app.main(sys.argv, initData=initData) test(app._restart == 5) test(app._destroyed) initData.properties.setProperty("Ice.Default.Router", "") with Ice.initialize(initData) as communicator: sys.stdout.write("testing stringToProxy for process object... ") sys.stdout.flush() processBase = communicator.stringToProxy( "Glacier2/admin -f Process:default -p 12061") print("ok") sys.stdout.write("testing checked cast for admin object... ") sys.stdout.flush() process = Ice.ProcessPrx.checkedCast(processBase) test(process) print("ok") sys.stdout.write("testing Glacier2 shutdown... ") sys.stdout.flush() process.shutdown()
#adapter.activate() // Don't activate OA to ensure collocation is used. if prx.ice_getConnection(): raise RuntimeError("collocation doesn't work") cl = AllTests.allTests(communicator) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.BatchAutoFlushSize", "100") communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status)
def handle(self, *args, **options): username = raw_input('MotionDB Username: '******'MotionDB Password: '******'') # Configure Ice and Connect to database. properties = Ice.createProperties(sys.argv) properties.load(ICE_CLIENT_CONFIG_PATH) init_data = Ice.InitializationData() init_data.properties = properties ic = Ice.initialize(init_data) router = Glacier2.RouterPrx.checkedCast(ic.getDefaultRouter()) session = router.createSession(username, password) db = MotionDatabase.MotionDatabaseSessionPrx.checkedCast(session) # Collect all matching C3D and MMM files. self.stdout.write('Collecting data from motion database ...') q = MotionFile.objects.filter(is_hidden=False, is_broken_reported=False, is_broken_confirmed=False) motion_ids = list(set([m.motion_db_id for m in q.all()])) all_c3d_files = [] all_mmm_files = [] all_annotations = [] all_motion_ids = [] all_database_entries = [] for idx, motion_id in enumerate(motion_ids): self.stdout.write(' {}/{} ...'.format(idx + 1, len(motion_ids)), ending=' ') self.stdout.flush() files = db.listFiles(motion_id) c3d_files = [f for f in files if f.fileType == 'Vicon C3D File'] mmm_files = [ f for f in files if f.fileType == 'Converted MMM Motion' ] for c3d_file in c3d_files: # Ensure that only visible data is exported. assert c3d_file.visibility == MotionDatabase.VisibilityLevel.Public # Fetch motion file from database. try: motion_file = MotionFile.objects.get( motion_db_file_id=c3d_file.id) except MotionFile.DoesNotExist: continue assert motion_file.motion_db_id == motion_id # Skip broken motions. if motion_file.is_broken_reported or motion_file.is_broken_confirmed: continue # Find the matching MMM file for the given C3D file. mmm_file = None for f in mmm_files: if f.originatedFrom.id == c3d_file.id: mmm_file = f break assert mmm_file is not None # Get all annotations. We include data even if it isn't annotated yet. annotations = Annotation.objects.filter( motion_file=motion_file).all() all_c3d_files.append(c3d_file) all_mmm_files.append(mmm_file) all_annotations.append(annotations) all_motion_ids.append(motion_id) all_database_entries.append(motion_file) self.stdout.write('done') n_motions = len(all_c3d_files) assert n_motions == len(all_mmm_files) assert n_motions == len(all_annotations) assert n_motions == len(all_motion_ids) assert n_motions == len(all_database_entries) self.stdout.write( 'done, obtained {} motions and their annotations'.format( n_motions)) self.stdout.write('') # Create temporary directory. tmp_path = mkdtemp() self.stdout.write('Downloading data to "{}" ...'.format(tmp_path)) motion_entry_cache = {} nb_annotations = 0 nb_motions = 0 for idx, (database_entry, c3d_file, mmm_file, annotations, motion_id) in enumerate( zip(all_database_entries, all_c3d_files, all_mmm_files, all_annotations, all_motion_ids)): self.stdout.write(' {}/{}: ...'.format(idx + 1, n_motions), ending=' ') self.stdout.flush() filename_prefix = '{0:05d}'.format(database_entry.id) filename_mmm = filename_prefix + '_mmm.xml' filename_c3d = filename_prefix + '_raw.c3d' filename_meta = filename_prefix + '_meta.json' filename_annotation = filename_prefix + '_annotations.json' # Download MMM. r = db.getFileReader(mmm_file.id) d = read_file(r) r.destroy() if d is None: return -1 with open(os.path.join(tmp_path, filename_mmm), 'wb') as f: f.write(d) # Download C3D. r = db.getFileReader(c3d_file.id) d = read_file(r) r.destroy() if d is None: return -1 with open(os.path.join(tmp_path, filename_c3d), 'wb') as f: f.write(d) # Retrieve motion information. if c3d_file.attachedToId in motion_entry_cache: motion_entry = motion_entry_cache[c3d_file.attachedToId] else: motion_entry = db.getMotion(c3d_file.attachedToId) motion_entry_cache[c3d_file.attachedToId] = motion_entry # Save annotations and extract their IDs for metadata. with open(os.path.join(tmp_path, filename_annotation), 'w') as f: json.dump([a.description for a in annotations], f) mat_annotation_ids = [a.id for a in annotations] # Save metadata. annotation_perplexities = [a.perplexity for a in annotations] assert len(annotation_perplexities) == len(annotations) with open(os.path.join(tmp_path, filename_meta), 'w') as f: data = { 'motion_annotation_tool': { 'id': database_entry.id, 'annotation_ids': mat_annotation_ids, }, 'source': { 'institution': { 'name': motion_entry.associatedInstitution.name, 'identifier': motion_entry.associatedInstitution.acronym.lower(), }, 'database': { 'identifier': 'kit', 'motion_id': motion_id, 'motion_file_id': c3d_file.id, }, }, 'nb_annotations': len(annotations), 'annotation_perplexities': annotation_perplexities, } if motion_entry.associatedInstitution.acronym.lower() == 'cmu': # Reference actual CMU database first and provide KIT database as the mirror. data['source']['mirror_database'] = data['source'][ 'database'] motion_id, file_id = [ int(x) for x in os.path.splitext(c3d_file.fileName) [0].split('_') ] data['source']['database'] = { 'identifier': 'cmu', 'motion_id': motion_id, 'motion_file_id': file_id, } json.dump(data, f) # Book-keeping. nb_annotations += len(annotations) nb_motions += 1 self.stdout.write('done') self.stdout.write('done') self.stdout.write('') # Create ZIP archive. filename = time.strftime('%Y-%m-%d') + '.zip' self.stdout.write('Exporting ZIP archive "{}" ...'.format(filename), ending=' ') self.stdout.flush() def callback_before(file): self.stdout.write(' processing file "{}" ...'.format(file), ending=' ') self.stdout.flush() def callback_after(file): self.stdout.write('done') zipdir(tmp_path, os.path.join(DATA_PATH, filename), callback_before=callback_before, callback_after=callback_after) self.stdout.write('done') self.stdout.write('') # Create dataset entry in DB. dataset = Dataset() dataset.nb_annotations = nb_annotations dataset.nb_motions = nb_motions dataset.filename = filename dataset.filesize = os.path.getsize(os.path.join(DATA_PATH, filename)) dataset.save() # Clean up tmp directory. self.stdout.write( 'Cleaning up temp directory "{}" ...'.format(tmp_path), ending=' ') self.stdout.flush() shutil.rmtree(tmp_path) self.stdout.write('done') self.stdout.write('') self.stdout.write( 'All done, remember to collect the static files so that people can download the dataset!' )
def allTests(communicator): sys.stdout.write("testing communicator operations... ") sys.stdout.flush() # # Test: Exercise addAdminFacet, findAdminFacet, removeAdminFacet with a typical configuration. # init = Ice.InitializationData() init.properties = Ice.createProperties() init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1") init.properties.setProperty("Ice.Admin.InstanceName", "Test") init.properties.setProperty("Ice.ProgramName", "MyTestProgram") com = Ice.initialize(init) testFacets(com) test(com.getLogger().getPrefix() == "MyTestProgram") com.destroy() # # Test: Verify that the operations work correctly in the presence of facet filters. # init = Ice.InitializationData() init.properties = Ice.createProperties() init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1") init.properties.setProperty("Ice.Admin.InstanceName", "Test") init.properties.setProperty("Ice.Admin.Facets", "Properties") com = Ice.initialize(init) testFacets(com, False) com.destroy() # # Test: Verify that the operations work correctly with the Admin object disabled. # com = Ice.initialize() testFacets(com, False) com.destroy() # # Test: Verify that the operations work correctly when Ice.Admin is enabled. # init = Ice.InitializationData() init.properties = Ice.createProperties() init.properties.setProperty("Ice.Admin.Enabled", "1") com = Ice.initialize(init) test(com.getAdmin() == None) identity = com.stringToIdentity("test-admin") try: com.createAdmin(None, identity) test(False) except Ice.InitializationException: pass adapter = com.createObjectAdapter("") test(com.createAdmin(adapter, identity) != None) test(com.getAdmin() != None) testFacets(com) com.destroy() # # Test: Verify that the operations work correctly when creation of the Admin object is delayed. # init = Ice.InitializationData() init.properties = Ice.createProperties() init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1") init.properties.setProperty("Ice.Admin.InstanceName", "Test") init.properties.setProperty("Ice.Admin.DelayCreation", "1") com = Ice.initialize(init) testFacets(com) com.getAdmin() testFacets(com) com.destroy() print("ok") ref = "factory:default -p 12010 -t 10000" factory = Test.RemoteCommunicatorFactoryPrx.uncheckedCast(communicator.stringToProxy(ref)) sys.stdout.write("testing process facet... ") sys.stdout.flush() # # Test: Verify that Process::shutdown() operation shuts down the communicator. # props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" com = factory.createCommunicator(props) obj = com.getAdmin() proc = Ice.ProcessPrx.checkedCast(obj, "Process") proc.shutdown() com.waitForShutdown() com.destroy() print("ok") sys.stdout.write("testing properties facet... ") sys.stdout.flush() props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" props["Prop1"] = "1" props["Prop2"] = "2" props["Prop3"] = "3" com = factory.createCommunicator(props) obj = com.getAdmin() pa = Ice.PropertiesAdminPrx.checkedCast(obj, "Properties") # # Test: PropertiesAdmin::getProperty() # test(pa.getProperty("Prop2") == "2") test(pa.getProperty("Bogus") == "") # # Test: PropertiesAdmin::getProperties() # pd = pa.getPropertiesForPrefix("") test(len(pd) == 5) test(pd["Ice.Admin.Endpoints"] == "tcp -h 127.0.0.1") test(pd["Ice.Admin.InstanceName"] == "Test") test(pd["Prop1"] == "1") test(pd["Prop2"] == "2") test(pd["Prop3"] == "3") changes = {} # # Test: PropertiesAdmin::setProperties() # setProps = {} setProps["Prop1"] = "10" # Changed setProps["Prop2"] = "20" # Changed setProps["Prop3"] = "" # Removed setProps["Prop4"] = "4" # Added setProps["Prop5"] = "5" # Added pa.setProperties(setProps) test(pa.getProperty("Prop1") == "10") test(pa.getProperty("Prop2") == "20") test(pa.getProperty("Prop3") == "") test(pa.getProperty("Prop4") == "4") test(pa.getProperty("Prop5") == "5") changes = com.getChanges() test(len(changes) == 5) test(changes["Prop1"] == "10") test(changes["Prop2"] == "20") test(changes["Prop3"] == "") test(changes["Prop4"] == "4") test(changes["Prop5"] == "5") pa.setProperties(setProps) changes = com.getChanges() test(len(changes) == 0) com.destroy() print("ok") sys.stdout.write("testing custom facet... ") sys.stdout.flush() # # Test: Verify that the custom facet is present. # props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" com = factory.createCommunicator(props) obj = com.getAdmin() tf = Test.TestFacetPrx.checkedCast(obj, "TestFacet") tf.op() com.destroy() print("ok") sys.stdout.write("testing facet filtering... ") sys.stdout.flush() # # Test: Set Ice.Admin.Facets to expose only the Properties facet, # meaning no other facet is available. # props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" props["Ice.Admin.Facets"] = "Properties" com = factory.createCommunicator(props) obj = com.getAdmin() proc = Ice.ProcessPrx.checkedCast(obj, "Process") test(proc == None) tf = Test.TestFacetPrx.checkedCast(obj, "TestFacet") test(tf == None) com.destroy() # # Test: Set Ice.Admin.Facets to expose only the Process facet, # meaning no other facet is available. # props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" props["Ice.Admin.Facets"] = "Process" com = factory.createCommunicator(props) obj = com.getAdmin() pa = Ice.PropertiesAdminPrx.checkedCast(obj, "Properties") test(pa == None) tf = Test.TestFacetPrx.checkedCast(obj, "TestFacet") test(tf == None) com.destroy() # # Test: Set Ice.Admin.Facets to expose only the TestFacet facet, # meaning no other facet is available. # props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" props["Ice.Admin.Facets"] = "TestFacet" com = factory.createCommunicator(props) obj = com.getAdmin() pa = Ice.PropertiesAdminPrx.checkedCast(obj, "Properties") test(pa == None) proc = Ice.ProcessPrx.checkedCast(obj, "Process") test(proc == None) com.destroy() # # Test: Set Ice.Admin.Facets to expose two facets. Use whitespace to separate the # facet names. # props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" props["Ice.Admin.Facets"] = "Properties TestFacet" com = factory.createCommunicator(props) obj = com.getAdmin() pa = Ice.PropertiesAdminPrx.checkedCast(obj, "Properties") test(pa.getProperty("Ice.Admin.InstanceName") == "Test") tf = Test.TestFacetPrx.checkedCast(obj, "TestFacet") tf.op() proc = Ice.ProcessPrx.checkedCast(obj, "Process") test(proc == None) com.destroy() # # Test: Set Ice.Admin.Facets to expose two facets. Use a comma to separate the # facet names. # props = {} props["Ice.Admin.Endpoints"] = "tcp -h 127.0.0.1" props["Ice.Admin.InstanceName"] = "Test" props["Ice.Admin.Facets"] = "TestFacet, Process" com = factory.createCommunicator(props) obj = com.getAdmin() pa = Ice.PropertiesAdminPrx.checkedCast(obj, "Properties") test(pa == None) tf = Test.TestFacetPrx.checkedCast(obj, "TestFacet") tf.op() proc = Ice.ProcessPrx.checkedCast(obj, "Process") proc.shutdown() com.waitForShutdown() com.destroy() print("ok") factory.shutdown()
# Do nothing. pass else: # if(oneway) publisher = publisher.ice_oneway() clock = Demo.ClockPrx.uncheckedCast(publisher) print("publishing tick events. Press ^C to terminate the application.") try: # Loop infinito del publisher. while 1: clock.tick(time.strftime("%m/%d/%Y %H:%M:%S")) time.sleep(1) except IOError: # Ignore pass except Ice.CommunicatorDestroyedException: # Ignore pass # # Ice.initialize returns an initialized Ice communicator, # the communicator is destroyed once it goes out of scope. # with Ice.initialize(sys.argv, "config.pub") as communicator: signal.signal(signal.SIGINT, lambda signum, frame: communicator.destroy()) if hasattr(signal, 'SIGBREAK'): signal.signal(signal.SIGBREAK, lambda signum, frame: communicator.destroy()) status = run(communicator)
import Test, TestI def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000") adapter = communicator.createObjectAdapter("TestAdapter") ident = communicator.stringToIdentity("factory") adapter.add(TestI.RemoteCommunicatorFactoryI(), ident) adapter.activate() communicator.waitForShutdown() return True try: communicator = Ice.initialize(sys.argv) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status)
# current.con.setACM(30, Ice.ACMClose.CloseOff, Ice.ACMHeartbeat.HeartbeatAlways) current.con.setCloseCallback(lambda con: destroySession(collocProxy)) return proxy def shutdown(self, current): print("Shutting down...") current.adapter.getCommunicator().shutdown() # # Ice.initialize returns an initialized Ice communicator, # the communicator is destroyed once it goes out of scope. # with Ice.initialize(sys.argv, "config.server") as communicator: # # Install a signal handler to shutdown the communicator on Ctrl-C # signal.signal(signal.SIGINT, lambda signum, handler: communicator.shutdown()) # # The communicator initialization removes all Ice-related arguments from argv # if len(sys.argv) > 1: print(sys.argv[0] + ": too many arguments") sys.exit(1) adapter = communicator.createObjectAdapter("SessionFactory") adapter.add(SessionFactoryI(), Ice.stringToIdentity("SessionFactory"))
def getPassFor(host_param): for line in open(os.getenv("HOME")+'/.rcremote', 'r').readlines(): s = line.strip().split('#', 1) if len(s) < 2: continue host = s[0] password = s[1] if host == host_param: return password raise Exception("can't find password for "+host_param+" in ~/.rcremote (format 'host#password')") if __name__ == '__main__': app = QtCore.QCoreApplication(sys.argv) ic = Ice.initialize(sys.argv) status = 0 mprx = {} if len(sys.argv) < 2: try: print 'Reading password from ~/.rcremote...' password = getPassFor('localhost') print 'ok.' except: print 'Couldn\'t read password from file!' print '\nUsage: rcremoteserver <password>' sys.exit(-1) else: password = sys.argv[1]
import Ice, kadmin5, sys, Tartarus import Tartarus.iface.Kerberos as I c = Ice.initialize() a = I.KadminPrx.checkedCast(c.propertyToProxy("Tartarus.Kadmin5.Prx")) t = kadmin5.keytab() try: svc = sys.argv[1] except IndexError: svc = "host" try: hostname = sys.argv[2] except IndexError: from socket import getfqdn hostname = getfqdn() pr = a.createServicePrincipal(svc, hostname) for k in pr.keys: t.add_entry(pr.name, k.kvno, k.enctype, k.data)
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") self._optSetProp(id, "Ice.ACM.Client.Timeout", str(omero.constants.ACMCLIENTTIMEOUT)) self._optSetProp(id, "Ice.ACM.Client.Heartbeat", str(omero.constants.ACMCLIENTHEARTBEAT)) 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") prop = "IceSSL.Ciphers" try: if sys.platform == "darwin": self._optSetProp(id, prop, "(AES_256) (DH_anon.*AES)") elif ssl.OPENSSL_VERSION_INFO >= (1, 1): self._optSetProp(id, prop, "HIGH:ADH:@SECLEVEL=0") else: self._optSetProp(id, prop, "HIGH:ADH") except Exception: # OPENSSL_VERSION_INFO not available for 2.6, fall back to default self._optSetProp(id, prop, "HIGH:ADH") self._optSetProp(id, "IceSSL.VerifyDepthMax", "6") 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)) # 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 try: import ObjectFactoryRegistrar as ofr except ImportError: from . import ObjectFactoryRegistrar as ofr ofr.registerObjectFactory(self.__ic, self) for of in list(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()