forked from ome/openmicroscopy
/
__init__.py
7939 lines (6635 loc) · 281 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# blitz_gateway - python bindings and wrappers to access an OMERO blitz server
#
# Copyright (c) 2007, 2010 Glencoe Software, Inc. All rights reserved.
#
# This software is distributed under the terms described by the LICENCE file
# you can find at the root of the distribution bundle, which states you are
# free to use it only for non commercial purposes.
# If the file is missing please request a copy by contacting
# jason@glencoesoftware.com.
# Set up the python include paths
import os,sys
THISPATH = os.path.dirname(os.path.abspath(__file__))
import warnings
import shutil
import tempfile
from types import IntType, LongType, UnicodeType, ListType, TupleType, StringType, StringTypes
from datetime import datetime
from cStringIO import StringIO
import ConfigParser
import omero
import omero.clients
from omero.util.decorators import timeit, TimeIt, setsessiongroup
from omero.cmd import Chgrp, DoAll
from omero.api import Save
from omero.callbacks import CmdCallbackI
from omero.gateway.utils import ServiceOptsDict, GatewayConfig
import omero.scripts as scripts
import Ice
import Glacier2
import traceback
import time
import array
import math
import logging
logger = logging.getLogger(__name__)
try:
from PIL import Image, ImageDraw, ImageFont # see ticket:2597
except: #pragma: nocover
try:
import Image, ImageDraw, ImageFont # see ticket:2597
except:
logger.error('No PIL installed, line plots and split channel will fail!')
from cStringIO import StringIO
from math import sqrt
from omero.rtypes import rstring, rint, rlong, rbool, rtime, rlist, rdouble, unwrap
def omero_type(val):
"""
Converts rtypes from static factory methods:
- StringType to rstring
- UnicodeType to rstring
- IntType to rint
- LongType to rlong
elswere return the argument itself
@param val: value
@rtype: omero.rtype
@return: matched RType or value
"""
if isinstance(val, StringType):
return rstring(val)
elif isinstance(val, UnicodeType):
return rstring(val.encode('utf-8'))
elif isinstance(val, IntType):
return rint(val)
elif isinstance(val, LongType):
return rlong(val)
else:
return val
def fileread (fin, fsize, bufsize):
"""
Reads everything from fin, in chunks of bufsize.
@type fin: file
@param fin: filelike readable object
@type fsize: int
@param fsize: total number of bytes to read
@type bufsize: int
@param fsize: size of each chunk of data read from fin
@rtype: string
@return: string buffer holding the contents read from the file
"""
# Read it all in one go
p = 0
rv = ''
while p < fsize:
s = min(bufsize, fsize-p)
rv += fin.read(p,s)
p += s
fin.close()
return rv
def fileread_gen (fin, fsize, bufsize):
"""
Generator helper function that yields chunks of the file of size fsize.
@type fin: file
@param fin: filelike readable object
@type fsize: int
@param fsize: total number of bytes to read
@type bufsize: int
@param fsize: size of each chunk of data read from fin that gets yielded
@rtype: generator
@return: generator of string buffers of size up to bufsize read from fin
"""
p = 0
while p < fsize:
s = min(bufsize, fsize-p)
yield fin.read(p,s)
p += s
fin.close()
class BlitzObjectWrapper (object):
"""
Object wrapper class which provides various methods for hierarchy traversing,
saving, handling permissions etc.
This is the 'abstract' super class which is subclassed by
E.g. _ProjectWrapper, _DatasetWrapper etc.
All ojbects have a reference to the L{BlitzGateway} connection, and therefore all services are
available for handling calls on the object wrapper. E.g listChildren() uses queryservice etc.
"""
OMERO_CLASS = None # E.g. 'Project', 'Dataset', 'Experimenter' etc.
LINK_CLASS = None
LINK_CHILD = 'child'
CHILD_WRAPPER_CLASS = None
PARENT_WRAPPER_CLASS = None
@staticmethod
def LINK_PARENT (x):
return x.parent
def __init__ (self, conn=None, obj=None, cache=None, **kwargs):
"""
Initialises the wrapper object, setting the various class variables etc
@param conn: The L{omero.gateway.BlitzGateway} connection.
@type conn: L{omero.gateway.BlitzGateway}
@param obj: The object to wrap. E.g. omero.model.Image
@type obj: omero.model object
@param cache: Cache which is passed to new child wrappers
"""
self.__bstrap__()
self._obj = obj
self._cache = cache
if self._cache is None:
self._cache = {}
self._conn = conn
self._creationDate = None
if conn is None:
return
if hasattr(obj, 'id') and obj.id is not None:
self._oid = obj.id.val
if not self._obj.loaded:
self._obj = self._conn.getQueryService().get(self._obj.__class__.__name__, self._oid, self._conn.SERVICE_OPTS)
self.__prepare__ (**kwargs)
def __eq__ (self, a):
"""
Returns true if the object is of the same type and has same id and name
@param a: The object to compare to this one
@return: True if objects are same - see above
@rtype: Boolean
"""
return type(a) == type(self) and self._obj.id == a._obj.id and self.getName() == a.getName()
def __bstrap__ (self):
""" Initialisation method which is implemented by subclasses to set their class variables etc. """
pass
def __prepare__ (self, **kwargs):
""" Initialisation method which is implemented by subclasses to handle various init tasks """
pass
def __repr__ (self):
"""
Returns a String representation of the Object, including ID if set.
@return: String E.g. '<DatasetWrapper id=123>'
@rtype: String
"""
if hasattr(self, '_oid'):
return '<%s id=%s>' % (self.__class__.__name__, str(self._oid))
return super(BlitzObjectWrapper, self).__repr__()
def _getQueryString(self):
"""
Used for building queries in generic methods such as getObjects("Project")
"""
return "select obj from %s obj join fetch obj.details.owner as owner join fetch obj.details.group "\
"join fetch obj.details.creationEvent" % self.OMERO_CLASS
def _getChildWrapper (self):
"""
Returns the wrapper class of children of this object.
Checks that this is one of the Wrapper objects in the L{omero.gateway} module
Raises NotImplementedError if this is not true or class is not defined (None)
This is used internally by the L{listChildren} and L{countChildren} methods.
@return: The child wrapper class. E.g. omero.gateway.DatasetWrapper.__class__
@rtype: class
"""
if self.CHILD_WRAPPER_CLASS is None: #pragma: no cover
raise NotImplementedError('%s has no child wrapper defined' % self.__class__)
if type(self.CHILD_WRAPPER_CLASS) is type(''):
# resolve class
if hasattr(omero.gateway, self.CHILD_WRAPPER_CLASS):
self.__class__.CHILD_WRAPPER_CLASS = self.CHILD_WRAPPER_CLASS = getattr(omero.gateway, self.CHILD_WRAPPER_CLASS)
else: #pragma: no cover
raise NotImplementedError
return self.CHILD_WRAPPER_CLASS
def _getParentWrappers (self):
"""
Returns the wrapper classes of the parent of this object.
This is used internally by the L{listParents} method.
@return: List of parent wrapper classes. E.g. omero.gateway.DatasetWrapper.__class__
@rtype: class
"""
if self.PARENT_WRAPPER_CLASS is None: #pragma: no cover
raise NotImplementedError
pwc = self.PARENT_WRAPPER_CLASS
if not isinstance(pwc, ListType):
pwc = [pwc,]
for i in range(len(pwc)):
if isinstance(pwc[i], StringTypes):
# resolve class
g = globals()
if not g.has_key(pwc[i]): #pragma: no cover
raise NotImplementedError
pwc[i] = g[pwc[i]]
#if type(self.PARENT_WRAPPER_CLASS) is type(''):
# # resolve class
# g = globals()
# if not g.has_key(self.PARENT_WRAPPER_CLASS): #pragma: no cover
# raise NotImplementedError
# self.__class__.PARENT_WRAPPER_CLASS = self.PARENT_WRAPPER_CLASS = g[self.PARENT_WRAPPER_CLASS]
#return self.PARENT_WRAPPER_CLASS
if pwc != self.PARENT_WRAPPER_CLASS or pwc != self.__class__.PARENT_WRAPPER_CLASS:
self.__class__.PARENT_WRAPPER_CLASS = self.PARENT_WRAPPER_CLASS = pwc
return self.PARENT_WRAPPER_CLASS
def __loadedHotSwap__ (self):
"""
Loads the object that is wrapped by this class. This includes linked objects.
This method can be overwritten by subclasses that want to specify how/which linked objects
are loaded.
"""
self._obj = self._conn.getContainerService().loadContainerHierarchy(self.OMERO_CLASS, (self._oid,), None, self._conn.SERVICE_OPTS)[0]
def _moveLink (self, newParent):
"""
Moves this object from a parent container (first one if there are more than one) to a new parent.
TODO: might be more useful if it didn't assume only 1 parent - option allowed you to specify the oldParent.
@param newParent: The new parent Object Wrapper.
@return: True if moved from parent to parent.
False if no parent exists or newParent has mismatching type
@rtype: Boolean
"""
p = self.getParent()
# p._obj.__class__ == p._obj.__class__ ImageWrapper(omero.model.DatasetI())
if p.OMERO_CLASS == newParent.OMERO_CLASS:
link = self._conn.getQueryService().findAllByQuery("select l from %s as l where l.parent.id=%i and l.child.id=%i" % (p.LINK_CLASS, p.id, self.id), None, self._conn.SERVICE_OPTS)
if len(link):
link[0].parent = newParent._obj
self._conn.getUpdateService().saveObject(link[0], self._conn.SERVICE_OPTS)
return True
logger.debug("## query didn't return objects: 'select l from %s as l where l.parent.id=%i and l.child.id=%i'" % (p.LINK_CLASS, p.id, self.id))
else:
logger.debug("## %s != %s ('%s' - '%s')" % (type(p), type(newParent), str(p), str(newParent)))
return False
def findChildByName (self, name, description=None):
"""
Find the first child object with a matching name, and description if specified.
@param name: The name which must match the child name
@param description: If specified, child description must match too
@return: The wrapped child object
@rtype: L{BlitzObjectWrapper}
"""
for c in self.listChildren():
if c.getName() == name:
if description is None or omero_type(description) == omero_type(c.getDescription()):
return c
return None
def getDetails (self):
"""
Gets the details of the wrapped object
@return: L{omero.gateway.DetailsWrapper} or None if object not loaded
@rtype: L{DetailsWrapper}
"""
if self._obj.loaded:
return omero.gateway.DetailsWrapper (self._conn, self._obj.getDetails())
return None
def getDate(self):
"""
Returns the object's acquisitionDate, or creation date (details.creationEvent.time)
@return: A L{datetime.datetime} object
@rtype: datetime
"""
try:
if self._obj.acquisitionDate.val is not None and self._obj.acquisitionDate.val > 0:
t = self._obj.acquisitionDate.val
return datetime.fromtimestamp(t/1000)
except:
# object doesn't have acquisitionDate
pass
return self.creationEventDate()
def save (self):
"""
Uses the updateService to save the wrapped object.
@rtype: None
"""
ctx = self._conn.SERVICE_OPTS.copy()
if self.getDetails() and self.getDetails().getGroup():
# This is a save for an object that already exists, make sure group matches
ctx.setOmeroGroup(self.getDetails().getGroup().getId())
self._obj = self._conn.getUpdateService().saveAndReturnObject(self._obj, ctx)
def saveAs (self, details):
"""
Save this object, keeping the object owner the same as the one on provided details
If the current user is an admin but is NOT the owner specified in 'details',
then create a new connection for that owner, clone the current object under that
connection and save.
Otherwise, simply save.
@param details: The Details specifying owner to save to
@type details: L{DetailsWrapper}
@return: None
"""
if self._conn.isAdmin():
d = self.getDetails()
if d.getOwner() and \
d.getOwner().omeName == details.getOwner().omeName and \
d.getGroup().name == details.getGroup().name:
return self.save()
else:
newConn = self._conn.suConn(details.getOwner().omeName, details.getGroup().name)
#p = omero.sys.Principal()
#p.name = details.getOwner().omeName
#p.group = details.getGroup().name
#p.eventType = "User"
#newConnId = self._conn.getSessionService().createSessionWithTimeout(p, 60000)
#newConn = self._conn.clone()
#newConn.connect(sUuid=newConnId.getUuid().val)
clone = self.__class__(newConn, self._obj)
clone.save()
self._obj = clone._obj
return
else:
return self.save()
def canWrite (self):
"""
Delegates to the connection L{BlitzGateway.canWrite} method
@rtype: Boolean
"""
return self._conn.canWrite(self)
def canOwnerWrite (self):
"""
Delegates to the connection L{BlitzGateway.canWrite} method
@rtype: Boolean
@return: True if the objects's permissions allow owner to write
"""
return self._conn.canOwnerWrite(self)
def isOwned(self):
"""
Returns True if the object owner is the same user specified in the connection's Event Context
@rtype: Boolean
@return: True if current user owns this object
"""
return (self._obj.details.owner.id.val == self._conn.getUserId())
def isLeaded(self):
"""
Returns True if the group that this object belongs to is lead by the currently logged-in user
@rtype: Boolean
@return: see above
"""
g = self._obj.details.group or self._obj.details
if g.id.val in self._conn.getEventContext().leaderOfGroups:
return True
return False
def isPublic(self):
"""
Determines if the object permissions are world readable, ie permissions.isWorldRead()
@rtype: Boolean
@return: see above
"""
g = self.getDetails().getGroup()
g = g and g.details or self._obj.details
return g.permissions.isWorldRead()
def isShared(self):
"""
Determines if the object is sharable between groups (but not public)
@rtype: Boolean
@return: True if the object is not L{public<isPublic>} AND the
object permissions allow group read.
"""
if not self.isPublic():
g = self.getDetails().getGroup()
g = g and g.details or self._obj.details
return g.permissions.isGroupRead()
return False
def isPrivate(self):
"""
Determines if the object is private
@rtype: Boolean
@return: True if the object is not L{public<isPublic>} and not L{shared<isShared>} and
permissions allow user to read.
"""
if not self.isPublic() and not self.isShared():
g = self.getDetails().getGroup()
g = g and g.details or self._obj.details
return g.permissions.isUserRead()
return False
def canEdit(self):
"""
Determines if the current user can Edit (E.g. name, description) link (E.g. Project, Dataset, Image etc)
or Delete this object. The canEdit() property is set on the permissions of every object as
it is read from the server, based on the current user, event context and group permissions.
@rtype: Boolean
@return: True if user can Edit this object Delete, link etc.
"""
return self.getDetails().getPermissions().canEdit()
def canDelete(self):
"""
Determines if the current user can Delete the object
"""
return self.getDetails().getPermissions().canDelete()
def canLink(self):
"""
Determines whether user can create 'hard' links (Not annotation links).
E.g. Between Project/Dataset/Image etc.
We have decided to restrict the clients to only allow the OWNER of data
to create these links.
The server is more permissive. To see what the server will allow,
use self.getDetails().getPermissions().canLink()
"""
return self.isOwned()
def canAnnotate(self):
"""
Determines if the current user can annotate this object: ie create annotation links.
The canAnnotate() property is set on the permissions of every object as
it is read from the server, based on the current user, event context and group permissions.
@rtype: Boolean
@return: True if user can Annotate this object
"""
return self.getDetails().getPermissions().canAnnotate()
def canChgrp(self):
"""
Specifies whether the current user can move this object to another group.
Web client will only allow this for the data Owner.
Admin CAN move other user's data, but we don't support this in Web yet.
"""
return self.isOwned() # or self._conn.isAdmin() #8974
def countChildren (self):
"""
Counts available number of child objects.
@return: The number of child objects available
@rtype: Long
"""
childw = self._getChildWrapper()
klass = "%sLinks" % childw().OMERO_CLASS.lower()
#self._cached_countChildren = len(self._conn.getQueryService().findAllByQuery("from %s as c where c.parent.id=%i" % (self.LINK_CLASS, self._oid), None))
self._cached_countChildren = self._conn.getContainerService().getCollectionCount(self.OMERO_CLASS, klass, [self._oid], None, self._conn.SERVICE_OPTS)[self._oid]
return self._cached_countChildren
def countChildren_cached (self):
"""
countChildren, but caching the first result, useful if you need to call this multiple times in
a single sequence, but have no way of storing the value between them.
It is actually a hack to support django template's lack of break in for loops
@return: The number of child objects available
@rtype: Long
"""
if not hasattr(self, '_cached_countChildren'):
return self.countChildren()
return self._cached_countChildren
def _listChildren (self, ns=None, val=None, params=None):
"""
Lists available child objects.
@rtype: generator of Ice client proxy objects for the child nodes
@return: child objects.
"""
if not params:
params = omero.sys.Parameters()
if not params.map:
params.map = {}
params.map["dsid"] = omero_type(self._oid)
query = "select c from %s as c" % self.LINK_CLASS
if ns is not None:
params.map["ns"] = omero_type(ns)
query += """ join fetch c.child as ch
left outer join fetch ch.annotationLinks as ial
left outer join fetch ial.child as a """
query += " where c.parent.id=:dsid"
if ns is not None:
query += " and a.ns=:ns"
if val is not None:
if isinstance(val, StringTypes):
params.map["val"] = omero_type(val)
query +=" and a.textValue=:val"
query += " order by c.child.name"
for child in ( x.child for x in self._conn.getQueryService().findAllByQuery(query, params, self._conn.SERVICE_OPTS) ):
yield child
def listChildren (self, ns=None, val=None, params=None):
"""
Lists available child objects.
@rtype: generator of L{BlitzObjectWrapper} objs
@return: child objects.
"""
childw = self._getChildWrapper()
for child in self._listChildren(ns=ns, val=val, params=params):
yield childw(self._conn, child, self._cache)
def getParent (self, withlinks=False):
"""
List a single parent, if available.
While the model suports many to many relationships between most objects, there are
implementations that assume a single project per dataset, a single dataset per image,
etc. This is just a shortcut method to return a single parent object.
@type withlinks: Boolean
@param withlinks: if true result will be a tuple of (linkobj, obj)
@rtype: L{BlitzObjectWrapper} ( or tuple(L{BlitzObjectWrapper}, L{BlitzObjectWrapper}) )
@return: the parent object with or without the link depending on args
"""
rv = self.listParents(withlinks=withlinks)
return len(rv) and rv[0] or None
def listParents (self, withlinks=False):
"""
Lists available parent objects.
@type withlinks: Boolean
@param withlinks: if true each yielded result will be a tuple of (linkobj, obj)
@rtype: list of L{BlitzObjectWrapper} ( or tuple(L{BlitzObjectWrapper}, L{BlitzObjectWrapper}) )
@return: the parent objects, with or without the links depending on args
"""
if self.PARENT_WRAPPER_CLASS is None:
return ()
parentw = self._getParentWrappers()
param = omero.sys.Parameters() # TODO: What can I use this for?
parentnodes = []
for pwc in parentw:
pwck = pwc()
if withlinks:
parentnodes.extend([(pwc(self._conn, pwck.LINK_PARENT(x), self._cache), BlitzObjectWrapper(self._conn, x)) for x in self._conn.getQueryService().findAllByQuery("from %s as c where c.%s.id=%i" % (pwck.LINK_CLASS, pwck.LINK_CHILD, self._oid), param, self._conn.SERVICE_OPTS)])
else:
t = self._conn.getQueryService().findAllByQuery("from %s as c where c.%s.id=%i" % (pwck.LINK_CLASS, pwck.LINK_CHILD, self._oid), param, self._conn.SERVICE_OPTS)
parentnodes.extend([pwc(self._conn, pwck.LINK_PARENT(x), self._cache) for x in t])
return parentnodes
def getAncestry (self):
"""
Get a list of Ancestors. First in list is parent of this object.
TODO: Assumes getParent() returns a single parent.
@rtype: List of L{BlitzObjectWrapper}
@return: List of Ancestor objects
"""
rv = []
p = self.getParent()
while p:
rv.append(p)
p = p.getParent()
return rv
def getParentLinks(self, pids=None):
"""
Get a list of parent objects links.
@param pids: List of parent IDs
@type pids: L{Long}
@rtype: List of L{BlitzObjectWrapper}
@return: List of parent object links
"""
if self.PARENT_WRAPPER_CLASS is None:
raise AttributeError("This object has no parent objects")
parentwrappers = self._getParentWrappers()
link_class = None
for v in parentwrappers:
link_class = v().LINK_CLASS
if link_class is not None:
break
if link_class is None:
raise AttributeError(
"This object has no parent objects with a link class!")
query_serv = self._conn.getQueryService()
p = omero.sys.Parameters()
p.map = {}
p.map["child"] = rlong(self.id)
sql = "select pchl from %s as pchl " \
"left outer join fetch pchl.parent as parent " \
"left outer join fetch pchl.child as child " \
"where child.id=:child" % link_class
if isinstance(pids, list) and len(pids) > 0:
p.map["parent"] = rlist([rlong(pa) for pa in pids])
sql+=" and parent.id in (:parent)"
for pchl in query_serv.findAllByQuery(sql, p, self._conn.SERVICE_OPTS):
yield BlitzObjectWrapper(self, pchl)
def getChildLinks(self, chids=None):
"""
Get a list of child objects links.
@param chids: List of children IDs
@type chids: L{Long}
@rtype: List of L{BlitzObjectWrapper}
@return: List of child object links
"""
if self.CHILD_WRAPPER_CLASS is None:
raise AttributeError("This object has no child objects")
childw = self._getChildWrapper()
query_serv = self._conn.getQueryService()
p = omero.sys.Parameters()
p.map = {}
p.map["parent"] = rlong(self.id)
sql = "select pchl from %s as pchl left outer join fetch pchl.child as child \
left outer join fetch pchl.parent as parent where parent.id=:parent" % self.LINK_CLASS
if isinstance(chids, list) and len(chids) > 0:
p.map["children"] = rlist([rlong(ch) for ch in chids])
sql+=" and child.id in (:children)"
for pchl in query_serv.findAllByQuery(sql, p, self._conn.SERVICE_OPTS):
yield BlitzObjectWrapper(self, pchl)
def _loadAnnotationLinks (self):
""" Loads the annotation links for the object (if not already loaded) and saves them to the object """
if not hasattr(self._obj, 'isAnnotationLinksLoaded'): #pragma: no cover
raise NotImplementedError
# Need to set group context. If '-1' then canDelete() etc on annotations will be False
ctx = self._conn.SERVICE_OPTS.copy()
ctx.setOmeroGroup(self.details.group.id.val)
if not self._obj.isAnnotationLinksLoaded():
query = "select l from %sAnnotationLink as l join fetch l.details.owner join fetch l.details.creationEvent "\
"join fetch l.child as a join fetch a.details.owner join fetch a.details.creationEvent "\
"where l.parent.id=%i" % (self.OMERO_CLASS, self._oid)
links = self._conn.getQueryService().findAllByQuery(query, None, ctx)
self._obj._annotationLinksLoaded = True
self._obj._annotationLinksSeq = links
# _listAnnotationLinks
def _getAnnotationLinks (self, ns=None):
"""
Checks links are loaded and returns a list of Annotation Links filtered by
namespace if specified
@param ns: Namespace
@type ns: String
@return: List of Annotation Links on this object
@rtype: List of Annotation Links
"""
self._loadAnnotationLinks()
rv = self.copyAnnotationLinks()
if ns is not None:
rv = filter(lambda x: x.getChild().getNs() and x.getChild().getNs().val == ns, rv)
return rv
def unlinkAnnotations (self, ns):
"""
Uses updateService to unlink annotations, with specified ns
@param ns: Namespace
@type ns: String
"""
dcs = []
for al in self._getAnnotationLinks(ns=ns):
dcs.append(omero.cmd.Delete(
"/%s" % al.ice_id().split("::")[-1], # This could be refactored
al.id.val, None))
# Using omero.cmd.Delete rather than deleteObjects since we need
# spec/id pairs rather than spec+id_list as arguments
if len(dcs):
doall = omero.cmd.DoAll()
doall.requests = dcs
handle = self._conn.c.sf.submit(doall, self._conn.SERVICE_OPTS)
try:
self._conn._waitOnCmd(handle)
finally:
handle.close()
self._obj.unloadAnnotationLinks()
def removeAnnotations (self, ns):
"""
Uses the delete service to delete annotations, with a specified ns,
and their links on the object and any other objects. Will raise a
L{omero.LockTimeout} if the annotation removal has not finished in
5 seconds.
@param ns: Namespace
@type ns: String
"""
ids = list()
for al in self._getAnnotationLinks(ns=ns):
a = al.child
ids.append(a.id.val)
if len(ids):
handle = self._conn.deleteObjects('/Annotation', ids)
try:
self._conn._waitOnCmd(handle)
finally:
handle.close()
self._obj.unloadAnnotationLinks()
# findAnnotations(self, ns=[])
def getAnnotation (self, ns=None):
"""
Gets the first annotation on the object, filtered by ns if specified
@param ns: Namespace
@type ns: String
@return: L{AnnotationWrapper} or None
"""
rv = self._getAnnotationLinks(ns)
if len(rv):
return AnnotationWrapper._wrap(self._conn, rv[0].child, link=rv[0])
return None
def listAnnotations (self, ns=None):
"""
List annotations in the ns namespace, linked to this object
@return: Generator yielding L{AnnotationWrapper}
@rtype: L{AnnotationWrapper} generator
"""
for ann in self._getAnnotationLinks(ns):
yield AnnotationWrapper._wrap(self._conn, ann.child, link=ann)
def listOrphanedAnnotations(self, eid=None, ns=None, anntype=None, addedByMe=True):
"""
Retrieve all Annotations not linked to the given Project, Dataset, Image,
Screen, Plate, Well ID controlled by the security system.
@param o_type: type of Object
@type o_type: String
@param oid: Object ID
@type oid: Long
@return: Generator yielding Tags
@rtype: L{AnnotationWrapper} generator
"""
if anntype is not None:
if anntype.title() not in ('Text', 'Tag', 'File', 'Long', 'Boolean'):
raise AttributeError('It only retrieves: Text, Tag, File, Long, Boolean')
sql = "select an from %sAnnotation as an " % anntype.title()
else:
sql = "select an from Annotation as an " \
if anntype.title() == "File":
sql += " join fetch an.file "
p = omero.sys.Parameters()
p.map = {}
filterlink = ""
if addedByMe:
userId = self._conn.getUserId()
filterlink = " and obal.details.owner.id=:linkOwner"
p.map["linkOwner"] = rlong(userId)
sql += "where not exists ( select obal from %sAnnotationLink as obal "\
"where obal.child=an.id and obal.parent.id=:oid%s)" % (self.OMERO_CLASS, filterlink)
q = self._conn.getQueryService()
p.map["oid"] = rlong(self._oid)
if ns is None:
sql += " and an.ns is null"
else:
p.map["ns"] = rlist([rstring(n) for n in ns])
sql += " and (an.ns not in (:ns) or an.ns is null)"
if eid is not None:
sql += " and an.details.owner.id=:eid"
p.map["eid"] = rlong(eid)
for e in q.findAllByQuery(sql,p,self._conn.SERVICE_OPTS):
yield AnnotationWrapper._wrap(self._conn, e)
def _linkObject (self, obj, lnkobjtype):
"""
Saves the object to DB if needed - setting the permissions manually.
Creates the object link and saves it, setting permissions manually.
TODO: Can't set permissions manually in 4.2 - Assumes world & group writable
@param obj: The object to link
@type obj: L{BlitzObjectWrapper}
"""
ctx = self._conn.SERVICE_OPTS.copy()
ctx.setOmeroGroup(self.details.group.id.val)
if not obj.getId():
# Not yet in db, save it
obj = obj.__class__(self._conn, self._conn.getUpdateService().saveAndReturnObject(obj._obj, ctx))
lnk = getattr(omero.model, lnkobjtype)()
lnk.setParent(self._obj.__class__(self._obj.id, False))
lnk.setChild(obj._obj.__class__(obj._obj.id, False))
self._conn.getUpdateService().saveObject(lnk, ctx)
return obj
def _linkAnnotation (self, ann):
"""
Saves the annotation to DB if needed - setting the permissions manually.
Creates the annotation link and saves it, setting permissions manually.
TODO: Can't set permissions manually in 4.2 - Assumes world & group writable
@param ann: The annotation object
@type ann: L{AnnotationWrapper}
"""
return self._linkObject(ann, "%sAnnotationLinkI" % self.OMERO_CLASS)
def linkAnnotation (self, ann, sameOwner=True):
"""
Link the annotation to this object.
@param ann: The Annotation object
@type ann: L{AnnotationWrapper}
@param sameOwner: If True, try to make sure that the link is created by the object owner
@type sameOwner: Boolean
@return: The annotation
@rtype: L{AnnotationWrapper}
"""
"""
My notes (will) to try and work out what's going on!
If sameOwner:
if current user is admin AND they are not the object owner,
if the object owner and annotation owner are the same:
use the Annotation connection to do the linking
else use a new connection for the object owner (?same owner as ann?)
do linking
else:
try to switch the current group of this object to the group of the annotation - do linking
else - just do linking
"""
if sameOwner:
d = self.getDetails()
ad = ann.getDetails()
if self._conn.isAdmin() and self._conn.getUserId() != d.getOwner().id:
# Keep the annotation owner the same as the linked of object's
if ad.getOwner() and d.getOwner().omeName == ad.getOwner().omeName and d.getGroup().name == ad.getGroup().name:
newConn = ann._conn
else:
#p = omero.sys.Principal()
#p.name = d.getOwner().omeName
group = None
if d.getGroup():
group = d.getGroup().name
# TODO: Do you know that the object owner is same as ann owner??
newConn = self._conn.suConn(d.getOwner().omeName, group)
#p.eventType = "User"
#newConnId = self._conn.getSessionService().createSessionWithTimeout(p, 60000)
#newConn = self._conn.clone()
#newConn.connect(sUuid=newConnId.getUuid().val)
clone = self.__class__(newConn, self._obj)
ann = clone._linkAnnotation(ann)
if newConn != self._conn:
newConn.seppuku()
elif d.getGroup():
# Try to match group
# TODO: Should switch session of this object to use group from annotation (ad) not this object (d) ?
self._conn.setGroupForSession(d.getGroup().getId())
ann = self._linkAnnotation(ann)
self._conn.revertGroupForSession()
else:
ann = self._linkAnnotation(ann)
else:
ann = self._linkAnnotation(ann)
self.unloadAnnotationLinks()
return ann
def simpleMarshal (self, xtra=None, parents=False):
"""
Creates a dict representation of this object.
E.g. for Image: {'description': '', 'author': 'Will Moore', 'date': 1286332557.0,
'type': 'Image', 'id': 3841L, 'name': 'cb_4_w500_t03_z01.tif'}
@param xtra: A dict of extra keys to include. E.g. 'childCount'
@type xtra: Dict
@param parents: If True, include a list of ancestors (in simpleMarshal form) as 'parents'
@type parents: Boolean
@return: A dict representation of this object
@rtype: Dict
"""
rv = {'type': self.OMERO_CLASS,
'id': self.getId(),
'name': self.getName(),
'description': self.getDescription(),
}
if hasattr(self, '_attrs'):
# for each of the lines in _attrs an instance variable named
# 'key' or 'title' where the line value can be:
# 'key' -> _obj[key]
# '#key' -> _obj[key].value.val
# '()key' -> _obj.getKey()
# '()#key' -> _obj.getKey().value.val
# suffix to the above we can have:
# 'key;title' - will use 'title' as the variable name, instead of 'key'
# 'key|wrapper' -> omero.gateway.wrapper(_obj[key]).simpleMarshal()
# 'key|' -> key.simpleMarshal() (useful with ()key )
for k in self._attrs:
if ';' in k:
s = k.split(';')
k = s[0]
rk = ';'.join(s[1:])
else:
rk = k
if '|' in k:
s = k.split('|')
if rk == k:
rk = s[0]
k = s[0]
wrapper = '|'.join(s[1:])
else:
wrapper = None
if k.startswith('()'):
if k == rk:
rk = k[2:]
k = k[2:]
getter = True
else:
getter = False
if k.startswith('#'):
k = k[1:]
unwrap = True
else:
unwrap = False
if getter:
v = getattr(self, 'get'+k[0].upper()+k[1:])()
else:
v = getattr(self, k)
if unwrap and v is not None:
v = v._value