def test1088(self):
        admin = self.root.sf.getAdminService()
        q = self.root.sf.getQueryService()
        cx = admin.getEventContext()

        p = omero.sys.Parameters()
        p.map = {}
        p.map["uid"] = rlong(cx.userId)
        p.map['start'] = start = rtime(1218529874000)
        p.map['end'] = end = rtime(1221121874000)

        sql1 = "select el from EventLog el left outer join fetch el.event ev " \
               "where el.entityType in ('ome.model.core.Pixels', 'ome.model.core.Image', " \
               "'ome.model.containers.Dataset', 'ome.model.containers.Project') " \
               "and ev.id in (select id from Event where experimenter.id=:uid and time > :start and time < :end)"


        sql2 = "select el from EventLog el left outer join fetch el.event ev " \
               "where el.entityType in ('ome.model.core.Pixels', 'ome.model.core.Image', " \
               "'ome.model.containers.Dataset', 'ome.model.containers.Project') " \
               "and ev.experimenter.id=:uid and ev.time > :start and ev.time < :end"

        import time
        sql1_start = time.time()
        l = q.findAllByQuery(sql1, p)
        sql1_stop = time.time()
        # print "\nSQL1: %s objects in %s seconds" % (str(len(l)), str(sql1_stop - sql1_start))

        sql2_start = time.time()
        l = q.findAllByQuery(sql2, p)
        sql2_stop = time.time()
    def test1173(self):
        uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
        timeline = self.root.sf.getTimelineService()

        # create image
        ds = self.make_dataset(name='test1173-ds-%s' % uuid, client=self.root)
        ds.unload()

        # Here we assume that this test is not run within the last 1 second
        start = long(time.time() * 1000 - 86400)
        end = long(time.time() * 1000 + 86400)

        p = omero.sys.Parameters()
        p.map = {}
        f = omero.sys.Filter()
        f.ownerId = rlong(self.new_user().id.val)
        p.theFilter = f

        M = timeline.getEventLogsByPeriod
        A = rtime(long(start))
        B = rtime(long(end))

        rv = M(A, B, p)
        assert rv > 0

        # And now for #9609
        rv = M(A, B, p, {"omero.group": "-1"})
        assert rv > 0
    def testGeneral(self):
        uuid = self.ctx.sessionUuid
        timeline = self.sf.getTimelineService()

        im_ids = dict()
        for i in range(0, 10):
            # create image
            acquired = long(time.time() * 1000)
            img = self.make_image(name='test-img-%s' % uuid, date=acquired)
            im_ids[i] = [img.id.val, acquired]

        # Here we assume that this test is not run within the last 1 second
        start = acquired - 86400
        end = acquired + 1

        p = omero.sys.Parameters()
        p.map = {}
        f = omero.sys.Filter()
        f.ownerId = rlong(self.ctx.userId)
        f.groupId = rlong(self.ctx.groupId)
        p.theFilter = f

        M = timeline.countByPeriod
        A = rtime(long(start))
        B = rtime(long(end))
        counter = M(['Image'], A, B, p)
        assert counter['Image'] == 10
        # And with #9609
        counter = M(['Image'], A, B, p, {"omero.group": "-1"})
        assert counter['Image'] == 10

        p2 = omero.sys.Parameters()
        p2.map = {}
        f2 = omero.sys.Filter()
        f2.ownerId = rlong(self.ctx.userId)
        f2.groupId = rlong(self.ctx.groupId)
        f2.limit = rint(5)
        p2.theFilter = f2

        # p.map["start"] = rtime(long(start))
        # p.map["end"] = rtime(long(end))

        M = timeline.getMostRecentObjects
        res = M(['Image'], p2, False)["Image"]
        assert 5 == len(res)
        # And with #9609
        res = M(['Image'], p2, False, {"omero.group": "-1"})["Image"]
        assert 5 == len(res)

        # 1st element should be the 9th from the im_ids
        assert im_ids[9][0] == res[0].id.val
        # 2nd element should be the 8th from the im_ids
        assert im_ids[8][0] == res[1].id.val
        # 3rd element should be the 7th from the im_ids
        assert im_ids[7][0] == res[2].id.val
        # 4th element should be the 6th from the im_ids
        assert im_ids[6][0] == res[3].id.val
        # 5th element should be the 5th from the im_ids
        assert im_ids[5][0] == res[4].id.val
Пример #4
0
def wrapped_image():
    image = ImageI()
    image.id = rlong(1L)
    image.description = rstring('description')
    image.name = rstring('name')
    image.acquisitionDate = rtime(1000)  # In milliseconds
    image.details.owner = ExperimenterI(1L, False)
    creation_event = EventI()
    creation_event.time = rtime(2000)  # In milliseconds
    image.details.creationEvent = creation_event
    return ImageWrapper(conn=MockConnection(), obj=image)
 def testTimes(self):
     p = ParametersI()
     self.assertNull(p.theFilter)
     p.startTime(rtime(0))
     self.assertNotNull(p.theFilter)
     self.assertNotNull(p.theFilter.startTime)
     p.endTime(rtime(1))
     self.assertNotNull(p.theFilter.endTime)
     p.allTimes()
     self.assertNotNull(p.theFilter)
     self.assertNull(p.theFilter.startTime)
     self.assertNull(p.theFilter.endTime)
Пример #6
0
def screen_with_plates(screen):
    for plate_id in range(5, 7):
        o = PlateI()
        o.id = rlong(plate_id)
        o.name = rstring('plate_name_%d' % plate_id)
        o.description = rstring('plate_description_%d' % plate_id)
        o.columnNamingConvention = rstring('number')
        o.rowNamingConvention = rstring('letter')
        o.columns = rint(12)
        o.rows = rint(8)
        o.defaultSample = rint(0)
        o.externalIdentifier = rstring('external_identifier_%d' % plate_id)
        o.status = rstring('status_%d' % plate_id)
        o.wellOriginX = LengthI(0.1, UnitsLength.REFERENCEFRAME)
        o.wellOriginY = LengthI(1.1, UnitsLength.REFERENCEFRAME)
        screen.linkPlate(o)
        for well_id in range(7, 9):
            well = WellI()
            well.id = rlong(well_id)
            well.column = rint(2)
            well.row = rint(1)
            well.externalDescription = \
                rstring('external_description_%d' % well_id)
            well.externalIdentifier = \
                rstring('external_identifier_%d' % well_id)
            well.type = rstring('the_type')
            well.alpha = rint(0)
            well.red = rint(255)
            well.green = rint(0)
            well.blue = rint(0)
            well.status = rstring('the_status')
            o.addWell(well)
            plateacquisition = PlateAcquisitionI()
            plateacquisition.id = rlong(well_id)
            plateacquisition.name = rstring(
                'plateacquisition_name_%d' % well_id)
            plateacquisition.description = rstring(
                'plateacquisition_description_%d' % well_id)
            plateacquisition.maximumFieldCount = rint(1)
            plateacquisition.startTime = rtime(1L)
            plateacquisition.endTime = rtime(2L)
            for wellsample_id in range(9, 11):
                wellsample = WellSampleI()
                wellsample.setPlateAcquisition(plateacquisition)
                wellsample.id = rlong(wellsample_id)
                wellsample.posX = LengthI(1.0, UnitsLength.REFERENCEFRAME)
                wellsample.posY = LengthI(2.0, UnitsLength.REFERENCEFRAME)
                wellsample.timepoint = rtime(1L)
                wellsample.image = create_image(1L)
                well.addWellSample(wellsample)

    return screen
Пример #7
0
 def testGetAttrWorks(self):
     rbool(True).val
     rdouble(0.0).val
     rfloat(0.0).val
     rint(0).val
     rlong(0).val
     rtime(0).val
     rinternal(None).val
     robject(None).val
     rstring("").val
     rclass("").val
     rarray().val
     rlist().val
     rset().val
     rmap().val
Пример #8
0
    def testWrappers(self):
        image = ImageI()
        info = image._field_info

        assert info.name.wrapper == rstring
        assert info.acquisitionDate.wrapper == rtime

        assert not info.name.nullable
        assert not info.acquisitionDate.nullable

        image.setAcquisitionDate("1", wrap=True)
        assert type(image.acquisitionDate) == type(rtime(0))

        # The following causes pytest to fail!
        # image.setAcquisitionDate("", wrap=True)

        # Note: collections still don't work well
        if False:
            image.addPixels(PixelsI())
            image.setPixels(0, "Pixels:1", wrap=True)
            assert type(image.pixels) == omero.model.PixelsI

            image.setPixels(0, "Pixels", wrap=True)
            image.setPixels(0, "Unknown", wrap=True)

        link = DatasetImageLinkI()
        link.setParent("Dataset:1")
        link.setChild("Image:1")
        def assert_timeline(timeline, start, end, ownerId=None, groupId=None):
            p = omero.sys.Parameters()
            p.map = {}
            f = omero.sys.Filter()
            if ownerId is not None:
                f.ownerId = ownerId
            if groupId is not None:
                f.groupId = groupId
            p.theFilter = f

            counter = timeline.countByPeriod(
                ['Image'], rtime(long(start)), rtime(long(end)), p)
            assert 10 == counter['Image']
            data = timeline.getByPeriod(
                ['Image'], rtime(long(start)), rtime(long(end)), p, False)
            assert 10 == len(data['Image'])
    def test_edit_share(self):

        # create images
        images = [self.createTestImage(session=self.sf),
                  self.createTestImage(session=self.sf)]

        sid = self.sf.getShareService().createShare(
            "foobar", rtime(None), images, [self.user], [], True)

        request_url = reverse("manage_action_containers",
                              args=["save", "share", sid])

        data = {
            'enable': 'on',
            'image': [i.id.val for i in images],
            'members': self.user.id.val,
            'message': 'another foobar'
        }
        _post_response(self.django_client, request_url, data)
        _csrf_post_response(self.django_client, request_url, data)

        # remove image from share
        request_url = reverse("manage_action_containers",
                              args=["removefromshare", "share", sid])
        data = {
            'source': images[1].id.val,
        }
        _post_response(self.django_client, request_url, data)
        _csrf_post_response(self.django_client, request_url, data)
Пример #11
0
 def testCreateAfterBlitzPort(self):
     ipojo = self.client.sf.getContainerService()
     i = ImageI()
     i.setName(rstring("name"))
     i.setAcquisitionDate(rtime(0))
     i = ipojo.createDataObject(i,None)
     o = i.getDetails().owner
     self.assertEquals( -1, o.sizeOfGroupExperimenterMap() )
Пример #12
0
    def createDiscussion(self, host, blitz_id, message, members, enable, expiration=None):
        expiration_date = None
        if expiration is not None:
            d1 = datetime.datetime.strptime(expiration + " 23:59:59", "%Y-%m-%d %H:%M:%S")
            expiration_date = rtime(long(time.mktime(d1.timetuple()) + 1e-6 * d1.microsecond) * 1000)
        ms = [long(m) for m in members]

        self.conn.createShare(host, int(blitz_id), [], message, ms, enable, expiration_date)
Пример #13
0
 def testThatPermissionsAreDefaultPrivate(self):
     i = omero.model.ImageI()
     i.name = rstring("name")
     i.acquisitionDate = rtime(0)
     i = self.client.sf.getUpdateService().saveAndReturnObject(i)
     self.assert_( not i.details.permissions.isGroupRead() )
     self.assert_( not i.details.permissions.isGroupWrite() )
     self.assert_( not i.details.permissions.isWorldRead() )
    def test1088(self):
        admin = self.root.sf.getAdminService()
        q = self.root.sf.getQueryService()
        cx = admin.getEventContext()

        p = omero.sys.Parameters()
        p.map = {}
        p.map["uid"] = rlong(cx.userId)
        p.map['start'] = rtime(1218529874000)
        p.map['end'] = rtime(1221121874000)

        sql1 = "select el from EventLog el left outer join " \
               "fetch el.event ev where el.entityType in " \
               "('ome.model.core.Pixels', 'ome.model.core.Image', " \
               "'ome.model.containers.Dataset', " \
               "'ome.model.containers.Project') " \
               "and ev.id in (select id from Event where " \
               "experimenter.id=:uid and time > :start and time < :end)"

        sql2 = "select el from EventLog el left outer join "\
               "fetch el.event ev where el.entityType in " \
               "('ome.model.core.Pixels', 'ome.model.core.Image', " \
               "'ome.model.containers.Dataset', " \
               "'ome.model.containers.Project') " \
               "and ev.experimenter.id=:uid " \
               "and ev.time > :start and ev.time < :end"

        # Much of the timing code here was already commented out, to fix
        # flake8 warnings the whole lot is commented out with just the two
        # queries repeated below.
        # import time
        # sql1_start = time.time()
        # l = q.findAllByQuery(sql1, p)
        # sql1_stop = time.time()
        # # print "\nSQL1: %s objects in %s seconds" % (str(len(l)),
        # # str(sql1_stop - sql1_start))
        q.findAllByQuery(sql1, p)

        # sql2_start = time.time()
        # l = q.findAllByQuery(sql2, p)
        # sql2_stop = time.time()
        # # print "SQL2: %s objects in %s seconds\n" % (str(len(l)),
        # # str(sql2_stop - sql2_start))
        q.findAllByQuery(sql2, p)
Пример #15
0
 def _createWithoutPixels (self, client, dataset):
     img = omero.model.ImageI()
     img.setName(omero.gateway.omero_type(self.name))
     img.setAcquisitionDate(rtime(0))
     if not dataset.imageLinksLoaded:
         print ".!."
         dataset._obj._imageLinksSeq = []
         dataset._obj._imageLinksLoaded = True;
     dataset.linkImage(img)
     dataset.save()
def image_no_acquisition_date(request, gatewaywrapper):
    """Creates an Image."""
    gatewaywrapper.loginAsAuthor()
    gw = gatewaywrapper.gateway
    update_service = gw.getUpdateService()
    image = ImageI()
    image.name = rstring('an image')
    image.acquisitionDate = rtime(0L)
    image_id, = update_service.saveAndReturnIds([image])
    return gw.getObject('Image', image_id)
Пример #17
0
 def createDiscussion(self, host, message, members, enable,
                      expiration=None):
     expiration_date = None
     if expiration is not None:
         d1 = datetime.datetime.strptime(
             expiration+" 23:59:59", "%Y-%m-%d %H:%M:%S")
         expiration_date = rtime(long(
             time.mktime(d1.timetuple()) + 1e-6 * d1.microsecond) * 1000)
     member_objects = list(self.conn.getObjects("Experimenter", members))
     return self.conn.createShare(
         host, [], message, member_objects, enable, expiration_date)
Пример #18
0
 def new_image(self, name=None, description=None, date=0):
     """
     Creates a new image object.
     If no name has been provided, a UUID string shall be used.
     :param name: The image name. If None, a UUID string will be used
     :param description: The image description
     :param date: The image acquisition date
     """
     img = self.new_object(ImageI, name=name, description=description)
     img.acquisitionDate = rtime(date)
     return img
Пример #19
0
    def testBasicUsage(self):
        img = omero.model.ImageI()
        img.name = rstring("delete test")
        img.acquisitionDate = rtime(0)
        tag = omero.model.TagAnnotationI()
        img.linkAnnotation(tag)

        img = self.client.sf.getUpdateService().saveAndReturnObject(img)

        command = omero.cmd.Delete("/Image", img.id.val, None)
        handle = self.client.sf.submit(command)
        self.waitOnCmd(self.client, handle)
Пример #20
0
    def testBasicImport(self):
        """
        basic server-side import steps

        Once a list of file paths have been passed to the server,
        an omero.model.Fileset object will be created which captures
        the state of the import.
        """

        # This should be passed in by the client
        clientInfo = omero.model.FilesetVersionInfoI()

        # This will be created server-side
        serverInfo = omero.model.FilesetVersionInfoI()
        serverInfo.bioformatsReader = _("ExampleReader")
        serverInfo.bioformatsVersion = _("v4.4.5 git: abc123")
        serverInfo.omeroVersion = _("v.4.4.4 git: def456")
        serverInfo.osName = _("Linux")
        serverInfo.osArchitecture = _("amd64")
        serverInfo.osVersion = _("2.6.38-8-generic")
        # Something returned by Locale.getDefault().toString()
        serverInfo.locale = "en_US"

        # Now that the basics are setup, we
        # need to link to all of the original files.
        fs = omero.model.FilesetI()
        fs.addFilesetEntry(self.mkentry("main_file.txt")) # First!
        fs.addFilesetEntry(self.mkentry("uf1.data"))
        fs.addFilesetEntry(self.mkentry("uf2.data"))

        # Now that the files are all added, we
        # add the "activities" that will be
        # performed on them.

        # Uploading is almost always the first
        # step, and must be completed by the clients
        # before any other activity.
        job1 = omero.model.UploadJobI()
        job1.scheduledFor = rtime(time.time() * 1000) # Now
        # Set this "started" since we're expecting
        # upload to be in process.

        # Import is a server-side activity which
        # causes the files to be parsed and their
        # metadata to be stored.
        job2 = omero.model.MetadataImportJobI()

        # Other possible activities include "pyramids"
        # and "re-import"

        fs.linkJob(job1)
        fs.linkJob(job2)
Пример #21
0
    def test1184(self):
        uuid = self.uuid()
        client = self.new_client(perms="rw----")

        share = client.sf.getShareService()
        query = client.sf.getQueryService()
        update = client.sf.getUpdateService()
        admin = client.sf.getAdminService()
        cont = client.sf.getContainerService()

        ds = DatasetI()
        ds.setName(rstring('test1184-ds-%s' % (uuid)))

        for i in range(1,2001):
            img = ImageI()
            img.setName(rstring('img1184-%s' % (uuid)))
            img.setAcquisitionDate(rtime(time.time()))
            # Saving in one go
            #dil = DatasetImageLinkI()
            #dil.setParent(ds)
            #dil.setChild(img)
            #update.saveObject(dil)
            ds.linkImage(img)
        ds = update.saveAndReturnObject(ds)

        c = cont.getCollectionCount(ds.__class__.__name__, ("imageLinks"), [ds.id.val], None)
        assert c[ds.id.val] == 2000

        page = 1
        p = omero.sys.Parameters()
        p.map = {}
        p.map["eid"] = rlong(admin.getEventContext().userId)
        p.map["oid"] = rlong(ds.id.val)
        if page is not None:
            f = omero.sys.Filter()
            f.limit = rint(24)
            f.offset = rint((int(page)-1)*24)
            p.theFilter = f

        sql = "select im from Image im join fetch im.details.owner join fetch im.details.group " \
              "left outer join fetch im.datasetLinks dil left outer join fetch dil.parent d " \
              "where d.id = :oid and im.details.owner.id=:eid order by im.id asc"

        start = time.time()
        res = query.findAllByQuery(sql,p)
        assert 24 ==  len(res)
        end = time.time()
        elapsed = end - start
        assert elapsed < 3.0,\
            "Expected the test to complete in < 3 seconds, took: %f" % elapsed
Пример #22
0
    def test13018(self):
        """
        Test that image in share is unavailable when share
        is inactive or expired
        """
        owner = self.new_client()
        member, mobj = self.new_client_and_user()

        createTestImage(owner.sf)
        image = owner.sf.getQueryService().findAll("Image", None)[0]

        o_share = owner.sf.getShareService()
        sid = o_share.createShare("", None, [image], [mobj], [], True)

        m_share = member.sf.getShareService()
        m_share.activate(sid)

        o_share.setActive(sid, False)
        with pytest.raises(omero.ValidationException):
            m_share.activate(sid)

        with pytest.raises(omero.ValidationException):
            obj = omero.model.ShareI(sid, False)
            member.sf.setSecurityContext(obj)

        # test inactive share, if member has no access to the image
        s = o_share.getShare(sid)
        with pytest.raises(Glacier2.PermissionDeniedException):
            self.new_client(session=s.uuid)

        # activate again
        o_share.setActive(sid, True)

        # test that the image is now loadable again.
        t_conn = self.new_client(session=s.uuid)
        t_conn.sf.getQueryService().find("Image", image.id.val)

        # test expired share, if member has no access to the image
        expiration = long(time.time() * 1000) + 500
        o_share.setExpiration(sid, rtime(expiration))
        self.assert_expiration(expiration, o_share.getShare(sid))
        time.sleep(0.5)

        # Forced closing
        o_session = owner.sf.getSessionService()
        o_session.closeSession(o_share.getShare(sid))

        with pytest.raises(Glacier2.PermissionDeniedException):
            self.new_client(session=s.uuid)
Пример #23
0
def create_image(image_index):
    image = ImageI()
    image.name = rstring("%s_%d" % (uuid(), image_index))
    image.acquisitionDate = rtime(0)
    pixels = PixelsI()
    pixels.sha1 = rstring("")
    pixels.sizeX = rint(1)
    pixels.sizeY = rint(1)
    pixels.sizeZ = rint(1)
    pixels.sizeC = rint(1)
    pixels.sizeT = rint(1)
    pixels.dimensionOrder = DimensionOrderI(1L, False)  # XYZCT
    pixels.pixelsType = PixelsTypeI(1L, False)  # bit
    image.addPixels(pixels)
    return image
Пример #24
0
    def test2327(self):

        ### create two users in two groups
        client_share1, user1 = self.new_client_and_user()
        client_share2, user2 = self.new_client_and_user()

        ## login as user1
        share1 = client_share1.sf.getShareService()
        update1 = client_share1.sf.getUpdateService()

        # create image
        img = ImageI()
        img.setName(rstring('test2327'))
        img.setAcquisitionDate(rtime(0))
        img = update1.saveAndReturnObject(img)
        img.unload()

        # create share
        description = "my description"
        timeout = None
        objects = [img]
        experimenters = [user2]
        guests = []
        enabled = True
        sid = share1.createShare(description, timeout, objects, experimenters, guests, enabled)
        self.assert_(len(share1.getContents(sid)) == 1)
        # add comment by the owner
        share1.addComment(sid, 'test comment by the owner %s' % user1.id.val)

        ## login as user2
        share2 = client_share2.sf.getShareService()
        query2 = client_share2.sf.getQueryService()

        l = share2.getMemberShares(False)
        self.assertEquals(1, len(l))

        # add comment by the member
        share2.addComment(sid, 'test comment by the member %s' % (user2.id.val))

        # Don't have to activate share2

        #get comments
        # by user1
        c1 = len(share1.getComments(sid))
        self.assertEquals(2, c1)
        # by user2
        c2 = len(share2.getComments(sid))
        self.assertEquals(2, c2)
Пример #25
0
    def test1154(self):
        uuid = self.root.sf.getAdminService().getEventContext().sessionUuid

        
        ### create two users in one group
        client_share1, user1 = self.new_client_and_user()
        client_share2, user2 = self.new_client_and_user()

        ## login as user1
        share1 = client_share1.sf.getShareService()
        update1 = client_share1.sf.getUpdateService()
        
        # create image
        img = ImageI()
        img.setName(rstring('test1154-img-%s' % (uuid)))
        img.setAcquisitionDate(rtime(0))
        img = update1.saveAndReturnObject(img)
        img.unload()
        
        # create share
        description = "my description"
        timeout = None
        objects = [img]
        experimenters = [user2]
        guests = []
        enabled = True
        sid = share1.createShare(description, timeout, objects,experimenters, guests, enabled)
        
        self.assertEquals(1,len(share1.getContents(sid)))
        
        ## login as user2
        share2 = client_share2.sf.getShareService()
        query2 = client_share2.sf.getQueryService()
        
        content = share2.getContents(sid)
        self.assertEquals(1,len(share2.getContents(sid)))
        
        # get shared image when share is activated
        share2.activate(sid)

        p = omero.sys.Parameters()
        p.map = {}
        p.map["ids"] = rlist([rlong(img.id.val)])
        sql = "select im from Image im where im.id in (:ids) order by im.name"
        res = query2.findAllByQuery(sql, p)
        self.assertEquals(1,len(res))
        for e in res:
            self.assert_(e.id.val == img.id.val)
def plate_wells_with_acq_date(itest, well_grid_factory, update_service):
    """
    Creates a plate with a single well containing an image with both an
    acquisition date set as well as a creation event with a date. Returns the
    plate and the acquisition date in a map.
    """
    acq_date = (time.time() - 60 * 60 * 24) * 1000
    plate = PlateI()
    plate.name = rstring(itest.uuid())
    # Simple grid: one well with one image
    [well] = well_grid_factory({(0, 0): 1})
    well.copyWellSamples()[0].image.acquisitionDate = rtime(int(acq_date))
    plate.addWell(well)
    plate = update_service.saveAndReturnObject(plate)
    return {'plate': plate,
            'acq_date': int(acq_date / 1000)}
Пример #27
0
    def testCheckIfDeleted2(self):
        uuid = self.client.sf.getAdminService().getEventContext().sessionUuid
        query = self.client.sf.getQueryService()
        update = self.client.sf.getUpdateService()

        # dataset with many images
        images = list()
        for i in range(0, 50):
            img = omero.model.ImageI()
            img.name = rstring("test-delete-image-%i" % i)
            img.acquisitionDate = rtime(0)
            tag = omero.model.TagAnnotationI()
            img.linkAnnotation(tag)
            images.append(update.saveAndReturnObject(img))

        # create dataset
        dataset = omero.model.DatasetI()
        dataset.name = rstring('DS-test-%s' % (uuid))
        dataset = update.saveAndReturnObject(dataset)
        # put image in dataset
        for img in images:
            dlink = omero.model.DatasetImageLinkI()
            dlink.parent = omero.model.DatasetI(dataset.id.val, False)
            dlink.child = omero.model.ImageI(img.id.val, False)
            update.saveAndReturnObject(dlink)

        commands = list()
        for img in images:
            commands.append(omero.cmd.Delete("/Image", img.id.val, None))
        doall = omero.cmd.DoAll()
        doall.requests = commands

        handle = self.client.sf.submit(doall)
        callback = self.waitOnCmd(self.client, handle, ms=1000, loops=50)

        callback.close(True)

        p = omero.sys.Parameters()
        p.map = {}
        p.map["oid"] = dataset.id

        sql = "select im from Image im "\
              "left outer join fetch im.datasetLinks dil "\
              "left outer join fetch dil.parent d " \
              "where d.id = :oid " \
              "order by im.id asc"
        assert 0 == len(query.findAllByQuery(sql, p))
Пример #28
0
    def test1157(self):
        uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
        share = self.root.sf.getShareService()
        
        ### create two users in one group
        client_share1, user1 = self.new_client_and_user()
        client_share2, user2 = self.new_client_and_user()
        
        ## login as user1 
        share1 = client_share1.sf.getShareService()
        update1 = client_share1.sf.getUpdateService()
        
        # create image
        img = ImageI()
        img.setName(rstring('test1154-img-%s' % (uuid)))
        img.setAcquisitionDate(rtime(0))
        img = update1.saveAndReturnObject(img)
        img.unload()
        
        # create share
        description = "my description"
        timeout = None
        objects = [img]
        experimenters = [user2]
        guests = []
        enabled = True
        sid = share1.createShare(description, timeout, objects,experimenters, guests, enabled)
        self.assert_(len(share1.getContents(sid)) == 1)
        # add comment by the owner
        share.addComment(sid, 'test comment by the owner %s' % (uuid))
        
        ## login as user2
        share2 = client_share2.sf.getShareService()
        query2 = client_share2.sf.getQueryService()
        
        # add comment by the member
        share2.addComment(sid, 'test comment by the member %s' % (uuid))

        # Don't have to activate share2

        #get comments
        # by user1
        c1 = len(share.getComments(sid))
        self.assertEquals(2,c1)
        # by user2
        c2 = len(share2.getComments(sid))
        self.assertEquals(2,c2)
Пример #29
0
    def test1201(self):
        admin = self.client.sf.getAdminService()

        # create two users in one group
        group = self.new_group()
        client_user1, user1 = self.new_client_and_user(group)
        client_user2, user2 = self.new_client_and_user(group)
        assert admin.getMemberOfGroupIds(user1) == admin\
            .getMemberOfGroupIds(user2)

        # create share
        share1 = client_user1.sf.getShareService()
        description = "my description"
        timeout = None
        objects = []
        experimenters = [user2]
        guests = ["*****@*****.**"]
        enabled = True
        sid = share1.createShare(description, timeout, objects,
                                 experimenters, guests, enabled)

        # check that owner and member can access share
        self.assert_access(client_user1, sid)
        self.assert_access(client_user2, sid)

        share2 = client_user2.sf.getShareService()
        new_description = "new description"
        share1.setDescription(sid, new_description)

        try:
            assert share2.getShare(sid).message.val == new_description
        except omero.ValidationException:
            pass  # This user can't see the share

        assert share1.getShare(sid).message.val == new_description

        expiration = long(time.time() * 1000) + 86400
        share1.setExpiration(sid, rtime(expiration))
        self.assert_expiration(expiration, share1.getShare(sid))

        share1.setActive(sid, False)
        assert share1.getShare(sid).active.val is False

        owned = share1.getOwnShares(False)
        assert 1 == len(owned)
        return client_user1, sid, expiration
Пример #30
0
    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()

        img = omero.model.ImageI()
        img.name = rstring("to delete - test")
        img.acquisitionDate = rtime(0)
        tag = omero.model.TagAnnotationI()
        img.linkAnnotation(tag)

        iid = update.saveAndReturnObject(img).id.val

        cmd = omero.cmd.Delete("/Image", iid, None)
        handle = self.client.sf.submit(cmd)
        callback = self.waitOnCmd(self.client, handle)
        cbString = str(handle)

        callback.close(True)  # Don't close handle

        assert not 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)
        cl1.createSession(userName, userName)

        with pytest.raises(Ice.ObjectNotExistException):
            omero.cmd.HandlePrx.checkedCast(
                cl1.ic.stringToProxy(cbString))

        # join session and double check
        cl2 = omero.client(host=host, port=port)
        cl2.joinSession(uuid)

        with pytest.raises(Ice.ObjectNotExistException):
            omero.cmd.HandlePrx.checkedCast(
                cl2.ic.stringToProxy(cbString))
Пример #31
0
    def test1071(self):
        uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
        pojos = self.root.sf.getContainerService()
        query = self.root.sf.getQueryService()
        update = self.root.sf.getUpdateService()

        #projects
        pr1 = ProjectI()
        pr1.setName(rstring('test1071-pr1-%s' % (uuid)))
        pr1 = update.saveAndReturnObject(pr1)
        pr1.unload()

        pr2 = ProjectI()
        pr2.setName(rstring('test1071-pr2-%s' % (uuid)))
        pr2 = update.saveAndReturnObject(pr2)
        pr2.unload()

        #datasets
        ds1 = DatasetI()
        ds1.setName(rstring('test1071-ds1-%s' % (uuid)))
        ds1 = update.saveAndReturnObject(ds1)
        ds1.unload()

        ds2 = DatasetI()
        ds2.setName(rstring('test1071-ds2-%s' % (uuid)))
        ds2 = update.saveAndReturnObject(ds2)
        ds2.unload()

        ds3 = DatasetI()
        ds3.setName(rstring('test1071-ds3-%s' % (uuid)))
        ds3 = update.saveAndReturnObject(ds3)
        ds3.unload()

        #images
        im2 = ImageI()
        im2.setName(rstring('test1071-im2-%s' % (uuid)))
        im2.acquisitionDate = rtime(0)
        im2 = update.saveAndReturnObject(im2)
        im2.unload()

        #links
        #
        # im2 -> ds3
        #    +-> ds2 --> pr2
        #    |       \
        #    \-> ds1 --> pr1
        #
        pdl1 = ProjectDatasetLinkI()
        pdl1.setParent(pr1)
        pdl1.setChild(ds1)
        update.saveObject(pdl1)

        pdl2 = ProjectDatasetLinkI()
        pdl2.setParent(pr1)
        pdl2.setChild(ds2)
        update.saveObject(pdl2)

        pdl3 = ProjectDatasetLinkI()
        pdl3.setParent(pr2)
        pdl3.setChild(ds2)
        update.saveObject(pdl3)

        dil4 = DatasetImageLinkI()
        dil4.setParent(ds1)
        dil4.setChild(im2)
        update.saveObject(dil4)

        dil5 = DatasetImageLinkI()
        dil5.setParent(ds2)
        dil5.setChild(im2)
        update.saveObject(dil5)

        dil6 = DatasetImageLinkI()
        dil6.setParent(ds3)
        dil6.setChild(im2)
        update.saveObject(dil6)

        #test:
        hier = pojos.findContainerHierarchies("Project", [long(im2.id.val)],
                                              None)

        assert 3 == len(hier), "len of hier != 3: %s" % [type(x) for x in hier]
        for c in hier:
            if c.id.val == pr1.id.val and isinstance(c, ProjectI):
                assert c.sizeOfDatasetLinks() == 2, "length 2 != " + str(
                    c.sizeOfDatasetLinks())
                for pdl in c.copyDatasetLinks():
                    assert pdl.child.sizeOfImageLinks() == 1
                    for dil in pdl.child.copyImageLinks():
                        assert dil.child.id.val == im2.id.val
            elif c.id.val == pr2.id.val and isinstance(c, ProjectI):
                assert c.sizeOfDatasetLinks() == 1
            elif c.id.val == ds3.id.val and isinstance(c, DatasetI):
                assert c.sizeOfImageLinks() == 1
Пример #32
0
                                 guests, enabled)

        #re - login as user1
        share2 = client_share2.sf.getShareService()

        new_description = "new description"
        share1.setDescription(sid, new_description)
        try:
            assert share2.getShare(sid).message.val == new_description
        except omero.ValidationException, ve:
            pass  # This user can't see the share

        assert share1.getShare(sid).message.val == new_description

        expiration = long(time.time() * 1000) + 86400
        share1.setExpiration(sid, rtime(expiration))
        self.assertExpiration(expiration, share1.getShare(sid))

        share1.setActive(sid, False)
        assert share1.getShare(sid).active.val == False

        owned = share1.getOwnShares(False)
        assert 1 == len(owned)
        return (client_share1, sid, expiration)

    def test1201b(self):
        share = self.client.sf.getShareService()
        # create share
        description = "my description"
        timeout = None
        objects = []
Пример #33
0
def add_plate_metadata(images, conn):
    logging.info("start add_plate_metadata")

    # sort images with image_name_sort_fn
    # makes sure well, wellsample and channels come sorted
    # after each other when looping the list
    sorted(images, key=image_name_sort_fn)

    # get meta from first image as a plate representative
    first_image_meta = parse_path_and_file(images[0])
    logging.debug(first_image_meta)
    plate_ID = getPlateID(conn, metadata['plate'])
    if plate_ID is not None:
        raise Exception(
            'Plate ' + str(metadata['plate']) +
            ' that is about to be imported is in database already with ID:' +
            str(plate_ID))

    # Create Plate
    plate = omero.model.PlateI()
    plate.setName(rstring(first_image_meta['plate']))
    plate = conn.getUpdateService().saveAndReturnObject(plate)

    # Create PlateAquisition?
    aq_start_time = datetime.datetime(
        year=first_image_meta['date_year'],
        month=first_image_meta['date_month'],
        day=first_image_meta['date_day_of_month'])
    plateaq = omero.model.PlateAcquisitionI()
    plateaq.setName(
        rstring(first_image_meta['plate'] + '_' + str(aq_start_time)))
    plateaq.setPlate(plate)
    start_time_epoch = time.mktime(aq_start_time.timetuple())
    plateaq.setStartTime(rtime(start_time_epoch))
    plateaq.setEndTime(rtime(start_time_epoch))
    plateaq = conn.getUpdateService().saveAndReturnObject(plateaq)

    # Loop all Images
    well = None
    last_well_name = None
    wellsample = None
    for image in images:
        img_meta = parse_path_and_file(image)

        # Get Image reference fom database
        # we have to get it by query-service or otherwise properties are
        # not filled in and Error will be thrown later when image methods are used
        qs = conn.getQueryService()
        params = omero.sys.Parameters()
        params.map = {'imagename': rstring(os.path.basename(image))}
        logging.debug(params.map)
        # TODO change from findAllByQuery to findAllByQuery and only one return
        images = qs.findAllByQuery("from Image as i where i.name=:imagename",
                                   params)
        image = images[0]

        well_name = img_meta['well']
        # Create Well, only if the well-name is different from the last image well-name
        if well is None or last_well_name != well_name:
            well = omero.model.WellI()
            well.setExternalDescription(rstring(well_name))
            row_col = well_label2row_col(well_name)
            logging.info(row_col)
            well.setColumn(rint(row_col['col']))
            well.setRow(rint(row_col['row']))
            well.setPlate(plate)
            well = conn.getUpdateService().saveAndReturnObject(well)
            last_well_name = well_name

        # Create Wellsamples (one for each picture, each channel is stored as a separate wellsampla=
        wellsample_name = img_meta['wellsample']
        wellsample = omero.model.WellSampleI()
        wellsample.setImage(image)
        # wellsample.well = well
        wellsample.setPlateAcquisition(plateaq)
        logging.debug(wellsample_name)
        #wellsample.posX = omero.model.LengthI(rdouble(img_meta['wellsample']), omero.model.enums.UnitsLength.PIXEL)
        well.addWellSample(wellsample)
        wellsample = conn.getUpdateService().saveAndReturnObject(wellsample)

        # TODO create channel?

        # Add key value annotation to image
        map_ann = omero.gateway.MapAnnotationWrapper(conn)
        # Use 'client' namespace to allow editing in Insight & web
        namespace = omero.constants.metadata.NSCLIENTMAPANNOTATION
        map_ann.setNs(namespace)

        img_meta_as_map_ann = dictToMapAnnotation(img_meta)

        logging.debug(img_meta_as_map_ann)

        map_ann.setValue(img_meta_as_map_ann)
        map_ann.save()

        # NB: only link a client map annotation to a single object

        image_id = image.getId()
        image_v2 = conn.getObject("Image", image_id)
        logging.debug(image_v2)

        image_v2.linkAnnotation(map_ann)
Пример #34
0
table = s.sharedResources().newTable(1, "iroi.h5")
cols = []
cols.append(omero.grid.RoiColumn('roi_id', 'Roi ID', None))
cols.append(omero.grid.DoubleColumn('area', 'Area of ROI', None))
cols.append(omero.grid.LongColumn('intensity', 'Intensity of ROI', None))
table.initialize(cols)
file = table.getOriginalFile()

# Setup data
plate = omero.model.PlateI()
plate.name = rstring("iroi.py")
well = omero.model.WellI()
sample = omero.model.WellSampleI()
image = omero.model.ImageI()
image.name = rstring("iroi.py")
image.acquisitionDate = rtime(0)
image.addWellSample(sample)
well.addWellSample(sample)
plate.addWell(well)

measurement = omero.model.FileAnnotationI()
measurement.ns = rstring(omero.constants.namespaces.NSMEASUREMENT)
measurement.file = file
plate.linkAnnotation(measurement)
plate = s.getUpdateService().saveAndReturnObject(plate)
image_id = plate.copyWells()[0].copyWellSamples()[0].image.id.val

roi_svc = s.getRoiService()
roi_meas = roi_svc.getRoiMeasurements(image_id, None)

if len(roi_meas) > 0:
Пример #35
0
def create_image(image_id, with_pixels=False):
    image_format = FormatI(1)
    image_format.value = rstring('PNG')

    image = ImageI()
    image.id = rlong(image_id)
    image.acquisitionDate = rtime(1)
    image.archived = rbool(False)
    image.description = rstring('image_description_%d' % image_id)
    image.name = rstring('image_name_%d' % image_id)
    image.partial = rbool(False)
    image.series = rint(0)
    image.format = image_format
    if not with_pixels:
        return image
    dimension_order = DimensionOrderI(1)
    dimension_order.value = rstring('XYZCT')
    pixels_type = PixelsTypeI(1)
    pixels_type.value = 'bit'

    pixels = PixelsI(1)
    pixels.methodology = rstring('methodology')
    pixels.physicalSizeX = LengthI(1.0, UnitsLength.MICROMETER)
    pixels.physicalSizeY = LengthI(2.0, UnitsLength.MICROMETER)
    pixels.physicalSizeZ = LengthI(3.0, UnitsLength.MICROMETER)
    pixels.sha1 = rstring('61ee8b5601a84d5154387578466c8998848ba089')
    pixels.significantBits = rint(16)
    pixels.sizeX = rint(1)
    pixels.sizeY = rint(2)
    pixels.sizeZ = rint(3)
    pixels.sizeC = rint(4)
    pixels.sizeT = rint(5)
    pixels.timeIncrement = TimeI(1.0, UnitsTime.MILLISECOND)
    pixels.waveIncrement = rdouble(2.0)
    pixels.waveStart = rint(1)
    pixels.dimensionOrder = dimension_order
    pixels.pixelsType = pixels_type
    image.addPixels(pixels)

    contrast_method = ContrastMethodI(8)
    contrast_method.value = rstring('Fluorescence')
    illumination = IlluminationI(1)
    illumination.value = rstring('Transmitted')
    acquisition_mode = AcquisitionModeI(1)
    acquisition_mode.value = rstring('WideField')
    photometric_interpretation = PhotometricInterpretationI(1)
    photometric_interpretation.value = rstring('RGB')

    channel_1 = ChannelI(1)
    channel_1.alpha = rint(255)
    channel_1.blue = rint(255)
    channel_1.green = rint(255)
    channel_1.red = rint(255)
    channel_1.lookupTable = rstring('rainbow')
    logical_channel_1 = LogicalChannelI(1)
    logical_channel_1.emissionWave = LengthI(509.0, UnitsLength.NANOMETER)
    logical_channel_1.excitationWave = LengthI(488.0, UnitsLength.NANOMETER)
    logical_channel_1.fluor = rstring('GFP')
    logical_channel_1.name = rstring('GFP/488')
    logical_channel_1.ndFilter = rdouble(1.0)
    logical_channel_1.pinHoleSize = LengthI(1.0, UnitsLength.NANOMETER)
    logical_channel_1.pockelCellSetting = rint(0)
    logical_channel_1.samplesPerPixel = rint(2)
    logical_channel_1.contrastMethod = contrast_method
    logical_channel_1.illumination = illumination
    logical_channel_1.mode = acquisition_mode
    logical_channel_1.photometricInterpretation = photometric_interpretation
    channel_1.logicalChannel = logical_channel_1

    channel_2 = ChannelI(2)
    channel_2.alpha = rint(255)
    channel_2.blue = rint(255)
    channel_2.green = rint(0)
    channel_2.red = rint(255)
    channel_2.lookupTable = rstring('rainbow')
    logical_channel_2 = LogicalChannelI(2)
    logical_channel_2.emissionWave = LengthI(470.0, UnitsLength.NANOMETER)
    logical_channel_2.excitationWave = LengthI(405.0, UnitsLength.NANOMETER)
    logical_channel_2.fluor = rstring('DAPI')
    logical_channel_2.name = rstring('DAPI/405')
    logical_channel_2.ndFilter = rdouble(1.0)
    logical_channel_2.pinHoleSize = LengthI(2.0, UnitsLength.NANOMETER)
    logical_channel_2.pockelCellSetting = rint(0)
    logical_channel_2.samplesPerPixel = rint(2)
    logical_channel_2.contrastMethod = contrast_method
    logical_channel_2.illumination = illumination
    logical_channel_2.mode = acquisition_mode
    logical_channel_2.photometricInterpretation = photometric_interpretation
    channel_2.logicalChannel = logical_channel_2

    pixels.addChannel(channel_1)
    pixels.addChannel(channel_2)
    return image
Пример #36
0
    def testFindAndCountAnnotationsForSharedData(self):
        uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
        query = self.root.sf.getQueryService()
        update = self.root.sf.getUpdateService()
        admin = self.root.sf.getAdminService()
        ipojo = self.root.sf.getContainerService()

        ### create new users
        #group1
        new_gr1 = ExperimenterGroupI()
        new_gr1.name = rstring("group1_%s" % uuid)
        gid = admin.createGroup(new_gr1)

        #new user1
        new_exp = ExperimenterI()
        new_exp.omeName = rstring("user1_%s" % uuid)
        new_exp.firstName = rstring("New")
        new_exp.lastName = rstring("Test")

        defaultGroup = admin.getGroup(gid)
        listOfGroups = list()
        listOfGroups.append(admin.lookupGroup("user"))

        eid = admin.createExperimenterWithPassword(new_exp, rstring("ome"),
                                                   defaultGroup, listOfGroups)

        #new user2
        new_exp2 = ExperimenterI()
        new_exp2.omeName = rstring("user2_%s" % uuid)
        new_exp2.firstName = rstring("New2")
        new_exp2.lastName = rstring("Test2")

        defaultGroup = admin.getGroup(gid)
        listOfGroups = list()
        listOfGroups.append(admin.lookupGroup("user"))

        eid2 = admin.createExperimenterWithPassword(new_exp2, rstring("ome"),
                                                    defaultGroup, listOfGroups)

        ## get users
        user1 = admin.getExperimenter(eid)
        user2 = admin.getExperimenter(eid2)

        ## login as user1
        cl1 = self.new_client(user=user1, password="******")
        update1 = cl1.sf.getUpdateService()
        ipojo1 = cl1.sf.getContainerService()

        # create image
        img = ImageI()
        img.setName(rstring('test1154-img-%s' % (uuid)))
        img.setAcquisitionDate(rtime(0))

        # default permission 'rw----':
        img = update1.saveAndReturnObject(img)
        img.unload()

        ann1 = CommentAnnotationI()
        ann1.textValue = rstring("user comment - %s" % uuid)
        l_ann1 = ImageAnnotationLinkI()
        l_ann1.setParent(img)
        l_ann1.setChild(ann1)
        update1.saveObject(l_ann1)

        #user retrives the annotations for image
        coll_count = ipojo1.getCollectionCount(
            "Image", "ome.model.containers.Image_annotationLinks",
            [img.id.val], None)
        self.assertEquals(1, coll_count.get(img.id.val, []))
        #self.assertEquals(1, len(ipojo1.findAnnotations("Image", [img.id.val], None, None).get(img.id.val, [])))

        ## login as user2
        cl2 = self.new_client(user=user2, password="******")
        update2 = cl1.sf.getUpdateService()

        ann = CommentAnnotationI()
        ann.textValue = rstring("user2 comment - %s" % uuid)
        l_ann = ImageAnnotationLinkI()
        l_ann.setParent(img)
        l_ann.setChild(ann)
        update2.saveObject(l_ann)

        #do they see the same vals?
        #print ipojo1.getCollectionCount("Image", "ome.model.containers.Image_annotationLinks", [img.id.val], None)
        #print ipojo.getCollectionCount("Image", "ome.model.containers.Image_annotationLinks", [img.id.val], None)
        #print len(ipojo1.findAnnotations("Image", [img.id.val], None, None).get(img.id.val, []))
        #print len(ipojo.findAnnotations("Image", [img.id.val], None, None).get(img.id.val, []))
        coll_count = ipojo1.getCollectionCount(
            "Image", "ome.model.containers.Image_annotationLinks",
            [img.id.val], None)
        self.assertEquals(2, coll_count.get(img.id.val, []))
        #anns = ipojo1.findAnnotations("Image", [img.id.val], None, None).get(img.id.val, [])
        #self.assertEquals(2, len(anns))

        #self.assert_(anns[0].details.permissions == 'rw----')
        #self.assert_(anns[1].details.permissions == 'rw----')

        cl1.sf.closeOnDestroy()
        cl2.sf.closeOnDestroy()
Пример #37
0
    def test1172(self):
        uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
        share = self.root.sf.getShareService()
        query = self.root.sf.getQueryService()

        # create user
        client_share1, user1 = self.new_client_and_user()

        # create dataset with image
        ds = self.make_dataset(name="dataset-%s" % uuid, client=self.root)
        img = self.new_image(name='test-img in dataset-%s' % uuid)
        self.link(ds, img, client=self.root)

        items = list()
        p = omero.sys.Parameters()
        p.map = {"oid": ds.id}
        sql = (
            "select ds from Dataset ds "
            "join fetch ds.details.owner "
            "join fetch ds.details.group "
            "left outer join fetch ds.imageLinks dil "
            "left outer join fetch dil.child i "
            "where ds.id=:oid")
        items.extend(query.findAllByQuery(sql, p))
        assert 1 == len(items)

        # members
        p.map["eid"] = rlong(user1.id.val)
        sql = ("select e from Experimenter e "
               "where e.id =:eid order by e.omeName")
        ms = query.findAllByQuery(sql, p)
        sid = share.createShare(("test-share-%s" % uuid),
                                rtime(long(time.time() * 1000 + 86400)),
                                items, ms, [], True)

        # USER RETRIEVAL
        # login as user1
        share1 = client_share1.sf.getShareService()
        query1 = client_share1.sf.getQueryService()

        content = share1.getContents(sid)
        # Content now contains just the dataset with nothing loaded
        assert 1 == len(content)

        # get shared dataset and image when share is activated
        share1.activate(sid)

        # retrieve dataset
        p = omero.sys.Parameters()
        p.map = {"ids": rlist([ds.id])}
        sql = (
            "select ds from Dataset ds "
            "join fetch ds.details.owner "
            "join fetch ds.details.group "
            "left outer join fetch ds.imageLinks dil "
            "left outer join fetch dil.child i "
            "where ds.id in (:ids) order by ds.name")
        try:
            res1 = query1.findAllByQuery(sql, p)
            assert False, "This should throw an exception"
        except:
            pass

        # Now we add all the other elements to the share to prevent
        # the security violation
        #
        # Not working imgs = cntar.getImages("Dataset",[ds.id.val], None)
        img = query.findByQuery(
            "select i from Image i join fetch i.datasetLinks dil "
            "join dil.parent d where d.id = %s " % ds.id.val, None)
        assert img
        share.addObject(sid, img)
        share.addObjects(sid, img.copyDatasetLinks())
        assert 3 == len(share.getContents(sid))

        # And try again to load them
        share1.activate(sid)
        res1 = query1.findAllByQuery(sql, p)
        assert len(res1) == 1
        for e in res1:
            assert e.id.val == ds.id.val

        # retrieve only image
        p = omero.sys.Parameters()
        p.map = {"oid": rlong(img.id)}
        sql = "select im from Image im " \
              "where im.id=:oid order by im.name"
        res2 = query1.findByQuery(sql, p)
        assert res2.id.val == img.id.val
Пример #38
0
def main(argv=sys.argv):

    # Configure argument parsing
    parser = ArgumentParser(description='''Report number of images imported in
                                           a date range''')
    parser.add_argument('-q',
                        '--quiet',
                        action='store_const',
                        const=True,
                        default=False,
                        help='Do not print output')
    parser.add_argument('-f',
                        '--file',
                        metavar='file',
                        help='Destination CSV file')
    parser.add_argument('-s',
                        '--start',
                        metavar='start',
                        help='Start timestamp')
    parser.add_argument('-e', '--end', metavar='end', help='End timestamp')
    parser.add_argument('-a',
                        '--all',
                        action='store_const',
                        const=True,
                        default=False,
                        help='Complete report. Ignores start/end')
    parser.add_argument('-p',
                        '--period',
                        choices=['year', 'month', 'day'],
                        default='month',
                        help='Period for use in conjunction with -a')
    args = parser.parse_args()

    # Create an OMERO Connection with our basic connection manager
    conn_manager = OMEROConnectionManager()

    if args.all:

        q = '''
            SELECT grp.name,
                   experimenter.omeName,
                   TO_CHAR(event.time, '{period}') AS cal_period,
                   count(event.time)
            FROM Image image
            JOIN image.details.creationEvent event
            JOIN image.details.owner experimenter
            JOIN image.details.group grp
            GROUP BY grp.name,
                     experimenter.omeName,
                     TO_CHAR(event.time, '{period}')
            ORDER BY grp.name,
                     experimenter.omeName,
                     TO_CHAR(event.time, '{period}')
            DESC
            '''

        q = q.format(period=periods[args.period])

        # Run the query
        rows = conn_manager.hql_query(q)
        header = ['Group', 'Username', 'Period', 'Count']

    else:

        params = ParametersI()
        params.map = {}

        start_date = None
        end_date = None

        try:
            if args.start:
                start_date = dateutil.parser.parse(args.start)
            if args.end:
                end_date = dateutil.parser.parse(args.end)
        except ValueError:
            sys.stderr.write('Start and/or end dates have to be parseable!')
            sys.exit(1)

        q = '''
            SELECT grp.name,
                   experimenter.omeName,
                   count(event.time)
            FROM Image image
            JOIN image.details.creationEvent event
            JOIN image.details.owner experimenter
            JOIN image.details.group grp
            '''

        if start_date or end_date:
            q += ' WHERE '

        if start_date:
            q += ' event.time >= :dstart '
            params.map['dstart'] = rtime(unix_time_millis(start_date))

        if start_date and end_date:
            q += ' AND '

        if end_date:
            q += ' event.time <= :dend'
            params.map['dend'] = rtime(unix_time_millis(end_date))

        q += '''
            GROUP BY grp.name,
                     experimenter.omeName
            '''

        # Run the query
        rows = conn_manager.hql_query(q, params)
        header = ['Group', 'Username', 'Count']

    # Print results (if not quieted)
    if args.quiet is False:
        print(', '.join(header))
        for row in rows:
            print(', '.join([str(item) for item in row]))

    # Output CSV file (if specified)
    if args.file is not None:
        write_csv(rows, args.file, header)
Пример #39
0
    def test1071_1(self):
        admin = self.root.sf.getAdminService()

        common_group = self.new_group(perms="rwrw--")
        c1 = self.new_client(common_group)
        c2 = self.new_client(common_group)

        c1_pojos = c1.sf.getContainerService()
        c1_query = c1.sf.getQueryService()
        c1_update = c1.sf.getUpdateService()
        c1_uuid = c1.sf.getAdminService().getEventContext().sessionUuid

        c2_pojos = c2.sf.getContainerService()
        c2_query = c2.sf.getQueryService()
        c2_update = c2.sf.getUpdateService()
        c2_uuid = c2.sf.getAdminService().getEventContext().sessionUuid

        #projects
        pr1 = ProjectI()
        pr1.setName(rstring('test1071-pr1-%s' % (c1_uuid)))
        pr1 = c1_update.saveAndReturnObject(pr1)
        pr1.unload()

        pr2 = ProjectI()
        pr2.setName(rstring('test1071-pr2-%s' % (c2_uuid)))
        pr2 = c2_update.saveAndReturnObject(pr2)
        pr2.unload()

        #datasets
        ds1 = DatasetI()
        ds1.setName(rstring('test1071-ds1-%s' % (c1_uuid)))
        ds1 = c1_update.saveAndReturnObject(ds1)
        ds1.unload()

        ds2 = DatasetI()
        ds2.setName(rstring('test1071-ds2-%s' % (c2_uuid)))
        ds2 = c2_update.saveAndReturnObject(ds2)
        ds2.unload()

        #images
        im2 = ImageI()
        im2.setName(rstring('test1071-im2-%s' % (c2_uuid)))
        im2.acquisitionDate = rtime(0)
        im2 = c2_update.saveAndReturnObject(im2)
        im2.unload()

        #links
        # im2 owned by u2
        #
        # im2   -> ds2 --> pr2 (owned by u2)
        #      |
        #      \-> ds1 --> pr1 (owned by u1)
        #
        pdl1 = ProjectDatasetLinkI()
        pdl1.setParent(pr1)
        pdl1.setChild(ds1)
        c1_update.saveObject(pdl1)

        pdl2 = ProjectDatasetLinkI()
        pdl2.setParent(pr2)
        pdl2.setChild(ds2)
        c2_update.saveObject(pdl2)

        dil2 = DatasetImageLinkI()
        dil2.setParent(ds2)
        dil2.setChild(im2)
        c2_update.saveObject(dil2)

        dil1 = DatasetImageLinkI()
        dil1.setParent(ds1)
        dil1.setChild(im2)
        c1_update.saveObject(dil1)

        #test:
        hier = c2_pojos.findContainerHierarchies("Project", [long(im2.id.val)],
                                                 None)

        assert 2 == len(
            hier), "size of hier != 2: %s" % [type(x) for x in hier]
        for c in hier:
            if c.id.val == pr1.id.val and isinstance(c, ProjectI):
                assert 1 == c.sizeOfDatasetLinks()
                for pdl in c.copyDatasetLinks():
                    assert 1 == pdl.child.sizeOfImageLinks()
                    for dil in pdl.child.copyImageLinks():
                        assert dil.child.id.val == im2.id.val
            elif c.id.val == pr2.id.val and isinstance(c, ProjectI):
                assert 1 == c.sizeOfDatasetLinks()
            elif c.id.val == ds3.id.val and isinstance(c, DatasetI):
                assert 1 == c.sizeOfImageLinks()
Пример #40
0
def add_annotations(o):
    '''
    Annotation
        BasicAnnotation
            BooleanAnnotation
                BooleanAnnotationI
            NumericAnnotation
                DoubleAnnotation
                    DoubleAnnotationI
                LongAnnotation
                    LongAnnotationI
            TermAnnotation
                TermAnnotationI
            TimestampAnnotation
                TimestampAnnotationI
        ListAnnotation
            ListAnnotationI
        MapAnnotation
            MapAnnotationI
        TextAnnotation
            CommentAnnotation
                CommentAnnotationI
            TagAnnotation
                TagAnnotationI
            XmlAnnotation
                XmlAnnotationI
        TypeAnnotation
            FileAnnotation
                FileAnnotationI
    '''
    annotation = BooleanAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('boolean_annotation')
    annotation.boolValue = rbool(True)
    o.linkAnnotation(annotation)
    annotation = CommentAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('comment_annotation')
    annotation.textValue = rstring('text_value')
    o.linkAnnotation(annotation)
    annotation = DoubleAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('double_annotation')
    annotation.doubleValue = rdouble(1.0)
    o.linkAnnotation(annotation)
    annotation = LongAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('long_annotation')
    annotation.longValue = rlong(1L)
    o.linkAnnotation(annotation)
    annotation = MapAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('map_annotation')
    annotation.setMapValue([NamedValue('a', '1'), NamedValue('b', '2')])
    o.linkAnnotation(annotation)
    annotation = TagAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('tag_annotation')
    annotation.textValue = rstring('tag_value')
    o.linkAnnotation(annotation)
    annotation = TermAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('term_annotation')
    annotation.termValue = rstring('term_value')
    o.linkAnnotation(annotation)
    annotation = TimestampAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('timestamp_annotation')
    annotation.timeValue = rtime(1)
    o.linkAnnotation(annotation)
    annotation = XmlAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('xml_annotation')
    annotation.textValue = rstring('<xml_value></xml_value>')
    o.linkAnnotation(annotation)
Пример #41
0
    def search(self,
               query,
               onlyTypes,
               fields,
               searchGroup,
               ownedBy,
               useAcquisitionDate,
               date=None,
               rawQuery=False):
        # If rawQuery, the raw lucene query is used in search.byFullText()
        # and fields is ignored.
        # If fields contains 'annotation', we really want to search files too
        # docs.openmicroscopy.org/latest/omero/developers/Modules/Search.html
        fields = set(fields)
        if "annotation" in fields or "file" in fields:
            fields = fields.union(
                ("file.name", "file.path", "file.format", "file.contents"))
            fields.discard("file")  # Not supported
        fields = list(fields)

        if 'plates' in onlyTypes:
            onlyTypes.append('plateacquisitions')
        created = None
        self.moreResults = False
        batchSize = 500
        if len(onlyTypes) == 1:
            batchSize = 1000
        if date is not None:
            p = str(date).split('_')
            if len(p) > 1:
                try:
                    d1 = getDateTime(p[0] + " 00:00:00")
                    d2 = getDateTime(p[1] + " 23:59:59")

                    created = [
                        rtime(
                            long(
                                time.mktime(d1.timetuple()) +
                                1e-6 * d1.microsecond) * 1000),
                        rtime(
                            long(
                                time.mktime(d2.timetuple()) +
                                1e-6 * d2.microsecond) * 1000)
                    ]
                except ValueError:
                    # User entered an invalid date format - Ignore
                    pass
            else:
                msg = "date should be start_end, e.g. 2015-12-01_2016-01-01"
                raise ValueError(msg)

        def doSearch(searchType):
            """ E.g. searchType is 'images' """
            objType = searchType[0:-1]  # remove 's'

            obj_list = list(
                self.conn.searchObjects([objType],
                                        query,
                                        created,
                                        fields=fields,
                                        batchSize=batchSize,
                                        searchGroup=searchGroup,
                                        ownedBy=ownedBy,
                                        useAcquisitionDate=useAcquisitionDate,
                                        rawQuery=rawQuery), )
            return obj_list

        self.containers = {}
        resultCount = 0
        self.searchError = None
        self.iids = []

        try:
            for dt in onlyTypes:
                dt = str(dt)
                if dt in [
                        'projects', 'datasets', 'images', 'screens',
                        'plateacquisitions', 'plates', 'wells'
                ]:
                    self.containers[dt] = doSearch(dt)
                    if dt == "wells":
                        for well in self.containers[dt]:
                            well.name = "%s - %s" %\
                                        (well.listParents()[0].name,
                                         well.getWellPos())
                    if dt == 'images':
                        self.iids = [i.id for i in self.containers[dt]]
                    # If we get a full page of results, we know there are more
                    if len(self.containers[dt]) == batchSize:
                        self.moreResults = True
                    resultCount += len(self.containers[dt])
        except Exception as x:
            logger.info("Search Exception: %s" % x.message)
            if isinstance(x, omero.ServerError):
                # Only show message to user if we can be helpful
                if "TooManyClauses" in x.message:
                    self.searchError = (
                        "Please try to narrow down your query. The wildcard"
                        " matched too many terms.")
                elif ":" in query:
                    self.searchError = (
                        "There was an error parsing your query."
                        " Colons ':' are reserved for searches of"
                        " key-value annotations in the form: 'key:value'.")

        self.c_size = resultCount
Пример #42
0
 def new_image(self, name=""):
     img = omero.model.ImageI()
     img.name = rstring(name)
     img.acquisitionDate = rtime(0)
     return img
Пример #43
0
    def testObjectCreationEqualsAndHash(self):

        # RBool
        true1 = rbool(True)
        true2 = rbool(True)
        false1 = rbool(False)
        false2 = rbool(False)
        assert true1 == true2
        assert false1 == false2
        assert true1.getValue()
        assert not false1.getValue()
        assert true1 == true2
        assert true1 != false1

        # RDouble
        double_zero1 = rdouble(0.0)
        double_zero2 = rdouble(0.0)
        double_notzero1 = rdouble(1.1)
        double_notzero1b = rdouble(1.1)
        double_notzero2 = rdouble(2.2)
        assert double_zero1.getValue() == 0.0
        assert double_notzero1.getValue() == 1.1
        assert double_zero1 == double_zero2
        assert double_zero1 != double_notzero1
        assert double_notzero1 == double_notzero1b
        assert double_notzero1 != double_notzero2

        # RFloat
        float_zero1 = rfloat(0.0)
        float_zero2 = rfloat(0.0)
        float_notzero1 = rfloat(1.1)
        float_notzero1b = rfloat(1.1)
        float_notzero2 = rfloat(2.2)
        assert float_zero1.getValue() == 0.0
        assert float_notzero1.getValue() == 1.1
        assert float_zero1 == float_zero2
        assert float_zero1 != float_notzero1
        assert float_notzero1 == float_notzero1b
        assert float_notzero1 != float_notzero2

        # RInt
        int_zero1 = rint(0)
        int_zero2 = rint(0)
        int_notzero1 = rint(1)
        int_notzero1b = rint(1)
        int_notzero2 = rint(2)
        assert int_zero1.getValue() == 0
        assert int_notzero1.getValue() == 1
        assert int_zero1 == int_zero2
        assert int_zero1 != int_notzero1
        assert int_notzero1 == int_notzero1b
        assert int_notzero1 != int_notzero2

        # RLong
        long_zero1 = rlong(0)
        long_zero2 = rlong(0)
        long_notzero1 = rlong(1)
        long_notzero1b = rlong(1)
        long_notzero2 = rlong(2)
        assert long_zero1.getValue() == 0
        assert long_notzero1.getValue() == 1
        assert long_zero1 == long_zero2
        assert long_zero1 != long_notzero1
        assert long_notzero1 == long_notzero1b
        assert long_notzero1 != long_notzero2

        # RTime
        time_zero1 = rtime(0)
        time_zero2 = rtime(0)
        time_notzero1 = rtime(1)
        time_notzero1b = rtime(1)
        time_notzero2 = rtime(2)
        assert time_zero1.getValue() == 0
        assert time_notzero1.getValue() == 1
        assert time_zero1 == time_zero2
        assert time_zero1 != time_notzero1
        assert time_notzero1 == time_notzero1b
        assert time_notzero1 != time_notzero2

        # RInternal
        internal_null1 = rinternal(None)
        internal_null2 = rinternal(None)
        internal_notnull1 = rinternal(omero.grid.JobParams())
        internal_notnull2 = rinternal(omero.grid.JobParams())
        assert internal_null1 == internal_null2
        assert internal_null1 == internal_null2
        assert internal_null1 != internal_notnull2
        assert internal_notnull1 == internal_notnull1
        assert internal_notnull1 != internal_notnull2

        # RObject
        object_null1 = robject(None)
        object_null2 = robject(None)
        object_notnull1 = robject(omero.model.ImageI())
        object_notnull2 = robject(omero.model.ImageI())
        assert object_null1 == object_null2
        assert object_null1 == object_null2
        assert object_null1 != object_notnull2
        assert object_notnull1 == object_notnull1
        assert object_notnull1 != object_notnull2

        # RString
        string_null1 = rstring(None)
        string_null2 = rstring(None)
        string_notnull1 = rstring("str1")
        string_notnull1b = rstring("str1")
        string_notnull2 = rstring("str2")
        assert string_null1 == string_null2
        assert string_null1 == string_null2
        assert string_null1 != string_notnull2
        assert string_notnull1 == string_notnull1
        assert string_notnull1 != string_notnull2
        assert string_notnull1 == string_notnull1b

        # RClass
        class_null1 = rclass(None)
        class_null2 = rclass(None)
        class_notnull1 = rclass("str1")
        class_notnull1b = rclass("str1")
        class_notnull2 = rclass("str2")
        assert class_null1 == class_null2
        assert class_null1 == class_null2
        assert class_null1 != class_notnull2
        assert class_notnull1 == class_notnull1
        assert class_notnull1 != class_notnull2
        assert class_notnull1 == class_notnull1b
Пример #44
0
    def testUnwrap(self):
        # NUMS plain
        assert 0 == unwrap(0)
        assert 1 == unwrap(1)
        assert 0.0 == unwrap(0.0)
        assert 1.0 == unwrap(1.0)
        # NUMS rtyped
        assert 0 == unwrap(rint(0))
        assert 0 == unwrap(rlong(0))
        assert 1 == unwrap(rint(1))
        assert 1 == unwrap(rlong(1))
        assert 0.0 == unwrap(rfloat(0.0))
        assert 0.0 == unwrap(rdouble(0.0))
        assert 1.0 == unwrap(rfloat(1.0))
        assert 1.0 == unwrap(rdouble(1.0))

        # STRINGS
        assert "" == unwrap("")
        assert "str" == unwrap("str")

        # BOOL
        assert True == unwrap(True)
        assert False == unwrap(False)
        assert True == unwrap(rbool(True))
        assert False == unwrap(rbool(False))

        # TIME
        # Bit odd, do we want the long for time, or transformed?
        assert 0 == unwrap(rtime(0))
        assert 1 == unwrap(rtime(1))

        # CLASS
        # same for class, should we map it?
        assert "k" == unwrap(rclass("k"))

        # INTERNAL
        color = omero.Color()
        assert color == unwrap(rinternal(color))

        # OBJECT
        image = omero.model.ImageI()
        assert image == unwrap(robject(image))

        # COLLECTIONS
        # empty
        assert [] == unwrap([])
        assert {} == unwrap({})
        assert set() == unwrap(set())
        # plain in collection
        assert [1] == unwrap([1])
        # rtype in collection
        assert [1] == unwrap([rint(1)])
        assert {"a": 1} == unwrap({"a": 1})
        # plain in rcollection ILLEGAL
        # assert [1] == unwrap(rlist([1]))
        # assert {"a":1} == unwrap(rmap({"a":1}))
        # rtype in rcollection
        assert [1] == unwrap(rlist([rint(1)]))
        assert {"a": 1} == unwrap(rmap({"a": rint(1)}))
        # rtype keys ILLEGAL
        # assert {"a":1} == unwrap(rmap({rstring("a"):rint(1)}))
        # recursion, ticket:1977
        m1 = rmap({"a": rint(1)})
        m1.val["m1"] = m1
        m2 = {"a": 1}
        m2["m1"] = m2
        unwrap(m1)
        assert m2["a"] == unwrap(m1)["a"]
        # Can't compare directly "maximum recursion depth exceeded in cmp"
        assert type(m2["m1"]) == type(unwrap(m1)["m1"])
Пример #45
0
    def testDeleteProjectWithoutContent(self):
        uuid = self.client.sf.getAdminService().getEventContext().sessionUuid
        query = self.client.sf.getQueryService()
        update = self.client.sf.getUpdateService()

        images = list()
        for i in range(0, 5):
            img = omero.model.ImageI()
            img.name = rstring("test-delete-image-%i" % i)
            img.acquisitionDate = rtime(0)
            tag = omero.model.TagAnnotationI()
            img.linkAnnotation(tag)
            images.append(update.saveAndReturnObject(img).id.val)

        # create dataset
        dataset = omero.model.DatasetI()
        dataset.name = rstring('DS-test-2936-%s' % (uuid))
        dataset = update.saveAndReturnObject(dataset)
        # create project
        project = omero.model.ProjectI()
        project.name = rstring('PR-test-2936-%s' % (uuid))
        project = update.saveAndReturnObject(project)
        # put dataset in project
        link = omero.model.ProjectDatasetLinkI()
        link.parent = omero.model.ProjectI(project.id.val, False)
        link.child = omero.model.DatasetI(dataset.id.val, False)
        update.saveAndReturnObject(link)
        # put image in dataset
        for iid in images:
            dlink = omero.model.DatasetImageLinkI()
            dlink.parent = omero.model.DatasetI(dataset.id.val, False)
            dlink.child = omero.model.ImageI(iid, False)
            update.saveAndReturnObject(dlink)

        op = dict()
        op["/TagAnnotation"] = "KEEP"
        op["/TermAnnotation"] = "KEEP"
        op["/FileAnnotation"] = "KEEP"
        op["/Dataset"] = "KEEP"
        op["/Image"] = "KEEP"

        dc = omero.cmd.Delete('/Project', long(project.id.val), op)
        handle = self.client.sf.submit(dc)
        self.waitOnCmd(self.client, handle)

        assert not query.find('Project', project.id.val)
        assert dataset.id.val == query.find('Dataset', dataset.id.val).id.val

        p = omero.sys.Parameters()
        p.map = {}
        p.map["oid"] = dataset.id

        sql = "select im from Image im "\
              "left outer join fetch im.datasetLinks dil "\
              "left outer join fetch dil.parent d " \
              "where d.id = :oid " \
              "order by im.id asc"
        res = query.findAllByQuery(sql, p)
        assert 5 == len(res)
        for e in res:
            if e.id.val not in images:
                self.assertRaises(
                    'Image %i is not in the [%s]'
                    % (e.id.val, ",".join(images)))
Пример #46
0
 def testPassThroughNoneAndRTypes(self):
     """
     To prevent having to check for isintance(int,...) or
     isintance(RInt,...) all over the place, the static methods
     automatically check for acceptable
     types and simply pass them through. Similarly, the primitive types all
     check for None and return a null RType if necessary.
     """
     # Bool
     assert None == rbool(None)
     assert rbool(True) == rbool(rbool(True))
     assert rbool(True) == rbool(1)
     assert rbool(False) == rbool(0)
     # Double
     assert None == rdouble(None)
     assert rdouble(0.0) == rdouble(rdouble(0.0))
     assert rdouble(0.0) == rdouble(rdouble(0))
     assert rdouble(0.0) == rdouble(rdouble("0.0"))
     pytest.raises(ValueError, lambda: rdouble("string"))
     # Float
     assert None == rfloat(None)
     assert rfloat(0.0) == rfloat(rfloat(0.0))
     assert rfloat(0.0) == rfloat(rfloat(0))
     assert rfloat(0.0) == rfloat(rfloat("0.0"))
     pytest.raises(ValueError, lambda: rfloat("string"))
     # Long
     assert None == rlong(None)
     assert rlong(0) == rlong(rlong(0))
     assert rlong(0) == rlong(rlong(0.0))
     assert rlong(0) == rlong(rlong("0"))
     pytest.raises(ValueError, lambda: rlong("string"))
     # Time
     assert None == rtime(None)
     assert rtime(0) == rtime(rtime(0))
     assert rtime(0) == rtime(rtime(0.0))
     assert rtime(0) == rtime(rtime("0"))
     pytest.raises(ValueError, lambda: rtime("string"))
     # Int
     assert None == rint(None)
     assert rint(0) == rint(rint(0))
     assert rint(0) == rint(rint(0.0))
     assert rint(0) == rint(rint("0"))
     pytest.raises(ValueError, lambda: rint("string"))
     #
     # Starting here handling of null is different.
     #
     # String
     assert rstring("") == rstring(None)
     assert rstring("a") == rstring(rstring("a"))
     pytest.raises(ValueError, lambda: rstring(0))
     # Class
     assert rclass("") == rclass(None)
     assert rclass("c") == rclass(rclass("c"))
     pytest.raises(ValueError, lambda: rclass(0))
     # Internal
     internal = omero.Internal()
     assert rinternal(None) == rinternal(None)
     assert rinternal(internal) == rinternal(rinternal(internal))
     pytest.raises(ValueError, lambda: rinternal("string"))
     # Object
     obj = omero.model.ImageI()
     assert robject(None) == robject(None)
     assert robject(obj) == robject(robject(obj))
     pytest.raises(ValueError, lambda: robject("string"))
     #
     # Same does not hold for collections
     #
     # Array
     assert rarray([]) == rarray(None)
     # assert rarray(obj) == rarray(rarray(obj))
     # pytest.raises(ValueError, lambda : rarray("string"))
     # List
     assert rlist([]) == rlist(None)
     # assert rlist(obj) == rlist(rlist(obj))
     # pytest.raises(ValueError, lambda : rlist("string"))
     # Set
     assert rset([]) == rset(None)
     # assert rset(obj) == rset(rset(obj))
     # pytest.raises(ValueError, lambda : rset("string"))
     # Map
     assert rmap({}) == rmap(None)
Пример #47
0
    def test1172(self):
        uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
        share = self.root.sf.getShareService()
        query = self.root.sf.getQueryService()
        update = self.root.sf.getUpdateService()

        ### create user
        client_share1, user1 = self.new_client_and_user()

        #create dataset with image
        #dataset with image
        ds = omero.model.DatasetI()
        ds.setName(rstring("dataset-%s" % (uuid)))
        ds = update.saveAndReturnObject(ds)
        ds.unload()

        # create image
        img = ImageI()
        img.setName(rstring('test-img in dataset-%s' % (uuid)))
        img.setAcquisitionDate(rtime(0))
        img = update.saveAndReturnObject(img)
        img.unload()

        dil = DatasetImageLinkI()
        dil.setParent(ds)
        dil.setChild(img)
        dil = update.saveAndReturnObject(dil)
        dil.unload()

        # create share by root
        items = list()
        ms = list()

        p = omero.sys.Parameters()
        p.map = {}
        p.map["oid"] = ds.id
        sql = "select ds from Dataset ds join fetch ds.details.owner join fetch ds.details.group " \
              "left outer join fetch ds.imageLinks dil left outer join fetch dil.child i " \
              "where ds.id=:oid"
        items.extend(query.findAllByQuery(sql, p))
        assert 1 == len(items)

        #members
        p.map["eid"] = rlong(user1.id.val)
        sql = "select e from Experimenter e where e.id =:eid order by e.omeName"
        ms = query.findAllByQuery(sql, p)
        sid = share.createShare(("test-share-%s" % uuid),
                                rtime(long(time.time() * 1000 + 86400)), items,
                                ms, [], True)

        # USER RETRIEVAL
        ## login as user1
        share1 = client_share1.sf.getShareService()
        query1 = client_share1.sf.getQueryService()
        cntar1 = client_share1.sf.getContainerService()

        content = share1.getContents(sid)
        # Content now contains just the dataset with nothing loaded
        assert 1 == len(content)

        # get shared dataset and image when share is activated
        share1.activate(sid)

        #retrieve dataset
        p = omero.sys.Parameters()
        p.map = {}
        p.map["ids"] = rlist([ds.id])
        sql = "select ds from Dataset ds join fetch ds.details.owner join fetch ds.details.group " \
              "left outer join fetch ds.imageLinks dil left outer join fetch dil.child i " \
              "where ds.id in (:ids) order by ds.name"
        try:
            res1 = query1.findAllByQuery(sql, p)
            assert False, "This should throw an exception"
        except:
            pass

        #
        # Now we add all the other elements to the share to prevent
        # the security violation
        #
        # Not working imgs = cntar.getImages("Dataset",[ds.id.val], None)
        img = query.findByQuery(
            "select i from Image i join fetch i.datasetLinks dil join dil.parent d where d.id = %s "
            % ds.id.val, None)
        assert img
        share.addObject(sid, img)
        share.addObjects(sid, img.copyDatasetLinks())
        assert 3 == len(share.getContents(sid))

        #
        # And try again to load them
        #
        share1.activate(sid)
        res1 = query1.findAllByQuery(sql, p)
        assert len(res1) == 1
        for e in res1:
            assert e.id.val == ds.id.val

        # retrieve only image
        p = omero.sys.Parameters()
        p.map = {}
        p.map["oid"] = rlong(img.id)
        sql = "select im from Image im " \
              "where im.id=:oid order by im.name"
        res2 = query1.findByQuery(sql, p)
        assert res2.id.val == img.id.val
Пример #48
0
 def testFindAnnotations(self):
     ipojo = self.client.sf.getContainerService()
     i = ImageI()
     i.setName(rstring("name"))
     i.setAcquisitionDate(rtime(0))
     i = ipojo.createDataObject(i, None)
Пример #49
0
def run():
    '''
    '''
    client = scripts.client(
        'Edit_Object_Attribute.py',
        'Edit the attributes of an object',
        scripts.String('Data_Type',
                       optional=False,
                       grouping='1',
                       description='The data type you want to work with.'),
        scripts.Long('ID',
                     optional=False,
                     grouping='2',
                     description='Object ID'),
        scripts.String('Attribute',
                       optional=False,
                       grouping='3',
                       description='Attribute to set'),
        scripts.String('Attribute_Type',
                       optional=False,
                       grouping='4',
                       description='Type of the attribute to set',
                       values=[
                           rstring('Bool'),
                           rstring('Double'),
                           rstring('Float'),
                           rstring('Int'),
                           rstring('Long'),
                           rstring('Time'),
                           rstring('String')
                       ],
                       default='String'),
        scripts.String('Value',
                       optional=False,
                       grouping='5',
                       description='Value to set'),
        version='0.1',
        authors=['Chris Allan'],
        institutions=['Glencoe Software Inc.'],
        contact='*****@*****.**',
    )

    try:
        script_params = {}
        for key in client.getInputKeys():
            if client.getInput(key):
                script_params[key] = client.getInput(key, unwrap=True)

        session = client.getSession()
        update_service = session.getUpdateService()
        query_service = session.getQueryService()

        value = script_params['Value']
        if script_params['Attribute_Type'] == 'Bool':
            value = rtype(bool(value))
        elif script_params['Attribute_Type'] == 'Double':
            value = rdouble(float(value))
        elif script_params['Attribute_Type'] == 'Float':
            value = rtype(float(value))
        elif script_params['Attribute_Type'] == 'Int':
            value = rtype(int(value))
        elif script_params['Attribute_Type'] == 'Long':
            value = rtype(int(value))
        elif script_params['Attribute_Type'] == 'Time':
            value = rtime(int(value))
        else:
            value = rtype(value)

        ctx = {'omero.group': '-1'}
        o = query_service.get(script_params['Data_Type'], script_params['ID'],
                              ctx)
        setattr(o, script_params['Attribute'], value)
        ctx = None
        try:
            ctx = {'omero.group': str(o.details.group.id.val)}
        except AttributeError:
            pass
        update_service.saveObject(o, ctx)

        client.setOutput('Message',
                         rstring('Setting of attribute successful.'))
    finally:
        client.closeSession()
Пример #50
0
 def testBasics(self):
     p = ParametersI()
     p.exp(rlong(1))
     p.grp(rlong(1))
     p.endTime(rtime(1))