/
OMEROGateway.java
7570 lines (7150 loc) · 257 KB
/
OMEROGateway.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 (C) 2006-2015 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.env.data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import org.apache.commons.collections.CollectionUtils;
import org.openmicroscopy.shoola.util.CommonsLangUtils;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.openmicroscopy.shoola.env.data.login.UserCredentials;
import org.openmicroscopy.shoola.env.data.model.AdminObject;
import org.openmicroscopy.shoola.env.data.model.EnumerationObject;
import org.openmicroscopy.shoola.env.data.model.ImportableObject;
import org.openmicroscopy.shoola.env.data.model.MovieExportParam;
import org.openmicroscopy.shoola.env.data.model.FigureParam;
import org.openmicroscopy.shoola.env.data.model.SaveAsParam;
import org.openmicroscopy.shoola.env.data.model.ScriptObject;
import org.openmicroscopy.shoola.env.data.model.TableParameters;
import org.openmicroscopy.shoola.env.data.util.ModelMapper;
import omero.gateway.util.PojoMapper;
import org.openmicroscopy.shoola.env.data.util.SearchDataContext;
import omero.gateway.Gateway;
import omero.gateway.LoginCredentials;
import omero.gateway.SecurityContext;
import omero.gateway.exception.DSAccessException;
import omero.gateway.exception.DSOutOfServiceException;
import omero.gateway.exception.RenderingServiceException;
import omero.gateway.facility.BrowseFacility;
import omero.gateway.facility.DataManagerFacility;
import omero.gateway.facility.ROIFacility;
import omero.gateway.facility.SearchFacility;
import omero.gateway.model.ROIResult;
import omero.gateway.model.SearchResultCollection;
import omero.gateway.model.SearchParameters;
import omero.gateway.model.TableResult;
import omero.gateway.util.Requests;
import org.openmicroscopy.shoola.env.data.util.StatusLabel;
import org.openmicroscopy.shoola.env.rnd.PixelsServicesFactory;
import org.openmicroscopy.shoola.env.rnd.RndProxyDef;
import org.openmicroscopy.shoola.util.ui.UIUtilities;
import omero.ResourceError;
import ome.formats.OMEROMetadataStoreClient;
import ome.formats.importer.ImportCandidates;
import ome.formats.importer.ImportConfig;
import ome.formats.importer.ImportContainer;
import ome.formats.importer.ImportEvent;
import ome.formats.importer.ImportLibrary;
import ome.formats.importer.OMEROWrapper;
import ome.formats.importer.util.ProportionalTimeEstimatorImpl;
import ome.formats.importer.util.TimeEstimator;
import ome.system.UpgradeCheck;
import ome.util.checksum.ChecksumProvider;
import ome.util.checksum.ChecksumProviderFactory;
import ome.util.checksum.ChecksumProviderFactoryImpl;
import ome.util.checksum.ChecksumType;
import omero.ApiUsageException;
import omero.AuthenticationException;
import omero.ChecksumValidationException;
import omero.ConcurrencyException;
import omero.InternalException;
import omero.LockTimeout;
import omero.MissingPyramidException;
import omero.RLong;
import omero.RString;
import omero.RType;
import omero.SecurityViolation;
import omero.ServerError;
import omero.SessionException;
import omero.ValidationException;
import omero.rtypes;
import omero.api.ExporterPrx;
import omero.api.IAdminPrx;
import omero.api.IContainerPrx;
import omero.api.IMetadataPrx;
import omero.api.IPixelsPrx;
import omero.api.IProjectionPrx;
import omero.api.IQueryPrx;
import omero.api.IRenderingSettingsPrx;
import omero.api.IRepositoryInfoPrx;
import omero.api.IRoiPrx;
import omero.api.IScriptPrx;
import omero.api.IUpdatePrx;
import omero.api.RawFileStorePrx;
import omero.api.RawPixelsStorePrx;
import omero.api.RenderingEnginePrx;
import omero.api.RoiOptions;
import omero.api.Save;
import omero.api.SearchPrx;
import omero.api.StatefulServiceInterfacePrx;
import omero.api.ThumbnailStorePrx;
import omero.cmd.Chmod2;
import omero.cmd.CmdCallbackI;
import omero.cmd.HandlePrx;
import omero.cmd.Request;
import omero.constants.projection.ProjectionType;
import omero.grid.BoolColumn;
import omero.grid.Column;
import omero.grid.Data;
import omero.grid.DoubleColumn;
import omero.grid.ImageColumn;
import omero.grid.ImportProcessPrx;
import omero.grid.ImportRequest;
import omero.grid.LongColumn;
import omero.grid.ProcessCallbackI;
import omero.grid.RepositoryMap;
import omero.grid.RepositoryPrx;
import omero.grid.RoiColumn;
import omero.grid.SharedResourcesPrx;
import omero.grid.StringColumn;
import omero.grid.TablePrx;
import omero.grid.WellColumn;
import omero.model.ChecksumAlgorithm;
import omero.model.ChecksumAlgorithmI;
import omero.model.Dataset;
import omero.model.DatasetI;
import omero.model.Details;
import omero.model.DetailsI;
import omero.model.EllipseI;
import omero.model.Experimenter;
import omero.model.ExperimenterGroup;
import omero.model.ExperimenterGroupI;
import omero.model.FileAnnotation;
import omero.model.Fileset;
import omero.model.FilesetEntry;
import omero.model.GroupExperimenterMap;
import omero.model.IObject;
import omero.model.Image;
import omero.model.ImageI;
import omero.model.Instrument;
import omero.model.LabelI;
import omero.model.Laser;
import omero.model.LogicalChannel;
import omero.model.MaskI;
import omero.model.OriginalFile;
import omero.model.OriginalFileI;
import omero.model.Permissions;
import omero.model.PermissionsI;
import omero.model.Pixels;
import omero.model.PixelsType;
import omero.model.Plate;
import omero.model.PlateAcquisition;
import omero.model.PlateAcquisitionI;
import omero.model.PlateI;
import omero.model.PointI;
import omero.model.PolygonI;
import omero.model.PolylineI;
import omero.model.Project;
import omero.model.ProjectI;
import omero.model.RectangleI;
import omero.model.RenderingDef;
import omero.model.Screen;
import omero.model.ScreenI;
import omero.model.TagAnnotation;
import omero.model.TagAnnotationI;
import omero.model.Well;
import omero.model.WellSample;
import omero.model.WellSampleI;
import omero.model.enums.ChecksumAlgorithmSHA1160;
import omero.sys.Parameters;
import omero.sys.ParametersI;
import omero.sys.Roles;
import omero.gateway.model.AnnotationData;
import omero.gateway.model.BooleanAnnotationData;
import omero.gateway.model.ChannelAcquisitionData;
import omero.gateway.model.DataObject;
import omero.gateway.model.DatasetData;
import omero.gateway.model.EllipseData;
import omero.gateway.model.ExperimenterData;
import omero.gateway.model.FileAnnotationData;
import omero.gateway.model.FileData;
import omero.gateway.model.FilesetData;
import omero.gateway.model.GroupData;
import omero.gateway.model.ImageAcquisitionData;
import omero.gateway.model.ImageData;
import omero.gateway.model.InstrumentData;
import omero.gateway.model.LightSourceData;
import omero.gateway.model.LongAnnotationData;
import omero.gateway.model.MapAnnotationData;
import omero.gateway.model.MaskData;
import omero.gateway.model.PlateAcquisitionData;
import omero.gateway.model.PlateData;
import omero.gateway.model.PointData;
import omero.gateway.model.PolygonData;
import omero.gateway.model.PolylineData;
import omero.gateway.model.ProjectData;
import omero.gateway.model.ROIData;
import omero.gateway.model.RatingAnnotationData;
import omero.gateway.model.RectangleData;
import omero.gateway.model.ScreenData;
import omero.gateway.model.TagAnnotationData;
import omero.gateway.model.TermAnnotationData;
import omero.gateway.model.TextData;
import omero.gateway.model.TextualAnnotationData;
import omero.gateway.model.TimeAnnotationData;
import omero.gateway.model.WellData;
import omero.gateway.model.WellSampleData;
/**
* Unified access point to the various <i>OMERO</i> services.
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author <br>Andrea Falconi
* <a href="mailto:a.falconi@dundee.ac.uk">a.falconi@dundee.ac.uk</a>
* @version 2.2
* @since OME2.2
*/
@SuppressWarnings({"rawtypes", "unchecked"})
class OMEROGateway
{
/** Identifies the fileset as root. */
private static final String REF_FILESET = "/Fileset";
/** Identifies the image as root. */
private static final String REF_IMAGE = "/Image";
/** Identifies the dataset as root. */
private static final String REF_DATASET = "/Dataset";
/** Identifies the project as root. */
private static final String REF_PROJECT = "/Project";
/** Identifies the screen as root. */
private static final String REF_SCREEN = "/Screen";
/** Identifies the plate as root. */
private static final String REF_PLATE = "/Plate";
/** Identifies the ROI as root. */
private static final String REF_ROI = "/Roi";
/** Identifies the PlateAcquisition as root. */
private static final String REF_PLATE_ACQUISITION = "/PlateAcquisition";
/** Identifies the PlateAcquisition as root. */
private static final String REF_WELL = "/Well";
/** Identifies the Tag. */
private static final String REF_ANNOTATION = "/Annotation";
/** Identifies the Tag. */
private static final String REF_TAG = "/TagAnnotation";
/** Identifies the Term. */
private static final String REF_TERM = "/TermAnnotation";
/** Identifies the File. */
private static final String REF_FILE= "/FileAnnotation";
/** Identifies the group. */
private static final String REF_GROUP = "/ExperimenterGroup";
/** Indicates to keep a certain type of annotations. */
static final String KEEP = "KEEP";
/** The default MIME type. */
private static final String DEFAULT_MIMETYPE =
"application/octet-stream";
/** String used to identify the overlays. */
private static final String OVERLAYS = "Overlays";
/** Maximum size of pixels read at once. */
private static final int INC = 262144;//256000;
/**
* The maximum number of thumbnails retrieved before restarting the
* thumbnails service.
*/
static final int MAX_RETRIEVAL = 50;//100;
/** Maximum number of rows to retrieve at one time from a table. */
private static final int MAX_TABLE_ROW_RETRIEVAL = 100000;
/** The collection of escaping characters we allow in the search. */
private static final List<Character> SUPPORTED_SPECIAL_CHAR;
/** The collection of escaping characters we allow in the search. */
private static final List<String> WILD_CARDS;
/** The collection of scripts that have a UI available. */
private static final List<String> SCRIPTS_UI_AVAILABLE;
/** The collection of scripts that have a UI available. */
private static final List<String> SCRIPTS_NOT_AVAILABLE_TO_USER;
/* checksum provider factory for verifying file integrity in upload */
private static final ChecksumProviderFactory checksumProviderFactory = new ChecksumProviderFactoryImpl();
static {
SUPPORTED_SPECIAL_CHAR = new ArrayList<Character>();
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('-'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('+'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('['));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf(']'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf(')'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('('));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf(':'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('|'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('!'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('{'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('}'));
SUPPORTED_SPECIAL_CHAR.add(Character.valueOf('^'));
WILD_CARDS = new ArrayList<String>();
WILD_CARDS.add("*");
WILD_CARDS.add("?");
WILD_CARDS.add("~");
//script w/ a UI.
SCRIPTS_UI_AVAILABLE = new ArrayList<String>();
SCRIPTS_UI_AVAILABLE.add(FigureParam.ROI_SCRIPT);
SCRIPTS_UI_AVAILABLE.add(FigureParam.THUMBNAIL_SCRIPT);
SCRIPTS_UI_AVAILABLE.add(FigureParam.MOVIE_SCRIPT);
SCRIPTS_UI_AVAILABLE.add(FigureParam.SPLIT_VIEW_SCRIPT);
SCRIPTS_UI_AVAILABLE.add(MovieExportParam.MOVIE_SCRIPT);
SCRIPTS_NOT_AVAILABLE_TO_USER = new ArrayList<String>();
SCRIPTS_NOT_AVAILABLE_TO_USER.add(
ScriptObject.IMPORT_PATH+"Populate_ROI.py");
SCRIPTS_NOT_AVAILABLE_TO_USER.add(
ScriptObject.ANALYSIS_PATH+"FLIM.py");
SCRIPTS_NOT_AVAILABLE_TO_USER.add(
ScriptObject.ANALYSIS_PATH+"flim-omero.py");
SCRIPTS_NOT_AVAILABLE_TO_USER.add(
ScriptObject.SETUP_PATH+"FLIM_initialise.py");
}
/**
* Used whenever a broken link is detected to get the Login Service and
* try re-establishing a valid link to <i>OMERO</i>.
*/
private DataServicesFactory dsFactory;
/** Map hosting the enumeration required for metadata. */
private Map<String, List<EnumerationObject>> enumerations;
/** Keep track of the file system view. */
private Map<Long, FSFileSystemView> fsViews;
private Gateway gw;
/**
* Creates the query to load the file set corresponding to a given image.
*
* @return See above.
*/
private String createFileSetQuery()
{
StringBuffer buffer = new StringBuffer();
buffer.append("select fs from Fileset as fs ");
buffer.append("join fetch fs.images as image ");
buffer.append("left outer join fetch fs.usedFiles as usedFile ");
buffer.append("join fetch usedFile.originalFile as f ");
buffer.append("join fetch f.hasher ");
buffer.append("where image.id in (:imageIds)");
return buffer.toString();
}
/**
* Logs the information.
*/
private void log(String msg)
{
dsFactory.getLogger().debug(this, msg);
}
/**
* Returns <code>true</code> if the server is running.
*
* @param ctx The security context.
* @return See above.
*/
boolean isServerRunning(SecurityContext ctx)
{
if (!gw.isConnected())
return false;
try {
return null != gw.getConnector(ctx, true, true);
} catch (Throwable t) {
return false;
}
}
/**
* Creates the permissions corresponding to the specified level.
*
* @param level The level to handle.
* @return
*/
private Permissions createPermissions(int level)
{
String perms = "rw----"; //private group
switch (level) {
case GroupData.PERMISSIONS_GROUP_READ:
perms = "rwr---";
break;
case GroupData.PERMISSIONS_GROUP_READ_LINK:
perms = "rwra--";
break;
case GroupData.PERMISSIONS_GROUP_READ_WRITE:
perms = "rwrw--";
break;
case GroupData.PERMISSIONS_PUBLIC_READ:
perms = "rwrwr-";
}
return new PermissionsI(perms);
}
/**
* Returns the identifier of the specified script.
*
* @param ctx The security context.
* @param name The name of the script.
* @param message The error message.
* @return See above.
* @throws DSOutOfServiceException If the connection is broken, or logged
* in.
* @throws DSAccessException If an error occurred while trying to
* retrieve data from OMEDS service.
*/
private long getScriptID(SecurityContext ctx, String name, String message)
throws DSOutOfServiceException, DSAccessException
{
IScriptPrx svc = getScriptService(ctx);
try {
return svc.getScriptID(name);
} catch (Exception e) {
handleException(e, message);
}
return -1;
}
/**
* Returns the specified script.
*
* @param ctx The security context.
* @param scriptID The identifier of the script to run.
* @param parameters The parameters to pass to the script.
* @return See above.
* @throws ProcessException If an error occurred while running the script.
*/
private ScriptCallback runScript(SecurityContext ctx, long scriptID,
Map<String, RType> parameters)
throws ProcessException
{
ScriptCallback cb = null;
try {
ProcessCallbackI pcb = gw.runScript(ctx, scriptID, parameters);
cb = new ScriptCallback(scriptID, pcb);
} catch (Exception e) {
handleConnectionException(e);
throw new ProcessException("Cannot run script with ID:"+scriptID,
e);
}
return cb;
}
/**
* Closes the specified service.
*
* @param ctx The security context.
* @param svc The service to close.
*/
void closeService(SecurityContext ctx,
StatefulServiceInterfacePrx svc)
{
if (ctx == null || svc == null) return;
gw.closeService(ctx, svc);
}
/**
* Creates a table with the overlays.
*
* @param imageID The id of the image.
* @param table The table to handle.
* @return See above
* @throws DSAccessException If an error occurred while trying to
* retrieve data from OMEDS service.
*/
private TableResult createOverlay(long imageID, TablePrx table)
throws DSAccessException
{
if (table == null) return null;
try {
Column[] cols = table.getHeaders();
int imageIndex = -1;
int roiIndex = -1;
int colorIndex = -1;
int size = 0;
for (int i = 0; i < cols.length; i++) {
if (cols[i] instanceof ImageColumn) {
imageIndex = i;
size++;
} else if (cols[i] instanceof RoiColumn) {
roiIndex = i;
size++;
} else if (cols[i] instanceof LongColumn) {
if ("Color".equals(cols[i].name)) {
colorIndex = i;
size++;
}
}
}
if (imageIndex == -1 || roiIndex == -1) return null;;
String[] headers = new String[size];
String[] headersDescriptions = new String[size];
headers[0] = cols[imageIndex].name;
headersDescriptions[0] = cols[imageIndex].description;
headers[1] = cols[roiIndex].name;
headersDescriptions[1] = cols[roiIndex].description;
headers[1] = cols[roiIndex].name;
headersDescriptions[1] = cols[roiIndex].description;
int n = (int) table.getNumberOfRows();
Data d;
Column column;
long[] a = {imageIndex, roiIndex, colorIndex};
long[] b = new long[0];
d = table.slice(a, b);
List<Integer> rows = new ArrayList<Integer>();
column = d.columns[imageIndex];
Long value;
if (column instanceof ImageColumn) {
for (int j = 0; j < n; j++) {
value = ((ImageColumn) column).values[j];
if (value == imageID)
rows.add(j);
}
}
Integer row;
Object[][] data = new Object[rows.size()][size];
int k = 0;
Iterator<Integer> r = rows.iterator();
column = d.columns[roiIndex];
Column columnColor = null;
if (colorIndex != -1) columnColor = d.columns[colorIndex];
while (r.hasNext()) {
row = r.next();
data[k][0] = row;
data[k][1] = ((RoiColumn) column).values[row];
if (columnColor != null)
data[k][2] = ((LongColumn) columnColor).values[row];
k++;
}
table.close();
return new TableResult(data, headers);
} catch (Exception e) {
try {
if (table != null) table.close();
} catch (Exception ex) {
//Digest exception
}
throw new DSAccessException("Unable to read the table.");
}
}
/**
* Translates a set of table results into an array.
* @param src Source data from the table.
* @param dst Destination array.
* @param offset Offset within the destination array from which to copy
* data into.
* @param length Number of rows of data to be copied.
*/
private void translateTableResult(Data src, Object[][] dst, int offset,
int length, Map<Integer, Integer> indexes)
{
Column[] cols = src.columns;
Column column;
for (int i = 0; i < cols.length; i++) {
column = cols[i];
if (column instanceof LongColumn) {
for (int j = 0; j < length; j++) {
dst[j + offset][i] =
((LongColumn) column).values[j];
}
} else if (column instanceof DoubleColumn) {
for (int j = 0; j < length; j++) {
dst[j + offset][i] =
((DoubleColumn) column).values[j];
}
} else if (column instanceof StringColumn) {
for (int j = 0; j < length; j++) {
dst[j + offset][i] =
((StringColumn) column).values[j];
}
} else if (column instanceof BoolColumn) {
for (int j = 0; j < length; j++) {
dst[j + offset][i] =
((BoolColumn) column).values[j];
}
} else if (column instanceof RoiColumn) {
indexes.put(TableResult.ROI_COLUMN_INDEX, i);
for (int j = 0; j < length; j++) {
dst[j + offset][i] =
((RoiColumn) column).values[j];
}
} else if (column instanceof ImageColumn) {
indexes.put(TableResult.IMAGE_COLUMN_INDEX, i);
for (int j = 0; j < length; j++) {
dst[j + offset][i] =
((ImageColumn) column).values[j];
}
} else if (column instanceof WellColumn) {
indexes.put(TableResult.WELL_COLUMN_INDEX, i);
for (int j = 0; j < length; j++) {
dst[j + offset][i] =
((WellColumn) column).values[j];
}
}
}
}
/**
* Transforms a set of rows for the passed table.
*
* @param table The table to convert.
* @param rows The rows of the table to convert.
* @return See above
* @throws DSAccessException If an error occurred while trying to
* retrieve data from OMEDS service.
*/
private TableResult createTableResult(TablePrx table, long[] rows)
throws DSAccessException
{
if (table == null) return null;
try {
Column[] cols = table.getHeaders();
String[] headers = new String[cols.length];
String[] headersDescriptions = new String[cols.length];
for (int i = 0; i < cols.length; i++) {
headers[i] = cols[i].name;
headersDescriptions[i] = cols[i].description;
}
int totalRowCount = rows.length;
Object[][] data = new Object[totalRowCount][cols.length];
Data d;
long[] columns = new long[cols.length];
for (int i = 0; i < cols.length; i++) {
columns[i] = i;
}
int rowOffset = 0;
int rowCount = 0;
int rowsToGo = totalRowCount;
long[] rowSubset;
Map<Integer, Integer> indexes = new HashMap<Integer, Integer>();
while (rowsToGo > 0) {
rowCount = (int) Math.min(MAX_TABLE_ROW_RETRIEVAL,
totalRowCount - rowOffset);
rowSubset = new long[rowCount];
System.arraycopy(rows, rowOffset, rowSubset, 0, rowCount);
d = table.slice(columns, rowSubset);
for (int i = 0; i < cols.length; i++) {
translateTableResult(d, data, rowOffset, rowCount, indexes);
}
rowOffset += rowCount;
rowsToGo -= rowCount;
}
table.close();
TableResult tr = new TableResult(data, headers);
tr.setIndexes(indexes);
return tr;
} catch (Exception e) {
try {
if (table != null) table.close();
} catch (Exception ex) {
//Digest exception
}
throw new DSAccessException("Unable to read the table.", e);
}
}
/**
* Helper method to handle exceptions thrown by the connection library.
* Methods in this class are required to fill in a meaningful context
* message.
* This method is not supposed to be used in this class' constructor or in
* the login/logout methods.
*
* @param t The exception.
* @param message The context message.
* @throws DSOutOfServiceException A connection problem.
* @throws DSAccessException A server-side error.
*/
private void handleException(Throwable t, String message)
throws DSOutOfServiceException, DSAccessException
{
boolean b = handleConnectionException(t);
if (!b) return;
if (!gw.isConnected()) return;
Throwable cause = t.getCause();
if (cause instanceof SecurityViolation) {
String s = "For security reasons, cannot access data. \n";
throw new DSAccessException(s+message, cause);
} else if (cause instanceof SessionException) {
String s = "Session is not valid. \n";
throw new DSOutOfServiceException(s+message, cause);
} else if (cause instanceof AuthenticationException) {
String s = "Cannot initialize the session. \n";
throw new DSOutOfServiceException(s+message, cause);
} else if (cause instanceof ResourceError) {
String s = "Fatal error. Please contact the administrator. \n";
throw new DSOutOfServiceException(s+message, t);
}
throw new DSAccessException("Cannot access data. \n"+message, t);
}
/**
* Helper method to handle exceptions thrown by the connection library.
* Depending on the specified exception, the user will be asked to
* reconnect or to exit the application.
*
* @param e The exception to handle.
* @return <code>true</code> to continue handling the error,
* <code>false</code> otherwise.
*/
boolean handleConnectionException(Throwable e)
{
ConnectionExceptionHandler handler = new ConnectionExceptionHandler();
int index = handler.handleConnectionException(e);
if (index < 0) return true;
dsFactory.sessionExpiredExit(index, e);
return false;
}
/**
* Helper method to handle exceptions thrown by the connection library.
* Methods in this class are required to fill in a meaningful context
* message.
* This method is not supposed to be used in this class' constructor or in
* the login/logout methods.
*
* @param t The exception.
* @param message The context message.
* @throws FSAccessException A server-side error.
*/
private void handleFSException(Throwable t, String message)
throws FSAccessException
{
boolean b = handleConnectionException(t);
if (!b) return;
if (!gw.isConnected()) return;
Throwable cause = t.getCause();
String s = "\nImage not ready. Please try again later.";
if (cause instanceof ConcurrencyException) {
ConcurrencyException mpe = (ConcurrencyException) cause;
//s += ", ready in approximately ";
//s += UIUtilities.calculateHMSFromMilliseconds(mpe.backOff);
FSAccessException fsa = new FSAccessException(message+s, cause);
if (mpe instanceof MissingPyramidException ||
mpe instanceof LockTimeout)
fsa.setIndex(FSAccessException.PYRAMID);
fsa.setBackOffTime(mpe.backOff);
throw fsa;
} else if (t instanceof ConcurrencyException) {
ConcurrencyException mpe = (ConcurrencyException) t;
s += UIUtilities.calculateHMSFromMilliseconds(mpe.backOff);
FSAccessException fsa = new FSAccessException(message+s, t);
if (mpe instanceof MissingPyramidException ||
mpe instanceof LockTimeout)
fsa.setIndex(FSAccessException.PYRAMID);
fsa.setBackOffTime(mpe.backOff);
throw fsa;
}
}
/**
* Utility method to print the error message
*
* @param e The exception to handle.
* @return See above.
*/
private String printErrorText(Throwable e)
{
return UIUtilities.printErrorText(e);
}
/**
* Handles the result of the search.
*
* @param type The supported type.
* @param r The collection to fill.
* @param svc Helper reference to the service.
* @return See above.
* @throws ServerError If an error occurs while reading the results.
*/
private Object handleSearchResult(String type, Collection r, SearchPrx svc)
throws ServerError
{
//First get object of a given type.
boolean hasNext = false;
try {
hasNext = svc.hasNext();
} catch (Exception e) {
int size = 0;
if (e instanceof InternalException) size = -1;
else svc.getBatchSize();
return Integer.valueOf(size);
}
if (!hasNext) return r;
List l = svc.results();
Iterator k = l.iterator();
IObject object;
long id;
while (k.hasNext()) {
object = (IObject) k.next();
if (type.equals(object.getClass().getName())) {
id = object.getId().getValue();
if (!r.contains(id))
r.add(id); //Retrieve the object of a given type.
}
}
return r;
}
/**
* Formats the elements of the passed array. Adds the
* passed field in front of each term.
*
* @param terms The terms to format.
* @param field The string to add in front of the terms.
* @return See above.
*/
private List<String> formatText(List<String> terms, String field)
{
if (CollectionUtils.isEmpty(terms)) return null;
if (CommonsLangUtils.isBlank(field)) return terms;
List<String> formatted = new ArrayList<String>(terms.size());
Iterator<String> j = terms.iterator();
while (j.hasNext())
formatted.add(field+":"+j.next());
return formatted;
}
/**
* Formats the elements of the passed array. Adds the
* passed field in front of each term.
* @param terms The terms to format.
* @param firstField The string to add in front of the terms.
* @param sep Separator used to join, exclude etc.
* @param secondField The string to add in front of the terms.
* @return See above.
*/
private List<String> formatText(List<String> terms, String firstField,
String sep, String secondField)
{
if (CollectionUtils.isEmpty(terms)) return null;
List<String> formatted = new ArrayList<String>(terms.size());
String value;
Iterator<String> j = terms.iterator();
String v;
while (j.hasNext()) {
v = j.next();
value = firstField+":"+v+" "+sep+" "+secondField+":"+v;
formatted.add(value);
}
return formatted;
}
/**
* Determines the table name corresponding to the specified class.
*
* @param klass The class to analyze.
* @return See above.
*/
private String getTableForLink(Class klass)
{
String table = null;
if (Dataset.class.equals(klass)) table = "DatasetImageLink";
else if (DatasetI.class.equals(klass)) table = "DatasetImageLink";
else if (Project.class.equals(klass)) table = "ProjectDatasetLink";
else if (ProjectI.class.equals(klass)) table = "ProjectDatasetLink";
else if (Screen.class.equals(klass)) table = "ScreenPlateLink";
else if (ScreenI.class.equals(klass)) table = "ScreenPlateLink";
else if (PlateAcquisition.class.equals(klass))
table = "PlateAcquisitionWellSampleLink";
else if (PlateAcquisitionI.class.equals(klass))
table = "PlateAcquisitionWellSampleLink";
else if (TagAnnotation.class.equals(klass))
table = "AnnotationAnnotationLink";
else if (TagAnnotationI.class.equals(klass))
table = "AnnotationAnnotationLink";
return table;
}
/**
* Determines the table name corresponding to the specified class.
*
* @param klass The class to analyze.
* @return See above.
*/
private String getAnnotationTableLink(Class klass)
{
String table = null;
if (Dataset.class.equals(klass) ||
DatasetI.class.equals(klass) ||
DatasetData.class.equals(klass))
table = "DatasetAnnotationLink";
else if (Project.class.equals(klass) ||
ProjectI.class.equals(klass) ||
ProjectData.class.equals(klass))
table = "ProjectAnnotationLink";
else if (Image.class.equals(klass) ||
ImageI.class.equals(klass) ||
ImageData.class.equals(klass))
table = "ImageAnnotationLink";
else if (Screen.class.equals(klass) ||
ScreenI.class.equals(klass) ||
ScreenData.class.equals(klass))
table = "ScreenAnnotationLink";
else if (Plate.class.equals(klass) ||
PlateI.class.equals(klass) ||
PlateData.class.equals(klass))
table = "PlateAnnotationLink";
else if (PlateAcquisition.class.equals(klass) ||
PlateAcquisitionI.class.equals(klass) ||
PlateAcquisitionData.class.equals(klass))
table = "PlateAcquisitionAnnotationLink";
else if (WellSample.class.equals(klass) ||
WellSampleI.class.equals(klass) ||
WellSampleData.class.equals(klass))
table = "ScreenAnnotationLink";
else if (RectangleData.class.equals(klass) || RectangleI.class.equals(klass) ||
EllipseData.class.equals(klass) || EllipseI.class.equals(klass) ||
PointData.class.equals(klass) || PointI.class.equals(klass) ||
PolygonData.class.equals(klass) || PolygonI.class.equals(klass) ||
PolylineData.class.equals(klass) || PolylineI.class.equals(klass) ||
TextData.class.equals(klass) || LabelI.class.equals(klass) ||
MaskData.class.equals(klass) || MaskI.class.equals(klass)) {
table = "ShapeAnnotationLink";
} else if (ROIData.class.equals(klass)) {
table = "RoiAnnotationLink";
}
else table = "AnnotationAnnotationLink";
return table;
}
/**
* Determines the table name corresponding to the specified class.
*
* @param klass The class to analyze.
* @return See above.
*/