Ejemplo n.º 1
0
    def download(self, ofile, filename = None, block_size = 1024*1024, filehandle = None):
        prx = self.__sf.createRawFileStore()
        try:
            if not ofile or not ofile.id:
                raise omero.ClientError("No file to download")
            ofile = self.__sf.getQueryService().get("OriginalFile", ofile.id.val)

            if block_size > ofile.size.val:
                block_size = ofile.size.val

            prx.setFileId(ofile.id.val)

            size = ofile.size.val
            offset = 0

            if filehandle is None:
                if filename is None:
                    raise omero.ClientError("no filename or filehandle specified")
                filehandle = open(filename, 'wb')
            else:
                if filename:
                    raise omero.ClientError("filename and filehandle specified.")

            try:
                while (offset+block_size) < size:
                    filehandle.write(prx.read(offset, block_size))
                    offset += block_size
                filehandle.write(prx.read(offset, (size-offset)))
            finally:
                if filename:
                    filehandle.close()
        finally:
            prx.close()
Ejemplo n.º 2
0
    def forEachTile(self, tileWidth, tileHeight, iteration):
        """
        Iterates over every tile in a given Pixels object based on the
        over arching dimensions and a requested maximum tile width and height.
        :param tileWidth: <b>Maximum</b> width of the tile requested. The tile
        request itself will be smaller than the original tile width requested
        if <code>x + tileWidth > sizeX</code>.
        :param tileHeight: <b>Maximum</b> height of the tile requested.
        The tile request itself will be smaller if
        <code>y + tileHeight > sizeY</code>.
        :param iteration: Invoker to call for each tile.
        @return The total number of tiles iterated over.
        """

        if self.pixels is None or self.pixels.id is None:
            import omero
            raise omero.ClientError("pixels instance must be managed!")
        elif not self.pixels.loaded:
            try:
                srv = self.getSession().getPixelsService()
                self.pixels = srv.retrievePixDescription(self.pixels.id.val)
            except Exception, e:
                import omero
                raise omero.ClientError("Failed to load %s\n%s" %
                                        (self.pixels.id.val, e))
Ejemplo n.º 3
0
    def download(self,
                 ofile,
                 filename=None,
                 block_size=1024 * 1024,
                 filehandle=None):
        if not self.__sf:
            raise omero.ClientError("No session. Use createSession first.")

        # Search for objects in all groups. See #12146
        ctx = self.getContext(group=-1)
        prx = self.__sf.createRawFileStore()

        try:
            if not ofile or not ofile.id:
                raise omero.ClientError("No file to download")
            ofile = self.__sf.getQueryService().get("OriginalFile",
                                                    ofile.id.val, ctx)

            prx.setFileId(ofile.id.val, ctx)
            size = None
            if prx.size() is None:
                name = omero.rtypes.unwrap(ofile.name)
                mimetype = omero.rtypes.unwrap(ofile.mimetype)
                raise omero.ClientError(("invalid size for OriginalFile '%s' "
                                         "(mimetype:%s)") % (name, mimetype))
            else:
                size = prx.size()

            if block_size > size:
                block_size = size

            if filehandle is None:
                if filename is None:
                    raise omero.ClientError(
                        "no filename or filehandle specified")
                filehandle = open(filename, 'wb')
            else:
                if filename:
                    raise omero.ClientError(
                        "filename and filehandle specified.")

            offset = 0
            try:
                while (offset + block_size) < size:
                    filehandle.write(prx.read(offset, block_size))
                    offset += block_size
                filehandle.write(prx.read(offset, (size - offset)))
            finally:
                if filename:
                    filehandle.close()
        finally:
            prx.close()
 def reloadLogs(self, toCopy, current=None):
     self.errorIfUnloaded()
     if self._logsLoaded:
         raise omero.ClientError("Cannot reload active collection: logsSeq")
     if not toCopy:
         raise omero.ClientError("Argument cannot be null")
     if toCopy.getId().getValue() != self.getId().getValue():
         raise omero.ClientError(
             "Argument must have the same id as this instance")
     copy = toCopy.copyLogs()  # May also throw
     for elt in copy:
         elt.setEvent(self)
     self._logsSeq = copy
     toCopy.unloadLogs()
     self._logsLoaded = True
 def shallowCopy(self, current=None):
     if not self._loaded: return self.proxy()
     copy = ScriptJobI()
     copy._id = self._id
     copy._version = self._version
     copy._details = None  # Unloading for the moment.
     raise omero.ClientError("NYI")
 def shallowCopy(self, current=None):
     if not self._loaded: return self.proxy()
     copy = LightPathEmissionFilterLinkI()
     copy._id = self._id
     copy._version = self._version
     copy._details = None  # Unloading for the moment.
     raise omero.ClientError("NYI")
Ejemplo n.º 7
0
 def shallowCopy(self, current=None):
     if not self._loaded: return self.proxy()
     copy = PlateAcquisitionAnnotationLinkI()
     copy._id = self._id
     copy._version = self._version
     copy._details = None  # Unloading for the moment.
     raise omero.ClientError("NYI")
Ejemplo n.º 8
0
 def shallowCopy(self, current = None):
       if not self._loaded: return self.proxy()
       copy = ReverseIntensityContextI()
       copy._id = self._id;
       copy._version = self._version;
       copy._details = None  # Unloading for the moment.
       raise omero.ClientError("NYI")
Ejemplo n.º 9
0
 def reloadAnnotationLinks(self, toCopy, current = None):
     self.errorIfUnloaded()
     if self._annotationLinksLoaded:
         raise omero.ClientError("Cannot reload active collection: annotationLinksSeq")
     if not toCopy:
         raise omero.ClientError("Argument cannot be null")
     if toCopy.getId().getValue() != self.getId().getValue():
        raise omero.ClientError("Argument must have the same id as this instance")
     if toCopy.getDetails().getUpdateEvent().getId().getValue() < self.getDetails().getUpdateEvent().getId().getValue():
        raise omero.ClientError("Argument may not be older than this instance")
     copy = toCopy.copyAnnotationLinks() # May also throw
     for elt in copy:
         elt.setParent( self )
     self._annotationLinksSeq = copy
     toCopy.unloadAnnotationLinks()
     self._annotationLinksLoaded = True
 def shallowCopy(self, current = None):
       if not self._loaded: return self.proxy()
       copy = WellReagentLinkI()
       copy._id = self._id;
       copy._version = self._version;
       copy._details = None  # Unloading for the moment.
       raise omero.ClientError("NYI")
Ejemplo n.º 11
0
    def getRouter(self, comm):
        """
        Acquires the default router, and throws an exception
        if it is not of type Glacier2.Router. Also sets the
        Ice.ImplicitContext on the router proxy.
        """
        prx = comm.getDefaultRouter()
        if not prx:
            raise omero.ClientError("No default router found.")
        router = Glacier2.RouterPrx.uncheckedCast(prx)
        if not router:
            raise omero.ClientError("Error obtaining Glacier2 router")

        # For whatever reason, we have to set the context
        # on the router context here as well
        router = router.ice_context(comm.getImplicitContext().getContext())
        return router
Ejemplo n.º 12
0
    def download(self,
                 ofile,
                 filename=None,
                 block_size=1024 * 1024,
                 filehandle=None):
        if not self.__sf:
            raise omero.ClientError("No session. Use createSession first.")

        # Search for objects in all groups. See #12146
        ctx = self.getContext(group=-1)
        prx = self.__sf.createRawFileStore()

        try:
            if not ofile or not ofile.id:
                raise omero.ClientError("No file to download")
            ofile = self.__sf.getQueryService().get("OriginalFile",
                                                    ofile.id.val, ctx)

            if block_size > ofile.size.val:
                block_size = ofile.size.val

            prx.setFileId(ofile.id.val, ctx)

            size = ofile.size.val
            offset = 0

            if filehandle is None:
                if filename is None:
                    raise omero.ClientError(
                        "no filename or filehandle specified")
                filehandle = open(filename, 'wb')
            else:
                if filename:
                    raise omero.ClientError(
                        "filename and filehandle specified.")

            try:
                while (offset + block_size) < size:
                    filehandle.write(prx.read(offset, block_size))
                    offset += block_size
                filehandle.write(prx.read(offset, (size - offset)))
            finally:
                if filename:
                    filehandle.close()
        finally:
            prx.close()
Ejemplo n.º 13
0
 def __setattr__(self, attr, value):
     if attr == "val":
         if self.__dict__.has_key("_val"):
             raise omero.ClientError("Cannot write to val")
         else:
             self.__dict__["_val"] = value
     else:
         object.__setattr__(self, attr, value)
Ejemplo n.º 14
0
 def reloadLightSourceSettings(self, toCopy, current=None):
     self.errorIfUnloaded()
     if self._lightSourceSettingsLoaded:
         raise omero.ClientError(
             "Cannot reload active collection: lightSourceSettingsSeq")
     if not toCopy:
         raise omero.ClientError("Argument cannot be null")
     if toCopy.getId().getValue() != self.getId().getValue():
         raise omero.ClientError(
             "Argument must have the same id as this instance")
     if toCopy.getDetails().getUpdateEvent().getId().getValue(
     ) < self.getDetails().getUpdateEvent().getId().getValue():
         raise omero.ClientError(
             "Argument may not be older than this instance")
     copy = toCopy.copyLightSourceSettings()  # May also throw
     for elt in copy:
         elt.setMicrobeamManipulation(self)
     self._lightSourceSettingsSeq = copy
     toCopy.unloadLightSourceSettings()
     self._lightSourceSettingsLoaded = True
Ejemplo n.º 15
0
    def __init__(self, adapter_or_client, handle, category=None):

        if adapter_or_client is None:
            raise omero.ClientError("Null client")

        if handle is None:
            raise omero.ClientError("Null handle")

        self.event = omero.util.concurrency.get_event(name="CmdCallbackI")
        self.state = (None, None)  # (Response, Status)
        self.handle = handle
        self.adapter, self.category = \
                adapter_and_category(adapter_or_client, category)

        self.id = Ice.Identity(str(uuid.uuid4()), self.category)
        self.prx = self.adapter.add(self, self.id)  # OK ADAPTER USAGE
        self.prx = omero.cmd.CmdCallbackPrx.uncheckedCast(self.prx)
        handle.addCallback(self.prx)

        # Now check just in case the process exited VERY quickly
        self.poll()
Ejemplo n.º 16
0
    def __init__(self,
                 adapter_or_client,
                 handle,
                 category=None,
                 foreground_poll=True):

        if adapter_or_client is None:
            raise omero.ClientError("Null client")

        if handle is None:
            raise omero.ClientError("Null handle")

        self.event = omero.util.concurrency.get_event(name="CmdCallbackI")
        self.state = (None, None)  # (Response, Status)
        self.handle = handle
        self.adapter, self.category = \
            adapter_and_category(adapter_or_client, category)

        self.id = Ice.Identity(native_str(uuid.uuid4()), self.category)
        self.prx = self.adapter.add(self, self.id)  # OK ADAPTER USAGE
        self.prx = omero.cmd.CmdCallbackPrx.uncheckedCast(self.prx)
        handle.addCallback(self.prx)
        self.initialPoll(foreground_poll)
Ejemplo n.º 17
0
 def _env(self, _unwrap, method, *args):
     """ Helper method to access session environment"""
     session = self.getSession()
     if not session:
         raise omero.ClientError("No session active")
     u = self.getSessionId()
     s = session.getSessionService()
     m = getattr(s, method)
     rv = m(*(u,)+args)
     if callable(_unwrap):
         rv = _unwrap(rv)  # Passed in function
     elif _unwrap:
         rv = omero.rtypes.unwrap(rv)  # Default method
     return rv
Ejemplo n.º 18
0
 def block(self, ms):
     """
     Should only be used if the default logic of the handle methods is kept
     in place. If "event.set" does not get called, this method will always
     block for the given milliseconds.
     """
     if self.poll:
         try:
             if self.handle.finished():
                 try:
                     self.finished(self.handle.errors())
                 except Exception, e:
                     DEL_LOG.warn("Error calling DeleteCallbackI.finished: %s" % e, exc_info=True)
         except Ice.ObjectNotExistException, onee:
             raise omero.ClientError("Handle is gone! %s" % self.handle)
         except:
Ejemplo n.º 19
0
def adapter_and_category(adapter_or_client, category):
    if isinstance(adapter_or_client, Ice.ObjectAdapter):
        # This should be the case either when an
        # instance is created server-side or when
        # the user has passed in a category
        # explicitly. If it's missing, then we'll
        # have to throw
        if not category:
            raise omero.ClientError("No category available")
        return adapter_or_client, category
    else:
        # This is the case client-side, where an
        # omero.client instance is available.
        # If a category is passed we use that
        # (though it's unlikely that that will be useful)
        if not category:
            category = adapter_or_client.getCategory()
        return adapter_or_client.getAdapter(), category
Ejemplo n.º 20
0
def rtype(val):
    """
    If None or an RType, return the argument itself. Otherwise,
    attempts to dispatch to the other omero.rtypes.* static methods
    to create a proper {@link RType} subclass by checking the type
    of the input. If no conversion is found, a {@link ClientError} is
    thrown.

    Note: unlike the statically typed languages, the rtype implementation
    in Python is somewhat limited by the lack of types (float v. double)
    All float-like values will produce an omero.RFloat subclass. Similar
    problems may arise with rlong and rint
    """
    if val is None:
        return None
    elif isinstance(val, omero.RType):
        return val
    elif isinstance(val, bool):
        return rbool(val)
    elif isinstance(val, int):
        return rint(val)
    elif isinstance(val, long):  # Maintains Py2 compatibility
        return rlong(val)
    elif isinstance(val, float):
        return rfloat(val)
    elif isinstance(val, basestring):
        return rstring(val)
    elif isinstance(val, omero.model.IObject):
        return robject(val)
    elif isinstance(val, omero.Internal):
        return rinternal(val)
    elif isinstance(val, list):
        return rlist(val)
    elif isinstance(val, set):
        return rset(val)
    elif isinstance(val, dict):
        return rmap(val)
    else:
        raise omero.ClientError("Cannot handle conversion from: %s" %
                                type(val))
Ejemplo n.º 21
0
 def proxy(self, current=None):
     if self._id is None: raise omero.ClientError("Proxies require an id")
     return MicroscopeTypeI(self._id.getValue(), False)
 def proxy(self, current = None):
     if self._id is None: raise omero.ClientError("Proxies require an id")
     return WellReagentLinkI( self._id.getValue(), False )
 def proxy(self, current=None):
     if self._id is None: raise omero.ClientError("Proxies require an id")
     return FilesetAnnotationLinkI(self._id.getValue(), False)
Ejemplo n.º 24
0
    def upload(self,
               filename,
               name=None,
               path=None,
               type=None,
               ofile=None,
               block_size=1024):
        """
        Utility method to upload a file to the server.
        """
        if not self.__sf:
            raise omero.ClientError("No session. Use createSession first.")

        import os, types
        if not filename or not isinstance(filename, types.StringType):
            raise omero.ClientError("Non-null filename must be provided")

        if not os.path.exists(filename):
            raise omero.ClientError("File does not exist: " + filename)

        from path import path as __path__
        filepath = __path__(filename)
        file = open(filename, 'rb')
        try:

            size = os.path.getsize(file.name)
            if block_size > size:
                block_size = size

            if not ofile:
                ofile = omero.model.OriginalFileI()

            ofile.hash = omero.rtypes.rstring(self.sha1(file.name))
            ofile.hasher = omero.model.ChecksumAlgorithmI()
            ofile.hasher.value = omero.rtypes.rstring("SHA1-160")

            abspath = filepath.normpath().abspath()
            if not ofile.name:
                if name:
                    ofile.name = omero.rtypes.rstring(name)
                else:
                    ofile.name = omero.rtypes.rstring(str(abspath.basename()))

            if not ofile.path:
                ofile.path = omero.rtypes.rstring(
                    str(abspath.dirname()) + os.path.sep)

            if not ofile.mimetype:
                if type:
                    # ofile.mimetype = 'application/octet-stream' by default
                    ofile.mimetype = omero.rtypes.rstring(type)

            # Disabled with group permissions #1434
            # if permissions:
            #    ofile.details.permissions = permissions

            up = self.__sf.getUpdateService()
            ofile = up.saveAndReturnObject(ofile)

            prx = self.__sf.createRawFileStore()
            try:
                prx.setFileId(ofile.id.val)
                prx.truncate(size)  # ticket:2337
                self.write_stream(file, prx, block_size)
            finally:
                prx.close()
        finally:
            file.close()

        return ofile
Ejemplo n.º 25
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
                    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
Ejemplo n.º 26
0
                    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

            if not prx:
                raise omero.ClientError("Obtained null object prox")

            # Check type
            self.__sf = omero.api.ServiceFactoryPrx.uncheckedCast(prx)
            if not self.__sf:
                raise omero.ClientError(
                    "Obtained object proxy is not a ServiceFactory")

            # Configure keep alive
            self.startKeepAlive()

            # Set the client callback on the session
            # and pass it to icestorm
            try:

                raw = self.__oa.createProxy(self.__cb.id)
Ejemplo n.º 27
0
 def proxy(self, current=None):
     if self._id is None: raise omero.ClientError("Proxies require an id")
     return ChecksumAlgorithmI(self._id.getValue(), False)
Ejemplo n.º 28
0
 def shallowCopy(self, current=None):
     if not self._loaded: return self.proxy()
     copy = ChecksumAlgorithmI()
     copy._id = self._id
     copy._details = None  # Unloading for the moment.
     raise omero.ClientError("NYI")
 def proxy(self, current=None):
     if self._id is None: raise omero.ClientError("Proxies require an id")
     return ScriptJobI(self._id.getValue(), False)
 def shallowCopy(self, current = None):
       if not self._loaded: return self.proxy()
       copy = ProjectionAxisI()
       copy._id = self._id;
       copy._details = None  # Unloading for the moment.
       raise omero.ClientError("NYI")