def setup_class(cls): cls.OmeroPy = cls.omeropydir() cls.__clients = Clients() # Create a root client p = Ice.createProperties(sys.argv) rootpass = p.getProperty("omero.rootpass") try: cls.root = omero.client() # ok because adds self cls.__clients.add(cls.root) cls.root.setAgent("OMERO.py.root_test") cls.root.createSession("root", rootpass) cls.root.getSession().keepAlive(None) except: raise Exception("Could not initiate a root connection") cls.group = cls.new_group(perms=cls.DEFAULT_PERMS) cls.user = cls.new_user(group=cls.group, owner=cls.DEFAULT_GROUP_OWNER) cls.client = omero.client() # ok because adds self cls.__clients.add(cls.client) cls.client.setAgent("OMERO.py.test") cls.sf = cls.client.createSession(cls.user.omeName.val, cls.user.omeName.val) cls.ctx = cls.sf.getAdminService().getEventContext() cls.update = cls.sf.getUpdateService() cls.query = cls.sf.getQueryService()
def testSessionWithIP(self): c1 = omero.client( pmap=['--Ice.Config='+(os.environ.get("ICE_CONFIG"))]) try: host = c1.ic.getProperties().getProperty('omero.host') port = int(c1.ic.getProperties().getProperty('omero.port')) rootpass = c1.ic.getProperties().getProperty('omero.rootpass') finally: c1.__del__() c = omero.client(host=host, port=port) try: c.setAgent("OMERO.py.root_test") c.setIP("127.0.0.1") s = c.createSession("root", rootpass) p = omero.sys.ParametersI() p.map = {} p.map["uuid"] = rstring( s.getAdminService().getEventContext().sessionUuid) res = s.getQueryService().findByQuery( "from Session where uuid=:uuid", p) assert "127.0.0.1" == res.getUserIP().val s.closeOnDestroy() c.closeSession() finally: c.__del__()
def test1018CreationDestructionClosing(self): c1 = omero.client() s1 = c1.createSession() s1.detachOnDestroy() uuid = s1.ice_getIdentity().name # Intermediate "disrupter" c2 = omero.client() s2 = c2.createSession(uuid, uuid) s2.getAdminService().getEventContext() c2.closeSession() # 1 should still be able to continue s1.getAdminService().getEventContext() # Now if s1 exists another session should be able to connect c1.closeSession() c3 = omero.client() s3 = c3.createSession(uuid, uuid) s3.getAdminService().getEventContext() c3.closeSession() # Now a connection should not be possible import Glacier2 c4 = omero.client() self.assertRaises(Glacier2.PermissionDeniedException, c4.joinSession, uuid) del c4
def testCreationDestructionClosing(self): c1, c2, c3, c4 = None, None, None, None try: c1 = omero.client() # ok rather than new_client since has __del__ s1 = c1.createSession() s1.detachOnDestroy() uuid = s1.ice_getIdentity().name # Intermediate "disrupter" c2 = omero.client() # ok rather than new_client since has __del__ s2 = c2.createSession(uuid, uuid) s2.closeOnDestroy() s2.getAdminService().getEventContext() c2.closeSession() # 1 should still be able to continue s1.getAdminService().getEventContext() # Now if s1 exists another session should be able to connect c1.closeSession() c3 = omero.client() # ok rather than new_client since has __del__ s3 = c3.createSession(uuid, uuid) s3.closeOnDestroy() s3.getAdminService().getEventContext() c3.closeSession() # Now a connection should not be possible c4 = omero.client() # ok rather than new_client since has __del__ import Glacier2 self.assertRaises(Glacier2.PermissionDeniedException, c4.createSession, uuid, uuid); finally: for c in (c1, c2, c3, c4): if c: c.__del__()
def setUp(self): self.OmeroPy = self.omeropydir() self.__clients = Clients() p = Ice.createProperties(sys.argv) rootpass = p.getProperty("omero.rootpass") name = None pasw = None if rootpass: self.root = omero.client() # ok because adds self self.__clients.add(self.root) self.root.setAgent("OMERO.py.root_test") self.root.createSession("root", rootpass) newuser = self.new_user() name = newuser.omeName.val pasw = "1" else: self.root = None self.client = omero.client() # ok because adds self self.__clients.add(self.client) self.client.setAgent("OMERO.py.test") self.sf = self.client.createSession(name, pasw) self.update = self.sf.getUpdateService() self.query = self.sf.getQueryService()
def testLogin(username, password): import os c = omero.client( pmap=['--Ice.Config=' + (os.environ.get("ICE_CONFIG"))]) host = c.ic.getProperties().getProperty('omero.host') port = int(c.ic.getProperties().getProperty('omero.port')) omero.client(host=host, port=port) sf = c.createSession(username, password) sf.getAdminService().getEventContext() c.closeSession()
def testBlockSize(self): c = omero.client("localhost") try: assert 5000000 == c.getDefaultBlockSize() finally: c.__del__() c = omero.client("localhost", ["--omero.block_size=1000000"]) try: assert 1000000 == c.getDefaultBlockSize() finally: c.__del__()
def testPorts(self): c = omero.client("localhost", 1111) try: self.assertEquals("1111",c.ic.getProperties().getProperty("omero.port")) finally: c.__del__() c = omero.client("localhost",["--omero.port=2222"]) try: self.assertEquals("2222",c.ic.getProperties().getProperty("omero.port")) finally: c.__del__()
def testPorts(self): c = omero.client("localhost", 1111) try: assert "1111" == c.ic.getProperties().getProperty("omero.port") finally: c.__del__() c = omero.client("localhost",["--omero.port=2222"]) try: assert "2222" == c.ic.getProperties().getProperty("omero.port") finally: c.__del__()
def testCheckIfDeleted(self): uuid = self.client.sf.getAdminService().getEventContext().sessionUuid userName = self.client.sf.getAdminService().getEventContext().userName query = self.client.sf.getQueryService() update = self.client.sf.getUpdateService() delete = self.client.sf.getDeleteService() img = omero.model.ImageI() img.name = omero.rtypes.rstring("to delete - test") img.acquisitionDate = omero.rtypes.rtime(0) tag = omero.model.TagAnnotationI() img.linkAnnotation( tag ) iid = update.saveAndReturnObject( img ).id.val cmd = omero.api.delete.DeleteCommand("/Image", iid, None) handle = delete.queueDelete([cmd]) cbString = str(handle) callback = omero.callbacks.DeleteCallbackI(self.client, handle) while callback.block(500) is not None: # ms. pass err = handle.errors() callback.close() self.assertEquals(0, err) self.assertEquals(None, query.find("Image", iid)) # create new session and double check import os import Ice c = omero.client(pmap=['--Ice.Config='+(os.environ.get("ICE_CONFIG"))]) host = c.ic.getProperties().getProperty('omero.host') port = int(c.ic.getProperties().getProperty('omero.port')) cl1 = omero.client(host=host, port=port) sf1 = cl1.createSession(userName,userName) try: handle1 = omero.api.delete.DeleteHandlePrx.checkedCast(cl1.ic.stringToProxy(cbString)) self.fail("exception Ice.ObjectNotExistException was not thrown") except Ice.ObjectNotExistException: pass # join session and double check cl2 = omero.client(host=host, port=port) sf2 = cl2.joinSession(uuid) try: handle2 = omero.api.delete.DeleteHandlePrx.checkedCast(cl2.ic.stringToProxy(cbString)) self.fail("exception Ice.ObjectNotExistException was not thrown") except Ice.ObjectNotExistException: pass
def testTwoDifferentHosts(self): try: c1 = omero.client(host="foo") c1.createSession() c1.closeSession() except: print "foo failed appropriately" c2 = omero.client(host=self.host, port=self.port) try: c2.createSession(self.user, self.passwd) c2.closeSession() finally: c2.__del__()
def testManageMySessions(self): import os adminCtx = self.client.sf.getAdminService().getEventContext() username = adminCtx.userName group = adminCtx.groupName self.root.sf.getAdminService().lookupExperimenter(username) p = omero.sys.Principal() p.name = username p.group = group p.eventType = "User" newConnId = self.root.sf.getSessionService().createSessionWithTimeout( p, 60000) # ok rather than new_client since has __del__ c1 = omero.client( pmap=['--Ice.Config=' + (os.environ.get("ICE_CONFIG"))]) try: host = c1.ic.getProperties().getProperty('omero.host') port = int(c1.ic.getProperties().getProperty('omero.port')) c1.__del__() # Just used for parsing # ok rather than new_client since has __del__ c1 = omero.client(host=host, port=port) s = c1.joinSession(newConnId.getUuid().val) s.detachOnDestroy() svc = self.client.sf.getSessionService() for s in svc.getMyOpenSessions(): if (adminCtx.sessionUuid != s.uuid.val and s.defaultEventType.val not in ('Internal', 'Sessions')): cc = None try: try: # ok rather than new_client since has __del__ cc = omero.client(host, port) cc.joinSession(s.uuid.val) cc.killSession() except: self.assertRaises(traceback.format_exc()) finally: cc.__del__() for s in svc.getMyOpenSessions(): assert s.uuid.val != newConnId.getUuid().val finally: c1.__del__()
def testTwoDifferentHosts(self): try: c1 = omero.client(host="foo") c1.createSession() c1.closeSession() except: print "foo failed appropriately" c2 = omero.client(host=self.host, port=self.port) try: user = self.new_user() c2.createSession(user.omeName.val, "ome") c2.closeSession() finally: c2.__del__()
def __init__(self, user = None, passwd = None, host = 'localhost', client = None, tableName = None, tableId = None): """ Create a new table handler, either by specifying user and passwd or by providing a client object (for scripts) @param user Username @param passwd Password @param host The server hostname @param client Client object with an active session @param tableName The name of the table file @param tableId The OriginalFile ID of the table file """ if not client: client = omero.client(host) sess = client.createSession(user, passwd) client.enableKeepAlive(60) else: sess = client.getSession() self.conn = BlitzGateway(client_obj = client) self.res = sess.sharedResources() if (not self.res.areTablesEnabled()): raise TableConnectionError('OMERO.tables not enabled') repos = self.res.repositories() self.rid = repos.descriptions[0].id.val self.tableName = tableName self.tableId = tableId self.table = None
def setUp (self): c = omero.client(pmap=['--Ice.Config='+(os.environ.get("ICE_CONFIG"))]) try: self.root_password = c.ic.getProperties().getProperty('omero.rootpass') omero_host = c.ic.getProperties().getProperty('omero.host') finally: c.__del__() blitz = Server.find(host=omero_host) if blitz is None: Server.reset() for s in settings.SERVER_LIST: server = (len(s) > 2) and unicode(s[2]) or None Server(host=unicode(s[0]), port=int(s[1]), server=server) Server.freeze() blitz = Server.find(server=omero_host) if blitz is not None: self.server_id = blitz.id connector = Connector(self.server_id, True) self.rootconn = connector.create_connection('TEST.webadmin', 'root', self.root_password) if self.rootconn is None or not self.rootconn.isConnected() or not self.rootconn.keepAlive(): raise exceptions.Exception("Cannot connect") else: raise exceptions.Exception("'%s' is not on omero.web.server_list" % omero_host)
def connect(cfg): client = omero.client(cfg['host']) password = cfg.get('password') if not password: password = getpass.getpass() session = client.createSession(cfg['user'], password) return client, session
def __init__(self, user = None, passwd = None, host = None, client = None): """ Create a new client session, either by specifying user and passwd or by providing a client object (for scripts) @param user Username @param passwd Password @param host The server hostname @param client Client object with an active session """ self.log = logging.getLogger(__name__) #self.log.setLevel(logging.DEBUG) if not client: client = omero.client(host) sess = client.createSession(user, passwd) client.enableKeepAlive(60) else: sess = client.getSession() self.conn = BlitzGateway(client_obj = client) self.res = sess.sharedResources() if (not self.res.areTablesEnabled()): raise TableConnectionError('OMERO.tables not enabled')
def __init__(self, host=None, port=None, user=None, password=None, sessionid=None, groupid=-1, detach=False): if not host: host = 'localhost' if not port: port = 4064 if not sessionid: if not user: user = raw_input('User: '******'Joined session as: %s', self.session) else: self.session = self.client.createSession(user, password) log.info('Created session: %s', self.session) self.client.enableKeepAlive(60) self.conn = omero.gateway.BlitzGateway(client_obj=self.client) self.conn.SERVICE_OPTS.setOmeroGroup(groupid) self.detach = detach if self.detach: log.info('Detaching session: %s', self.session) self.session.detachOnDestroy()
def new_client( self, group=None, user=None, perms=None, owner=False, system=False, session=None, password=None, email=None ): """ Like new_user() but returns an active client. Passing user= or session= will prevent self.new_user from being called, and instead the given user (by name or ExperimenterI) or session will be logged in. """ props = self.root.getPropertyMap() if session is not None: if user is not None: self.log.warning("user= argument will be ignored: %s", user) session = unwrap(session) props["omero.user"] = session props["omero.pass"] = session else: if user is not None: user, name = self.user_and_name(user) else: user = self.new_user(group, perms, owner=owner, system=system, email=email) props["omero.user"] = user.omeName.val if password is not None: props["omero.pass"] = password else: props["omero.pass"] = user.omeName.val client = omero.client(props) self.__clients.add(client) client.setAgent("OMERO.py.new_client_test") client.createSession() return client
def loginAttempt(self, name, t, pw="BAD", less=False): """ Checks that login happens in less than or greater than the given time. By default, the password "BAD" is used, and the expectation is that login will take greather than the specified time since the password won't match. To check that logins happen more quickly, pass the correct password and less=True: loginAttempt("user", 0.15, pw="REALVALUE", less=True) See integration.tickets4000 and 5000 """ c = omero.client() # ok because followed by __del__ try: t1 = time.time() try: c.createSession(name, pw) if pw == "BAD": assert False, "Should not reach this point" except Glacier2.PermissionDeniedException: if pw != "BAD": raise t2 = time.time() T = t2 - t1 if less: assert T < t, "%s > %s" % (T, t) else: assert T > t, "%s < %s" % (T, t) finally: c.__del__()
def test8118(self): uuid = self.root.sf.getAdminService().getEventContext().sessionUuid share_serv = self.root.sf.getShareService() # create user user1 = self.new_user() # create image img = self.make_image(name='test8118-img-%s' % uuid) # create share description = "my description" timeout = None objects = [img] experimenters = [user1] guests = [] enabled = True sid = share_serv.createShare(description, timeout, objects, experimenters, guests, enabled) suuid = share_serv.getShare(sid).uuid assert 1 == len(share_serv.getContents(sid)) # join share user1_client = omero.client() try: user1_client.createSession(suuid, suuid) user1_share = user1_client.sf.getShareService() user1_share.activate(sid) assert 1 == len(user1_share.getContents(sid)) finally: user1_client.__del__()
def testHostConstructor(self): c = omero.client(host=self.host, port=self.port) try: c.createSession("root", self.rootpasswd) c.closeSession() c.createSession("root", self.rootpasswd) except: c.__del__()
def setup_method(self, method): self.cli = omero.client() un = unwrap(self.user.getOmeName()) self.sess = self.cli.createSession(un, un) self.fsmeta = {'fsname': 'a'} ns = UserAccount.uuid() self.nsc = ns + '/c' self.nsr = ns + '/r'
def setUp (self): c = omero.client(pmap=['--Ice.Config='+(os.environ.get("ICE_CONFIG"))]) try: self.root_password = c.ic.getProperties().getProperty('omero.rootpass') self.omero_host = c.ic.getProperties().getProperty('omero.host') self.omero_port = c.ic.getProperties().getProperty('omero.port') finally: c.__del__()
def testPythonCtorRepair(self): #c = omero.client(self.host, omero.constants.GLACIER2PORT) c = omero.client(self.host, self.port) try: c.createSession("root", self.rootpasswd) c.closeSession() finally: c.__del__()
def emanToOmero(commandArgs): #print commandArgs client = omero.client(commandArgs["host"]) global session session = client.createSession(commandArgs["username"], commandArgs["password"]) global re global queryService global pixelsService global rawPixelStore global updateService global rawFileStore re = session.createRenderingEngine() queryService = session.getQueryService() pixelsService = session.getPixelsService() rawPixelStore = session.createRawPixelsStore() updateService = session.getUpdateService() rawFileStore = session.createRawFileStore() path = commandArgs["bdb"] # get a name for the project head,tail = os.path.split(path) projectName = tail if projectName == "": projectName = head # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) if projectName.find("#") > -1: if path.lower()[:4]!="bdb:" : path="bdb:"+path print projectName, "has #. Importing from", path dataset = createDataset(projectName, project) uploadBdbAsDataset(path, dataset) return # import the micrographs in the root folder #importMicrographs(path, project=project) # import particles into 3 datasets, "particles", "ctf", "wiener" d = "Raw particle images picked from original micrographs" importParticles(path + "particles", bdbExt="ptcls", datasetName="particles", project=project, desc=d) d = "Ctf-corrected particle images, phase flipped" importParticles(path + "particles", bdbExt="ctf_flip", datasetName="ctf", project=project, desc=d) d = "Ctf-corrected particles, weiner filtered" importParticles(path + "particles", bdbExt="ctf_wiener", datasetName="wiener", project=project, desc=d) # make a dataset from each particle set (only do '...flipped' particle sets) importParticles(path + "sets", bdbExt="flipped", project=project) # import refine2d. First, the stack of 36x36 particles referred to by classes importParticles(path + "r2d_01", bdbExt="all4", project=project) # import class averages. These will link to datasets of their member particles. importParticles(path + "r2d_01", bdbExt="classes_01", project=project)
def testSimpleDestruction(self): c = omero.client() # ok rather than new_client since has __del__ try: c.ic.getImplicitContext().put(omero.constants.CLIENTUUID,"SimpleDestruction") s = c.createSession() s.closeOnDestroy() c.closeSession() finally: c.__del__()
def setup_method(self, method): lib.ITest.setup_method(self, method) c = omero.client(pmap=['--Ice.Config='+(os.environ.get("ICE_CONFIG"))]) try: self.host = c.ic.getProperties().getProperty('omero.host') self.port = int(c.ic.getProperties().getProperty('omero.port')) self.rootpasswd = c.ic.getProperties().getProperty('omero.rootpass') finally: c.__del__()
def __init__(self, host, user, passwd, group=None, session_keep_tokens=1): self.user = user self.passwd = passwd self.group_name = group self.client = omero.client(host) self.session_keep_tokens = session_keep_tokens self.transaction_tokens = 0 self.current_session = None self.logger = logger
def create_omero_gateway(host=DEFAULT_OMERO_HOST, port=DEFAULT_OMERO_PORT, username=DEFAULT_OMERO_USERNAME, password=DEFAULT_OMERO_PASSWORD): '''Connect to an omero server and create an omero gateway instance''' try: omero_client = omero.client(host, port) omero_session = omero_client.createSession(username, password) omero_gateway = omero_session.createGateway() except Exception, err: raise RuntimeError("Unable to connect to OMERO server %s@%s:%d"% (username, host, int(port)), err)
info = True if option == "-k": session_key = argument if option == "-d": logging_level = logging.DEBUG if option == "-t": thread_count = int(argument) if session_key is None and username is None: usage("Username must be specified!") if session_key is None and hostname is None: usage("Host name must be specified!") if session_key is None and password is None: password = getpass() logging.basicConfig(level = logging_level) client = client(hostname, port) client.setAgent("OMERO.populate_metadata") client.enableKeepAlive(60) try: if session_key is not None: client.joinSession(session_key) else: client.createSession(username, password) log.debug('Creating pool of %d threads' % thread_count) thread_pool = ThreadPool(thread_count) ctx = ParsingContext(client, target_object, file) ctx.parse() if not info: ctx.write_to_omero() finally:
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import omero import omero.cli HOST = "yourhost" USER = "******" PASS = "******" client = omero.client(HOST) client.createSession(USER, PASS) try: cli = omero.cli.CLI() cli.loadplugins() cli._client = client for x in sys.argv[1:]: cli.invoke([ "hql", "-q", "--limit", "-1", ("SELECT i.id FROM Experimenter i " "WHERE i.omeName='%s'") % x ]) finally: client.__del__()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import omero args = list(sys.argv) client = omero.client(args) sudoClient = omero.client(args) try: sf = client.createSession("root", "ome") sessionSvc = sf.getSessionService() p = omero.sys.Principal() p.name = "root" # Can change to any user p.group = "user" p.eventType = "User" # 3 minutes to live sudoSession = sessionSvc.createSessionWithTimeout(p, 3 * 60 * 1000L) sudoSf = sudoClient.joinSession(sudoSession.getUuid().getValue()) sudoAdminSvc = sudoSf.getAdminService() print sudoAdminSvc.getEventContext().userName finally: sudoClient.closeSession() client.closeSession()
def testClientClosedManually(self): client = omero.client() user = self.new_user() client.createSession(user.omeName.val, user.omeName.val) client.getSession().closeOnDestroy() client.closeSession()
#!/usr/bin/env python # -*- coding: utf-8 -*- import omero import Ice # All configuration in file pointed to by # --Ice.Config=file.config or ICE_CONFIG # environment variable; # No username, password entered try: client1 = omero.client() client1.createSession() client1.closeSession() except Ice.ConnectionRefusedException: pass # Bad address or port? # Most basic configuration. # Uses default port 4064 # createSession needs username and password try: client2 = omero.client("localhost") client2.createSession("root", "ome") client2.closeSession() except Ice.ConnectionRefusedException: pass # Bad address or port? # Configuration with port information try: client3 = omero.client("localhost", 24064) client3.createSession("root", "ome") client3.closeSession()
Change this file to Parse_OMERO_Properties.py and enter your ID/username """ import omero import os import sys try: omero_app_url = os.environ["OMERO_APP_URL"] omero_username = os.environ["OMERO_USERNAME"] omero_user_password = os.environ["OMERO_USER_PASSWORD"] except KeyError: print "Please set the environment variable OMERO_USERNAME, OMERO_USER_PASSWORD and OMERO_APP_URL" sys.exit(1) client = omero.client(omero_app_url) omeroProperties = client.getProperties().getPropertiesForPrefix('omero') # Configuration # ================================================================= # These values will be imported by all the other training scripts. HOST = omeroProperties.get('omero.host', omero_app_url) PORT = omeroProperties.get('omero.port', 4064) USERNAME = omeroProperties.get('omero.user', omero_username) PASSWORD = omeroProperties.get('omero.pass', omero_user_password) OMERO_WEB_HOST = omeroProperties.get('omero.webhost') SERVER_NAME = omeroProperties.get(omero_app_url) # projectId = omeroProperties.get('omero.projectid') # datasetId = omeroProperties.get('omero.datasetid') # imageId = omeroProperties.get('omero.imageid')
def testClientClosedAutomatically(self): client = omero.client() user = self.new_user() client.createSession(user.omeName.val, "ome") client.getSession().closeOnDestroy()
def __init__(self): self.root = omero.client() self.root.setAgent(__name__) rootpass = self.root.getProperty('omero.rootpass') self.root.createSession('root', rootpass)
def testClientClosedManually(self): client = omero.client() client.createSession() client.getSession().closeOnDestroy() client.closeSession()
scripts.List("IDs", optional=False).ofType(rlong(0))) # we can now create our local Blitz Gateway by wrapping the client object local_conn = BlitzGateway(client_obj=client) # get the 'IDs' parameter (which we have restricted to 'Image' IDs) host = client.getInput("serverUrl", unwrap=True) port = client.getInput("port", unwrap=True) sessionUuid = client.getInput("sessionUuid", unwrap=True) ids = unwrap(client.getInput("IDs")) # The managed_dir is where the local images are stored. managed_dir = client.sf.getConfigService().getConfigValue("omero.managed.dir") # Connect to remote omero c = omero.client(host=host, port=port, args=["--Ice.Config=/dev/null", "--omero.debug=1"]) c.joinSession(sessionUuid) try: # Just to test connection, print the projects. remote_conn = BlitzGateway(client_obj=c) for p in remote_conn.getObjects("Project"): print p.id, p.name print "Connected to ", REMOTE_HOST, ", now to transfer image" cli = omero.cli.CLI() cli.loadplugins() cli.set_client(c) del os.environ["ICE_CONFIG"]
def imageUploadImportOmero(request, conn=None, **kwargs): try: fileId = request.POST.get("fileId", 0) datasetId = request.POST.get("datasetId", 0) path = ImportFile.getPathFromId(fileId) if path is None: return HttpResponse("FAIL:No path for temp file ID " + str(fileId)) dataset = conn.getObject("Dataset", datasetId) if dataset is None: return HttpResponse("FAIL:No dataset with ID " + str(datasetId)) txt = "" ret_code = -1 with tempfile.NamedTemporaryFile(suffix=".stdout") as stdout: with tempfile.NamedTemporaryFile(suffix=".stderr") as stderr: cli = omero.cli.CLI() cli.loadplugins() cli._client = conn.c cli.invoke([ "import", "---errs", stderr.name, "---file", stdout.name, "--no-upgrade-check", path, "-d", datasetId ]) ret_code = cli.rv if ret_code == 0: txt = "IM_" + stdout.readline().split(':')[1] # if there was an import error, we expect the file is not an image if ret_code != 0: newFileId = -1 fileName = os.path.basename(path) fileSize = os.path.getsize(path) c = omero.client('localhost', 4064) jSes = c.joinSession(conn.getEventContext().sessionUuid) fileService = jSes.getReceptorLightFileManager() if fileService is not None: newFileId = fileService.createFile(fileName) if newFileId > 0: newFileInfo = fileService.getFileInformation(newFileId) if newFileInfo is not None: ft = newFileInfo.getFileType() ft.setValue(omero.rtypes.rstring("ReceptorLightFile")) newFileInfo.setFileType(ft) fSi = omero.rtypes.rint(int(fileSize)) newFileInfo.setSize(fSi) fileService.setFileInformation(newFileId, newFileInfo) dataPath = fileService.getDataDir() targetPath = dataPath + '/RL_FILES/' + \ str(newFileId) + '_' + fileName os.remove(targetPath) shutil.move(path, targetPath) txt = "FI_" + str(newFileId) else: txt = "FAIL:FileInfo was NULL." else: txt = "FAIL:FIleID was -1." else: txt = "FAIL:FileServer was NULL." return HttpResponse(txt) except Exception as e: txt = "FAIL:" + str(e) return HttpResponse(txt)
#!/usr/bin/python # #------------------------------------------------------------------------------ # Copyright (C) 2006-2008 University of Dundee. All rights reserved. # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #------------------------------------------------------------------------------ # import omero client = omero.client(["--Ice.Config=./ice.config"]) session = client.createSession("root", "omero") client.getSession().createRawPixelsStore()
def get_admin_service(conn): sessionId = conn.getEventContext().sessionUuid c = omero.client(thisHost, thisPort) sf = c.joinSession(sessionId) return sf.getAdminService()
def testCreateUserSession(self): iSession = self.client.sf.getSessionService() newSession = iSession.createUserSession(10 * 1000, 10 * 1000, self.ctx.groupName) c = omero.client(self.client.getPropertyMap()) c.joinSession(newSession.uuid.val)
if option == "-u": username = argument if option == "-k": session_key = argument if option == "--dry-run": dry_run = True if session_key is None: print "Username: %s" % username try: password = getpass.getpass() except KeyboardInterrupt: sys.exit(2) try: client = omero.client('localhost') client.setAgent("OMERO.cleanse") if session_key is None: client.createSession(username, password) else: client.createSession(session_key) except PermissionDeniedException: print "%s: Permission denied" % sys.argv[0] print "Sorry." sys.exit(1) try: cleanse(data_dir, client, dry_run) finally: if session_key is None: client.closeSession()
def testChangeActiveGroupWhenConnectionLost(self): import os client = self.new_client() admin = client.sf.getAdminService() uuid = client.sf.getAdminService().getEventContext().sessionUuid assert 2 == len(admin.getEventContext().memberOfGroups) # AS ROOT: adding user to extra group admin_root = self.root.sf.getAdminService() exp = admin_root.getExperimenter(admin.getEventContext().userId) grp = self.new_group() admin_root.addGroups(exp, [grp]) assert 3 == len(admin.getEventContext().memberOfGroups) proxies = dict() # creating stateful services proxies['search'] = client.sf.createSearchService() # 1A proxies['thumbnail'] = client.sf.createThumbnailStore() # 1B proxies['admin'] = client.sf.getAdminService() copy = dict(proxies) # loosing the connection # ... # joining session c = omero.client( pmap=['--Ice.Config=' + (os.environ.get("ICE_CONFIG"))]) host = c.ic.getProperties().getProperty('omero.host') port = int(c.ic.getProperties().getProperty('omero.port')) c = omero.client(host=host, port=port) sf = c.joinSession(uuid) # retriving stateful services proxies['search'] = sf.createSearchService() # 2A proxies['thumbnail'] = sf.createThumbnailStore() # 2B proxies['admin'] = sf.getAdminService() # changing group for k in proxies.keys(): prx = proxies[k] if isinstance(prx, omero.api.StatefulServiceInterfacePrx): prx.close() """ A security violation must be thrown here because the first instances which are stored in proxies (#1A and #1B) are never closed since #2A and #2B overwrite them. Using the copy instance, we can close them. """ with pytest.raises(omero.SecurityViolation): sf.setSecurityContext( omero.model.ExperimenterGroupI(grp.id.val, False)) for k in copy.keys(): prx = copy[k] if isinstance(prx, omero.api.StatefulServiceInterfacePrx): prx.close() sf.setSecurityContext(omero.model.ExperimenterGroupI( grp.id.val, False)) ec = admin.getEventContext() sf.getAdminService().setDefaultGroup( sf.getAdminService().getExperimenter(ec.userId), omero.model.ExperimenterGroupI(grp.id.val, False)) assert grp.id.val == ec.groupId
def setup_method(self, method): self.cli = omero.client() un = unwrap(self.user.getOmeName()) self.sess = self.cli.createSession(un, un)
def connection(host=None, user=None, password=None, port=None, verbose=1): """ Connect to the IDR analysis OMERO server Lookup of connection parameters is done in this order: 1. If host/IDR_HOST starts with protocol:// and protocol is not an Ice transport treat this as a full omero-client.json configuration URL and fetch it 2. If host/IDR_HOST starts with an Ice transport:// connect directly 3. If host/IDR_HOST is defined but port/IDR_PORT empty and there is no protocol then attempt to fetch configuration from https://host/connection/omero-client.json 4. Remaining parameters are taken first from the method arguments, then from IDR_{HOST,PORT,USER,PASSWORD} 5. If host/IDR_HOST was a configuration URL then automatically set host to the host portion of the URL in case it needs to be substituted into the fetched configuration To support firewalled environments if host/IDR_HOST has no protocol and the connection fails automatically attempt to reconnect using websockets (wss) on port 443. No defaults are provided :return: A BlitzGateway object """ host = _lookup_parameter(host, "host", "") port = int(_lookup_parameter(port, "port", 0)) user = _lookup_parameter(user, "user", None) password = _lookup_parameter(password, "password", None) autocfg = [] if ((host and not port) or re.match(r"\w+://", host)) and ( not _host_includes_ice_proto(host) ): autocfg, host = _configuration_from_url(host) # https://github.com/openmicroscopy/openmicroscopy/blob/v5.4.3/components/tools/OmeroPy/src/omero/clients.py#L50 kwargs = {"args": autocfg} if host: kwargs["host"] = host if port: kwargs["port"] = port c = omero.client(**kwargs) # If omero.user and omero.pass were included in omero-client.json # they can optionally be omitted in createSession create_session_args = [] if user: create_session_args.append(user) if password: create_session_args.append(password) try: c.createSession(*create_session_args) c.enableKeepAlive(300) conn = BlitzGateway(client_obj=c) except omero.ClientError as e: if re.match(r"\w+://", host): raise print( "Failed to connect: {}, retrying with websockets".format(e), file=sys.stderr ) return connection( "wss://{}/omero-ws".format(host), user, password, 443, verbose ) if verbose > 0: server = "" if verbose > 1: info = conn.c.sf.ice_getConnection().getInfo() server = "[{}:{}]".format(info.remoteAddress, info.remotePort) print("Connected to IDR%s ..." % server) return conn
if option == "--url": es = Elasticsearch([argument], verify_certs=True, timeout=60) if option == "--index": index = argument if option == "--screen": screen_ids.append(long(argument)) if option == "--project": project_ids.append(long(argument)) if _all is False and len(screen_ids) < 1 and len(project_ids) < 1: usage('Either -a, Project or Screen hierarchy specification required!') format = "%(asctime)s %(levelname)-7s [%(name)16s] %(message)s" logging.basicConfig(level=level, format=format) client = omero.client(server, port) client.createSession(username, password) try: if _all: project_ids = find_project_ids(client) screen_ids = find_screen_ids(client) log.info('Found %d Projects' % len(project_ids)) log.info('Found %d Screens' % len(screen_ids)) index_projects(es, index, client, project_ids) index_screens(es, index, client, screen_ids) finally: client.closeSession() if __name__ == '__main__':
def get_connection(ic1): cli = omero.client(args=['--Ice.Config=%s' % ic1]) sess = cli.createSession() conn = omero.gateway.BlitzGateway(client_obj=cli) conn.SERVICE_OPTS.setOmeroGroup(-1) return conn
# # $Id$ # # Copyright 2008 Glencoe Software, Inc. All rights reserved. # Use is subject to license terms supplied in LICENSE.txt # import omero, omero.scripts as sc client = sc.client( "script_1", """ This is a test script used to test the basic parsing functionality and attempts to interaction with the server """, #sc.Int("myint"), sc.Long("mylong"), sc.Bool("mybool"), sc.String("mystring"), sc.String("myoptional", optional=True)) import os, sys, types assert type(client) == types.TupleType self = sys.argv[0] cfg = self.replace("py", "cfg") real_client = omero.client(["--Ice.Config=%s" % cfg]) parse_only = real_client.getProperty("omero.script.parse") assert parse_only == "true"
if "clean" in args: cleanUpScriptFiles(session, scriptService) if __name__ == "__main__": commandArgs, args = readCommandArgs() if "help" in args: printHelp(args) elif "host" not in commandArgs: print "No server specified. Use -s serverName" print "For more info, use: python adminWorkflow help" elif "username" not in commandArgs: print "No user specified. Use -u userName" print "For more info, use: python adminWorkflow help" else: client = omero.client(commandArgs["host"]) try: # log on to the server, create client and session and scripting # service if "password" not in commandArgs: print "NB: you can also run script with -p yourPassword" commandArgs["password"] = getpass.getpass() doWorkflow(client, commandArgs) except: raise finally: client.closeSession()
import omero c = omero.client("localhost") s = c.createSession("root", "ome") admin = s.getAdminService() _ = omero.rtypes.rstring # Users try: owner = admin.lookupExperimenter("owner") except omero.ApiUsageException: owner = omero.model.ExperimenterI() owner.omeName = _("owner") owner.firstName = _("first") owner.lastName = _("last") try: nonOwner = admin.lookupExperimenter("nonOwner") except omero.ApiUsageException: nonOwner = omero.model.ExperimenterI() nonOwner.omeName = _("nonOwner") nonOwner.firstName = _("first") nonOwner.lastName = _("last") try: group = admin.lookupGroup("group") except omero.ApiUsageException: group = omero.model.ExperimenterGroupI() group.name = _("group") if not group.id: gid = admin.createGroup(group)
def client(*args, **kwargs): """ Entry point for all script engine scripts. Typical usage consists of:: client = omero.scripts.client("name","description", \ omero.scripts.Long("name"),...) where the returned client is created via the empty constructor to omero.client using only --Ice.Config or ICE_CONFIG, and the function arguments are taken as metdata about the current script. With this information, all script consumers should be able to determine the required types for execution. Possible types are all subclasses of omero.scripts.Type To change the omero.model.Format of the stdout and stderr produced by this script, use the constructor arguments:: client = omero.scripts.client(..., \ stdoutFormat = "text/plain", stderrFormat = "text/plain") If you would like to prevent stdout and/or stderr from being uploaded, set the corresponding value to None. If you would like to overwrite the value with another file, use client.setOutput(). Though it is possible to attach any RType to "stdout" or "stderr", there is an assumption that the value will be an robject(OriginalFileI()) Providing your own client is possible via the kwarg "client = ...", but be careful since this may break usage with the rest of the scripting framework. The client should not have a session, and must be configured for the argumentless version of createSession() """ args = list(args) if len(args) >= 1: if isinstance(args[0], str): kwargs["name"] = args.pop(0) if len(args) >= 1: if isinstance(args[0], str): kwargs["description"] = args.pop(0) if not kwargs.has_key("client"): kwargs["client"] = omero.client() c = kwargs["client"] c.setAgent("OMERO.scripts") if args and isinstance(args[0], omero.grid.JobParams): c.params = args.pop(0) else: c.params = omero.grid.JobParams() c.params.inputs = {} c.params.outputs = {} for k, v in kwargs.items(): if hasattr(c.params, k): setattr(c.params, k, v) if not c.params.stdoutFormat: c.params.stdoutFormat = "text/plain" if not c.params.stderrFormat: c.params.stderrFormat = "text/plain" for p in args: if isinstance(p, Type): if p._in: c.params.inputs[p._name] = p if p._out: c.params.outputs[p._name] = p else: raise ValueError("Not Type: %s" % type(p)) handleParse(c) # May throw c.createSession().detachOnDestroy() return c
""" Uses the default {@link DeleteCallbackI} instance. """ import omero import omero.callbacks c = omero.client() s = c.createSession() class Subclass(omero.callbacks.DeleteCallbackI): def finished(self, errors): omero.callbacks.DeleteCallbackI.finished(self, errors) print "Finished. Error count=%s" % errors try: reports = self.handle.report() for r in reports: print "Report:error=%s,warning=%s,deleted=%s" % \ (r.error, r.warning, r.actualDeletes) except omero.ServerError: print "Something happened to the handle?!?" try: deleteServicePrx = s.getDeleteService() dc = omero.api.delete.DeleteCommand("/Image", 1, None) deleteHandlePrx = deleteServicePrx.queueDelete([dc]) cb = Subclass(c, deleteHandlePrx)
def create_client_session(self, user): cli = omero.client() self.clis.append(cli) un = unwrap(user.getOmeName()) sess = cli.createSession(un, un) return sess
# # Copyright (C) 2015 University of Dundee & Open Microscopy Environment. # All Rights Reserved. # Use is subject to license terms supplied in LICENSE.txt # """ FOR TRAINING PURPOSES ONLY! Change this file to Parse_OMERO_Properties.py and enter your ID/username """ import omero client = omero.client('omero-app.research.uts.edu.au') omeroProperties = client.getProperties().getPropertiesForPrefix('omero') # Configuration # ================================================================= # These values will be imported by all the other training scripts. HOST = omeroProperties.get('omero.host', 'omero-app.research.uts.edu.au') PORT = omeroProperties.get('omero.port', 4064) USERNAME = omeroProperties.get('omero.user','111111') PASSWORD = omeroProperties.get('omero.pass','your-password') OMERO_WEB_HOST = omeroProperties.get('omero.webhost') SERVER_NAME = omeroProperties.get('omero-app.research.uts.edu.au') #projectId = omeroProperties.get('omero.projectid') #datasetId = omeroProperties.get('omero.datasetid') #imageId = omeroProperties.get('omero.imageid')
import sys import omero import Usage, AllProjects, PrintProjects if __name__ == "__main__": try: host = sys.argv[1] port = sys.argv[2] user = sys.argv[3] pasw = sys.argv[4] except: Usage.usage() client = omero.client(sys.argv) try: factory = client.createSession(user, pasw) projects = AllProjects.getProjects(factory.getQueryService(), user) PrintProjects.print_(projects) finally: client.closeSession()
################ to be changed depending on data input_dataset_id = 4702 #Dataset ID where individual images are output_dataset_id = 4853 #Dataset ID where combined images will be stored session_id = '4b2c3d7c-962e-414a-abf2-af21d109183f' #session id filter_pattern = 'Well\w{3}_Field\w{2}' parameter_map = {} parameter_map["Channel_Name_Pattern"] = 'None' parameter_map["Time_Name_Pattern"] = 'Time' parameter_map["Z_Name_Pattern"] = 'None' parameter_map["Channel_Colours"]=['Green','Red','White'] ################## client = omero.client("omero.hms.harvard.edu") session = client.joinSession(session_id) conn = BlitzGateway(client_obj=client) #get DataSet input_dataset = conn.getObject("Dataset",input_dataset_id) #input dataset output_dataset = conn.getObject("Dataset",output_dataset_id) images = list(input_dataset.listChildren()) images.sort(key=lambda x: x.name.lower()) image_ids = [x.getId() for x in images] image_names = [x.name for x in images] images_output = list(output_dataset.listChildren()) images_names_output = [x.name for x in images_output]
def get_receptor_light_file_service(conn): sessionId = conn.getEventContext().sessionUuid c = omero.client(thisHost, thisPort) sf = c.joinSession(sessionId) return sf.getReceptorLightFileManager()