/
IceMapper.java
1480 lines (1284 loc) · 50.2 KB
/
IceMapper.java
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
/*
* Copyright 2007-2014 Glencoe Software, Inc. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package omero.util;
import static omero.rtypes.rbool;
import static omero.rtypes.rclass;
import static omero.rtypes.rdouble;
import static omero.rtypes.rfloat;
import static omero.rtypes.rint;
import static omero.rtypes.rinternal;
import static omero.rtypes.rlist;
import static omero.rtypes.rlong;
import static omero.rtypes.rmap;
import static omero.rtypes.robject;
import static omero.rtypes.rstring;
import static omero.rtypes.rtime;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ome.conditions.InternalException;
import ome.model.IObject;
import ome.model.ModelBased;
import ome.model.enums.AdminPrivilege;
import ome.services.blitz.util.ConvertToBlitzExceptionMessage;
import ome.system.OmeroContext;
import ome.system.Principal;
import ome.system.Roles;
import ome.util.Filterable;
import ome.util.ModelMapper;
import ome.util.ReverseModelMapper;
import ome.util.Utils;
import omeis.providers.re.RGBBuffer;
import omeis.providers.re.codomain.CodomainMapContext;
import omeis.providers.re.codomain.ReverseIntensityContext;
import omeis.providers.re.data.PlaneDef;
import omeis.providers.re.data.RegionDef;
import omero.ApiUsageException;
import omero.RString;
import omero.RTime;
import omero.RType;
import omero.ServerError;
import omero.rtypes.Conversion;
import omero.model.NamedValue;
import omero.model.PermissionsI;
import omero.romio.BlueBand;
import omero.romio.GreenBand;
import omero.romio.PlaneDefWithMasks;
import omero.romio.RedBand;
import omero.romio.XY;
import omero.romio.XZ;
import omero.romio.ZY;
import omero.sys.EventContext;
import omero.sys.Filter;
import omero.sys.Options;
import omero.sys.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import Ice.UserException;
/**
* Responsible for the mapping of ome.* types to omero.* types and back again.
* Not all types are bidirectional, rather only those mappings are needed that
* actually appear in the blitz API.
*
* As of Beta3.1, an {@link IceMapper} instance can also be configured to handle
* return value mapping, though by default an exception will be thrown if
* {@link #mapReturnValue(Object)} is called.
*/
public class IceMapper extends ome.util.ModelMapper implements
ReverseModelMapper {
private static Logger log = LoggerFactory.getLogger(IceMapper.class);
// Return value mapping
// =========================================================================
private final ReturnMapping mapping;
public IceMapper() {
this.mapping = null;
}
public IceMapper(ReturnMapping mapping) {
this.mapping = mapping;
}
public interface ReturnMapping {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException;
}
public final static ReturnMapping VOID = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws UserException {
if (value != null) {
throw new IllegalArgumentException("Method is void");
}
return null;
}
};
public final static ReturnMapping FILTERABLE = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws UserException {
return mapper.map((Filterable) value);
}
};
public final static ReturnMapping FILTERABLE_ARRAY = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws UserException {
Filterable[] array = (Filterable[]) value;
if (array == null) {
return null;
} else {
List rv = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
rv.add(mapper.map(array[i]));
}
return rv;
}
}
};
public final static ReturnMapping FILTERABLE_COLLECTION = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws UserException {
Collection<Filterable> coll = (Collection<Filterable>) value;
if (coll == null) {
return null;
} else {
List rv = new ArrayList();
for (Filterable f : coll) {
rv.add(mapper.map(f));
}
return rv;
}
}
};
public final static ReturnMapping OBJECTARRAY_TO_RTYPESEQ = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
if (value == null) {
return null;
}
Object[] objArr = (Object[]) value;
List<RType> rv = new ArrayList<RType>();
for (Object obj : objArr) {
rv.add((RType) OBJECT_TO_RTYPE.mapReturnValue(mapper, obj));
}
return rv;
}
};
@SuppressWarnings("unchecked")
public final static ReturnMapping LISTOBJECTARRAY_TO_RTYPESEQSEQ = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
if (value == null) {
return null;
}
List<Object[]> listObjArr = (List<Object[]>) value;
List<List<RType>> rv = new ArrayList<List<RType>>();
for (Object[] objs : listObjArr) {
rv.add((List<RType>)OBJECTARRAY_TO_RTYPESEQ.mapReturnValue(mapper, objs));
}
return rv;
}
};
public final static ReturnMapping OBJECT_TO_RTYPE = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
return mapper.toRType(value);
}
};
public final static ReturnMapping STRING_TO_RSTRING = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
String str = (String) value;
return omero.rtypes.rstring(str);
}
};
/**
* Specifies a return type which should not be parsed. This should
* only be used for objects unknown to the Mapper, and should <em>not</em>
* be used for any types which contain by transitivity any ome.model.* types!
*/
public final static ReturnMapping UNMAPPED = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
return value;
}
};
public final static ReturnMapping PRIMITIVE = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
if (value == null) {
return null;
} else {
if (!IceMapper.isNullablePrimitive(value.getClass())) {
throw new RuntimeException(
"Object not nullable primitive: " + value);
}
return value;
}
}
};
public final static ReturnMapping PRIMITIVE_MAP = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
if (value == null) {
return null;
} else {
Map map = (Map) value;
Map rv = new HashMap();
for (Object k : map.keySet()) {
Object v = map.get(k);
Object kr = PRIMITIVE.mapReturnValue(mapper, k);
Object vr = PRIMITIVE.mapReturnValue(mapper, v);
rv.put(kr, vr);
}
return rv;
}
}
};
public final static ReturnMapping FILTERABLE_PRIMITIVE_MAP = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
if (value == null) {
return null;
} else {
Map map = (Map) value;
Map rv = new HashMap();
for (Object k : map.keySet()) {
Object v = map.get(k);
Object kr = FILTERABLE.mapReturnValue(mapper, k);
Object vr = PRIMITIVE.mapReturnValue(mapper, v);
rv.put(kr, vr);
}
return rv;
}
}
};
public final static ReturnMapping PRIMITIVE_FILTERABLE_COLLECTION_MAP = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
if (value == null) {
return null;
} else {
Map map = (Map) value;
Map rv = new HashMap();
for (Object k : map.keySet()) {
Object v = map.get(k);
Object kr = PRIMITIVE.mapReturnValue(mapper, k);
Object vr = FILTERABLE_COLLECTION.mapReturnValue(mapper, v);
rv.put(kr, vr);
}
return rv;
}
}
};
public final static ReturnMapping RTYPEDICT = new ReturnMapping() {
public Object mapReturnValue(IceMapper mapper, Object value)
throws Ice.UserException {
if (value == null) {
return null;
} else {
Map map = (Map) value;
Map rv = new HashMap();
for (Object k : map.keySet()) {
Object v = map.get(k);
Object kr = PRIMITIVE.mapReturnValue(mapper, k);
Object vr = OBJECT_TO_RTYPE.mapReturnValue(mapper, v);
rv.put(kr, vr);
}
return rv;
}
}
};
/**
* Returns true only if the current mapping is the {@link #VOID} mapping.
*/
public boolean isVoid() {
return canMapReturnValue() && mapping == VOID;
}
/**
* True if this instance has a {@link ReturnMapping}
*/
public boolean canMapReturnValue() {
return mapping != null;
}
/**
* Convert the given Object via the set {@link ReturnMapping}. Throws a
* {@link NullPointerException} if no mapping is set.
*/
public Object mapReturnValue(Object value) throws Ice.UserException {
return mapping.mapReturnValue(this, value);
}
// Exception handling
// =========================================================================
public static ServerError fillServerError(ServerError se, Throwable t) {
se.message = t.getMessage();
se.serverExceptionClass = t.getClass().getName();
se.serverStackTrace = stackAsString(t);
return se;
}
// Classes
// =========================================================================
private static Class<? extends IObject> _class(String className) {
Class k = null;
try {
k = Class.forName(className);
} catch (Exception e) {
// ok
}
return k;
}
public static Class<? extends IObject> omeroClass(String className,
boolean strict) throws ApiUsageException {
Class k = _class(className);
// If that didn't work, try to prefix with "omero.model"
if (k == null) {
k = _class("omero.model." + className);
}
// If either of those attempts worked, map it with IceMap unless
// it's already in the key of OMEtoOMERO
if (k != null) {
if (IceMap.OMEtoOMERO.containsKey(k)) {
// good
} else {
k = IceMap.OMEROtoOME.get(k);
}
}
// For whatever reason, it's not valid. Log it.
if (k == null) {
if (log.isDebugEnabled()) {
log.debug(className + " does not specify a valid class.");
}
}
if (k == null && strict) {
ApiUsageException aue = new ApiUsageException();
aue.message = className + " does not specify a valid class.";
throw aue;
}
// Return, even null.
return k;
}
// Conversions
// =========================================================================
public RType toRType(Object o) throws omero.ApiUsageException {
if (o == null) {
return null;
} else if (o instanceof RType) {
return (RType) o;
} else if (o instanceof Boolean) {
Boolean b = (Boolean) o;
omero.RBool bool = rbool(b.booleanValue());
return bool;
} else if (o instanceof Class) {
Class c = (Class) o;
omero.RClass rc = rclass(c.getName());
return rc;
} else if (o instanceof Date) {
Date date = (Date) o;
omero.RTime time = rtime(date.getTime());
return time;
} else if (o instanceof Integer) {
Integer i = (Integer) o;
omero.RInt rint = rint(i);
return rint;
} else if (o instanceof Long) {
Long lng = (Long) o;
omero.RLong rlng = rlong(lng.longValue());
return rlng;
} else if (o instanceof Float) {
Float flt = (Float) o;
omero.RFloat rflt = rfloat(flt);
return rflt;
} else if (o instanceof Double) {
Double dbl = (Double) o;
omero.RDouble rdbl = rdouble(dbl.doubleValue());
return rdbl;
} else if (o instanceof String) {
String str = (String) o;
omero.RString rstr = rstring(str);
return rstr;
} else if (o instanceof ome.util.PermDetails) {
// Implements IObject as well!
ome.util.PermDetails p = (ome.util.PermDetails) o;
return toRType(p.getDetails().getPermissions());
} else if (o instanceof IObject) {
IObject obj = (IObject) o;
omero.model.IObject om = (omero.model.IObject) map(obj);
omero.RObject robj = robject(om);
return robj;
} else if (o instanceof Collection) {
List<RType> l = new ArrayList<RType>();
for (Object i : (Collection) o) {
l.add(toRType(i));
}
return rlist(l);
} else if (o instanceof Map) {
Map<?, ?> mIn = (Map) o;
Map<String, RType> mOut = new HashMap<String, RType>();
for (Object k : mIn.keySet()) {
if (!(k instanceof String)) {
throw new omero.ValidationException(
null, null, "Map key not a string");
}
mOut.put((String) k, toRType(mIn.get(k)));
}
return rmap(mOut);
} else if (o instanceof omero.Internal) {
return rinternal((omero.Internal) o);
} else if (o instanceof ome.model.internal.Permissions) {
ome.model.internal.Permissions p = (ome.model.internal.Permissions) o;
Map<String, RType> rv = new HashMap<String, RType>();
rv.put("perm", rstring(p.toString()));
rv.put("canAnnotate", rbool(!p.isDisallowAnnotate()));
rv.put("canDelete", rbool(!p.isDisallowDelete()));
rv.put("canEdit", rbool(!p.isDisallowEdit()));
rv.put("canLink", rbool(!p.isDisallowLink()));
rv.put("canChgrp", rbool(!p.isDisallowChgrp()));
rv.put("canChown", rbool(!p.isDisallowChown()));
return rmap(rv);
} else if (o instanceof ome.model.units.Unit) {
ome.model.units.Unit u = (ome.model.units.Unit) o;
Map<String, RType> rv = new HashMap<String, RType>();
rv.put("value", rdouble(u.getValue()));
rv.put("unit", rstring(u.getUnit().toString()));
rv.put("symbol", rstring(u.getUnit().getSymbol()));
return rmap(rv);
} else if (o instanceof ome.model.units.UnitEnum) {
return rstring(((ome.model.units.UnitEnum) o).toString());
} else {
throw new ApiUsageException(null, null,
"Unsupported conversion to rtype from " + o.getClass().getName() + ":" + o);
}
}
/**
* Uses the omero.rtypes hierarchy to properly convert any {@link RType} to
* its internal representation. This requires that the instance properly
* implement {@link omero.rtypes.Conversion} otherwise ApiUsageException
* will be thrown.
*
* @param rt the wrapped value
* @return the value unwrapped
* @throws omero.ApiUsageException if the given value is not wrapped
*/
public Object fromRType(RType rt) throws omero.ApiUsageException {
if (rt == null) {
return null;
}
if (rt instanceof omero.rtypes.Conversion) {
omero.rtypes.Conversion conv = (omero.rtypes.Conversion) rt;
return conv.convert(this);
} else {
omero.ApiUsageException aue = new omero.ApiUsageException();
aue.message = rt.getClass() + " is not a conversion type";
throw aue;
}
}
public static EventContext convert(ome.system.EventContext ctx) {
if (ctx == null) {
return null;
}
EventContext ec = new EventContext();
Long event = ctx.getCurrentEventId();
ec.eventId = event == null ? -1 : event;
Long shareId = ctx.getCurrentShareId();
ec.shareId = shareId == null ? -1 : shareId;
ec.sessionId = ctx.getCurrentSessionId();
ec.sessionUuid = ctx.getCurrentSessionUuid();
ec.eventType = ctx.getCurrentEventType();
ec.groupId = ctx.getCurrentGroupId();
ec.groupName = ctx.getCurrentGroupName();
ec.userId = ctx.getCurrentUserId();
ec.userName = ctx.getCurrentUserName();
ec.sudoerId = ctx.getCurrentSudoerId() == null ? null : rlong(ctx.getCurrentSudoerId());
ec.sudoerName = ctx.getCurrentSudoerName() == null ? null : rstring(ctx.getCurrentSudoerName());
ec.leaderOfGroups = ctx.getLeaderOfGroupsList();
ec.memberOfGroups = ctx.getMemberOfGroupsList();
ec.isAdmin = ctx.isCurrentUserAdmin();
ec.adminPrivileges = new ArrayList<>(ctx.getCurrentAdminPrivileges().size());
for (final AdminPrivilege privilege : ctx.getCurrentAdminPrivileges()) {
ec.adminPrivileges.add(privilege.getValue());
}
// ticket:2265 Removing from public interface
// ec.isReadOnly = ctx.isReadOnly();
ec.groupPermissions = convert(ctx.getCurrentGroupPermissions());
return ec;
}
public static omero.romio.RGBBuffer convert(RGBBuffer buffer) {
omero.romio.RGBBuffer b = new omero.romio.RGBBuffer();
b.bands = new byte[3][];
b.bands[RedBand.value] = buffer.getRedBand();
b.bands[GreenBand.value] = buffer.getGreenBand();
b.bands[BlueBand.value] = buffer.getBlueBand();
b.sizeX1 = buffer.getSizeX1();
b.sizeX2 = buffer.getSizeX2();
return b;
}
/**
* Converts the passed Ice Object and returns the converted object.
*
* @param ctx The object to convert
* @return See above.
* @throws omero.ApiUsageException Thrown if the slice is unknown.
*/
public CodomainMapContext convert(omero.romio.CodomainMapContext ctx)
{
if (!(ctx instanceof omero.romio.ReverseIntensityMapContext)) {
return null;
}
return new ReverseIntensityContext();
}
/**
* Converts the passed Ice Object and returns the converted object.
*
* @param def The object to convert
* @return See above.
* @throws omero.ApiUsageException Thrown if the slice is unknown.
*/
public static PlaneDef convert(omero.romio.PlaneDef def)
throws omero.ApiUsageException {
if (def == null) {
return null;
}
PlaneDef pd = new PlaneDef(def.slice, def.t);
pd.setStride(def.stride);
omero.romio.RegionDef r = def.region;
if (r != null) {
pd.setRegion(new RegionDef(r.x, r.y, r.width, r.height));
}
if (def instanceof PlaneDefWithMasks) {
pd.setRenderShapes(true);
if (((PlaneDefWithMasks) def).shapeIds != null) {
pd.setShapeIds(((PlaneDefWithMasks) def).shapeIds);
}
}
switch (def.slice) {
case XY.value:
pd.setZ(def.z);
break;
case ZY.value:
pd.setX(def.x);
break;
case XZ.value:
pd.setY(def.y);
break;
default:
omero.ApiUsageException aue = new omero.ApiUsageException();
aue.message = "Unknown slice for " + def;
throw aue;
}
return pd;
}
public static Principal convert(omero.sys.Principal old) {
if (old == null) {
return null;
}
return new Principal(old.name, old.group, old.eventType);
}
public static omero.sys.Roles convert(Roles roles) {
omero.sys.Roles r = new omero.sys.Roles();
r.rootId = roles.getRootId();
r.rootName = roles.getRootName();
r.systemGroupId = roles.getSystemGroupId();
r.systemGroupName = roles.getSystemGroupName();
r.userGroupId = roles.getUserGroupId();
r.userGroupName = roles.getUserGroupName();
r.guestId = roles.getGuestId();
r.guestName = roles.getGuestName();
r.guestGroupId = roles.getGuestGroupId();
r.guestGroupName = roles.getGuestGroupName();
return r;
}
public static RTime convert(Date date) {
return rtime(date);
}
public static Timestamp convert(RTime time) {
if (time == null) {
return null;
}
return new Timestamp(time.getValue());
}
public ome.parameters.Parameters convert(Parameters params)
throws ApiUsageException {
if (params == null) {
return null;
}
ome.parameters.Parameters p = new ome.parameters.Parameters();
if (params.map != null) {
for (String name : params.map.keySet()) {
Object obj = params.map.get(name);
p.add(convert(name, obj));
}
}
if (params.theFilter != null) {
p.setFilter(convert(params.theFilter));
}
if (params.theOptions != null) {
p.setOptions(convert(params.theOptions));
}
return p;
}
public ome.parameters.QueryParameter convert(String key, Object o)
throws ApiUsageException {
if (o == null) {
return null;
}
String name = key;
Class klass = o.getClass();
Object value = null;
if (RType.class.isAssignableFrom(klass)) {
value = fromRType((RType) o);
// If fromRType passes correctly, then we're sure that we
// can convert to rtypes.Conversion
klass = ((Conversion) o).type();
} else {
omero.ApiUsageException aue = new omero.ApiUsageException();
aue.message = "Query parameter must be a subclass of RType " + o;
throw aue;
}
ome.parameters.QueryParameter qp = new ome.parameters.QueryParameter(
name, klass, value);
return qp;
}
public static ome.parameters.Options convert(Options o) {
if (o == null) {
return null;
}
ome.parameters.Options options = new ome.parameters.Options();
if (o.orphan != null) {
options.orphan = o.orphan.getValue();
}
if (o.leaves != null) {
options.leaves= o.leaves.getValue();
}
if (o.cacheable != null) {
options.cacheable = o.cacheable.getValue();
}
if (o.acquisitionData != null) {
options.acquisitionData = o.acquisitionData.getValue();
}
return options;
}
public static ome.parameters.Filter convert(Filter f) {
if (f == null) {
return null;
}
ome.parameters.Filter filter = new ome.parameters.Filter();
if (f.offset != null) {
filter.offset = f.offset.getValue();
}
if (f.limit != null) {
filter.limit = f.limit.getValue();
}
if (f.ownerId != null) {
filter.owner(f.ownerId.getValue());
}
if (f.groupId != null) {
filter.group(f.groupId.getValue());
}
if (f.startTime != null) {
filter.startTime = convert(f.startTime);
}
if (f.endTime != null) {
filter.endTime = convert(f.endTime);
}
if (f.unique != null && f.unique.getValue()) {
filter.unique();
}
return filter;
}
public static List<NamedValue> convertNamedValueList(List<ome.model.internal.NamedValue> map) {
if (map == null) {
return null;
}
final List<NamedValue> nvl = new ArrayList<NamedValue>(map.size());
for (final ome.model.internal.NamedValue nv : map) {
if (nv == null) {
nvl.add(null);
} else {
final String name = nv.getName();
final String value = nv.getValue();
nvl.add(new NamedValue(name, value));
}
}
return nvl;
}
public static List<NamedValue> convertMapPairs(List<ome.xml.model.MapPair> map) {
if (map == null) {
return null;
}
final List<NamedValue> nvl = new ArrayList<NamedValue>(map.size());
for (final ome.xml.model.MapPair nv : map) {
if (nv == null) {
nvl.add(null);
} else {
final String name = nv.getName();
final String value = nv.getValue();
nvl.add(new NamedValue(name, value));
}
}
return nvl;
}
/**
* Convert a String→String map's values to {@link RString}s.
* <code>null</code> values are dropped completely.
* @param map a map
* @return the converted map, or <code>null</code> if <code>map == null</code>
*/
public static Map<String, RString> convertStringStringMap(Map<String, String> map) {
if (map == null) {
return null;
}
final Map<String, RString> rMap = new HashMap<String, RString>(map.size());
for (final Map.Entry<String, String> mapEntry : map.entrySet()) {
final String key = mapEntry.getKey();
final String value = mapEntry.getValue();
if (value != null) {
rMap.put(key, rstring(value));
}
}
return rMap;
}
/**
* Overrides the findCollection logic of {@link ModelMapper}, since all
* {@link Collection}s should be {@link List}s in Ice.
*/
@Override
public Collection findCollection(Collection source) {
if (source == null) {
return null;
}
Collection target = (Collection) model2target.get(source);
if (null == target) {
target = new ArrayList();
model2target.put(source, target);
}
return target;
}
public List map(Filterable[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return new ArrayList();
} else {
List l = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
l.add(map(array[i]));
}
return l;
}
}
// ~ For Reversing (omero->ome). Copied from ReverseModelMapper.
// =========================================================================
protected Map<Object, Object> target2model = new IdentityHashMap<Object, Object>();
public static omero.model.Permissions convert(ome.model.internal.Permissions p) {
if (p == null) {
return null;
}
return new PermissionsI(p.toString());
}
public static ome.model.internal.Permissions convert(omero.model.Permissions p) {
if (p == null) {
return null;
}
return Utils.toPermissions(p.getPerm1());
}
// TODO copied with ModelMapper
public boolean isImmutable(Object obj) {
if (null == obj || obj instanceof Number || obj instanceof Number[]
|| obj instanceof String || obj instanceof String[]
|| obj instanceof Boolean || obj instanceof Boolean[]) {
return true;
}
return false;
}
public Object reverse(Object source) throws ApiUsageException {
if (source == null) {
return null;
} else if (Collection.class.isAssignableFrom(source.getClass())) {
return reverse((Collection) source);
} else if (ModelBased.class.isAssignableFrom(source.getClass())) {
return reverse((ModelBased) source);
} else if (isImmutable(source)) {
return source;
} else if (RType.class.isAssignableFrom(source.getClass())) {
return fromRType((RType) source);
} else {
omero.ApiUsageException aue = new omero.ApiUsageException();
aue.message = "Don't know how to reverse " + source;
throw aue;
}
}
/**
* Copied from {@link ModelMapper#findCollection(Collection)} This could be
* unified in that a method findCollection(Collection, Map) was added with
* {@link ModelMapper} calling {@code findCollection(source, model2target)}
* and {@code reverseCollection(Collection)} calling
* {@code findCollection(source,target2model)}.
*
* @param source the wrapped {@link Collection}
* @return the {@link Collection} unwrapped
*/
public Collection reverse(Collection source) { // FIXME throws
// omero.ApiUsageException {
return reverse(source, source == null ? null : source.getClass());
}
/**
* Creates a collection assignable to the given type. Currently only
* {@link Set} and {@link List} are supported, and {@link HashSet}s and
* {@link ArrayList}s will be returned. The need for this arose from the
* decision to have no {@link Set}s in the Ice Java mapping.
*
* @see <a href="https://trac.openmicroscopy.org/ome/ticket/684">Trac ticket #684</a>
*/
public Collection reverse(Collection source, Class targetType) { // FIXME
// throws
// omero.ApiUsageException
// {
if (source == null) {
return null;
}
Collection target = (Collection) target2model.get(source);
if (null == target) {
if (Set.class.isAssignableFrom(targetType)) {
target = new HashSet();
} else if (List.class.isAssignableFrom(targetType)) {
target = new ArrayList();
} else {
// omero.ApiUsageException aue = new omero.ApiUsageException();
// aue.message = "Unknown collection type "+targetType;
// throw aue;
throw new InternalException("Unknown collection type "
+ targetType);
}
target2model.put(source, target);
try {
for (Object object : source) {
target.add(reverse(object));
}
} catch (ApiUsageException aue) { // FIXME reverse can't throw
// ServerErrors!
convertAndThrow(aue);
}
}
return target;
}
/**
* Supports the separate case of reversing for arrays. See
* {@link #reverse(Collection, Class)} and {@link #map(Filterable[])}.
*/
public Object[] reverseArray(List list, Class type)
throws omero.ServerError {
if (list == null) {
return null;
}
Class component = type.getComponentType();
Object[] array = null;
try {
array = (Object[]) Array.newInstance(component, list.size());
for (int i = 0; i < array.length; i++) {
array[i] = this.handleInput(component, list.get(i));
}
} catch (Exception e) {
String msg = "Cannot create array from type " + type;
if (log.isErrorEnabled()) {
log.error(msg, e);
}
omero.ApiUsageException aue = new omero.ApiUsageException();