-
Notifications
You must be signed in to change notification settings - Fork 3
/
ConquestService.java
executable file
·1522 lines (1252 loc) · 59.8 KB
/
ConquestService.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
/*
* This file is part of RadPlanBio
*
* Copyright (C) 2013-2022 RPB Team
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package de.dktk.dd.rpb.core.service;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import de.dktk.dd.rpb.core.DicomImageFactory;
import de.dktk.dd.rpb.core.domain.edc.ItemData;
import de.dktk.dd.rpb.core.domain.edc.StudySubject;
import de.dktk.dd.rpb.core.domain.edc.Subject;
import de.dktk.dd.rpb.core.domain.pacs.*;
import de.dktk.dd.rpb.core.service.support.PacsPatientResponseUnmashaller;
import de.dktk.dd.rpb.core.util.CallableJerseyClient;
import de.dktk.dd.rpb.core.util.Constants;
import de.dktk.dd.rpb.core.util.JsonStringUtil;
import org.apache.commons.lang.StringUtils;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Sequence;
import org.dcm4che3.data.Tag;
import org.dcm4che3.io.DicomInputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Named;
import java.awt.*;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static de.dktk.dd.rpb.core.util.Constants.*;
/**
* Conquest PACS service interface implementation
* The service provides client access to conquest specific functions and deployed lua scripts
*
* @author tomas@skripcak.net
* @since 29 Nov 2013
*/
@Transactional(readOnly = true)
@Named("pacsService")
public class ConquestService implements IConquestService {
//region Finals
private static final Logger log = LoggerFactory.getLogger(ConquestService.class);
private static final String mode = "?mode=";
private static final String wado = "?requestType=WADO";
private static final String dum = "&dum=.zip";
private static final String archiveStudy = "&study=";
private static final String archiveSeries = "&series=";
private static final String patientId = "&PatientID=";
private static final String studyUid = "&StudyUID=";
private static final String seriesUid = "&SeriesUID=";
private static final String sopUid = "&SopUID=";
private static final String seriesCount = "&SeriesCount=";
private static final String filesCount = "&FilesCount=";
private static final String aet = "&AET=";
//endregion
//region Members
private String baseUrl;
private String username;
private String password;
private int threadPoolSize;
private int structureFillTransparency = 115;
private int isoFillTransparency = 70;
private boolean forceRecalculateDvh = false;
//endregion
//region Constructors
/**
* Conquest service constructor
*/
public ConquestService() {
// NOOP
}
//endregion
//region Methods
//region Setup
/**
* {@inheritDoc}
*/
public void setupConnection(String baseUrl, int threadPoolSize) {
this.baseUrl = baseUrl;
this.threadPoolSize = threadPoolSize;
}
/**
* {@inheritDoc}
*/
public void setupConnection(String baseUrl, int threadPoolSize, String user, String password) {
this.baseUrl = baseUrl;
this.threadPoolSize = threadPoolSize;
this.username = user;
this.password = password;
}
//endregion
//region RT Treatment Case
public RtTreatmentCase loadRtTreatmentCase(String dicomPatientId, DicomStudy dicomStudy) {
RtTreatmentCase tc = new RtTreatmentCase();
if (dicomStudy != null) {
// RTSTRUCT list
List<DicomSeries> rtStructSeries = dicomStudy.getSeriesByModality("RTSTRUCT");
if (rtStructSeries != null) {
for (DicomSeries rtStructSerie : rtStructSeries) {
DicomSeries dicomSeriesWithImages = this.loadStudySeries(
dicomPatientId,
dicomStudy.getStudyInstanceUID(),
rtStructSerie.getSeriesInstanceUID()
);
if (dicomSeriesWithImages != null && dicomSeriesWithImages.getSeriesImages() != null && dicomSeriesWithImages.getSeriesImages().size() > 0) {
List<DicomRtStructureSet> structureSets = new ArrayList<>();
for (DicomImage instance : dicomSeriesWithImages.getSeriesImages()) {
structureSets.add(
this.loadDicomRtStructureSet(
dicomStudy.getStudyInstanceUID(),
rtStructSerie.getSeriesInstanceUID(),
dicomSeriesWithImages.getSeriesImages().get(0).getSopInstanceUID(),
tc
)
);
}
tc.setRtStructureSets(structureSets);
}
}
}
// RTPLAN list
List<DicomSeries> rtPlanSeries = dicomStudy.getSeriesByModality("RTPLAN");
for (DicomSeries planSerie : rtPlanSeries) {
DicomSeries dicomSeriesWithImages = this.loadStudySeries(
dicomPatientId,
dicomStudy.getStudyInstanceUID(),
planSerie.getSeriesInstanceUID()
);
if (dicomSeriesWithImages != null && dicomSeriesWithImages.getSeriesImages() != null) {
List<DicomSeriesRtPlan> plans = new ArrayList<>();
for (DicomImage instance : dicomSeriesWithImages.getSeriesImages()) {
plans.add(
this.loadDicomRtPlan(
dicomStudy.getStudyInstanceUID(),
planSerie.getSeriesInstanceUID(),
instance.getSopInstanceUID()
)
);
}
tc.setRtPlans(plans);
}
}
// RTDOSE list
List<DicomSeries> rtDoseSeries = dicomStudy.getSeriesByModality("RTDOSE");
for (DicomSeries doseSerie : rtDoseSeries) {
DicomSeries dicomSeriesWithImages = this.loadStudySeries(
dicomPatientId,
dicomStudy.getStudyInstanceUID(),
doseSerie.getSeriesInstanceUID()
);
if (dicomSeriesWithImages != null && dicomSeriesWithImages.getSeriesImages() != null) {
List<DicomSeriesRtDose> doses = new ArrayList<>();
for (DicomImage instance : dicomSeriesWithImages.getSeriesImages()) {
doses.add(
this.loadDicomRtDose(
dicomStudy.getStudyInstanceUID(),
doseSerie.getSeriesInstanceUID(),
instance.getSopInstanceUID()
)
);
}
tc.setRtDoses(doses);
}
}
}
return tc;
}
//endregion
//region DICOM Patient
/**
* {@inheritDoc}
*/
public List<Subject> loadPatient(String dicomPatientId) throws Exception {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_PATIENTS.toString() + patientId + dicomPatientId;
List<Subject> results;
ClientResponse response = queryConquest(compositeQueryUrl);
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
if (response.hasEntity()) {
String queryResultString = response.getEntity(String.class);
queryResultString = JsonStringUtil.trimJsonString(queryResultString);
results = handlePacsPatientResponse(queryResultString);
} else {
String errorMessage = "There was a problem with your request, because the response had no entity.";
String errorDetails = "Status: 200 " + "URL: " + compositeQueryUrl;
String userAdvice = "Please try again or contact your administrator";
log.error(errorMessage + " " + errorDetails);
throw new Exception(errorMessage + " " + userAdvice);
}
return results;
}
/**
* {@inheritDoc}
*/
public List<Subject> loadPatients(List<StudySubject> studySubjectList) throws Exception {
List<List<StudySubject>> listOfStudySubjectLists = splitIntoSubLists(studySubjectList);
List<Subject> loadedSubjects = new ArrayList<>();
for (List<StudySubject> studySubjectSubList : listOfStudySubjectLists) {
loadedSubjects.addAll(loadPatientsForSublist(studySubjectSubList));
}
return loadedSubjects;
}
/**
* {@inheritDoc}
*/
public boolean movePatient(String dicomPatientId, String destinationAet) {
boolean result = Boolean.FALSE;
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.MOVE_PATIENTS.toString();
if (!"".equals(dicomPatientId)) {
compositeQueryUrl += patientId + dicomPatientId;
}
if (!"".equals(destinationAet)) {
compositeQueryUrl += aet + destinationAet;
}
ClientResponse response = queryConquest(compositeQueryUrl);
if (response.getStatus() == 200) {
result = Boolean.TRUE;
}
return result;
}
//endregion
//region DICOM Studies
/**
* {@inheritDoc}
*/
public DicomStudy loadPatientStudy(String dicomPatientId, String dicomStudyUid) {
DicomStudy result = new DicomStudy();
try {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_STUDIES.toString();
compositeQueryUrl += patientId + dicomPatientId;
compositeQueryUrl += studyUid + dicomStudyUid;
ClientResponse response = queryConquest(compositeQueryUrl);
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
if (response.hasEntity()) {
JSONArray jsonStudies = getJsonEntityFromString(response, "Studies");
if (jsonStudies.length() > 0) {
JSONObject jsonStudy = jsonStudies.getJSONObject(0);
unmarshalStudyProperties(result, jsonStudy);
}
} else {
log.error("The response on the request with query: " + compositeQueryUrl + "had no entity");
log.debug(response.toString());
}
} catch (Exception err) {
String message = "Loading the DICOM series failed!\nThere appears to be a problem with the server connection.";
log.error(message, err);
}
return result;
}
/**
* {@inheritDoc}
*/
public List<DicomStudy> loadPatientStudies(String dicomPatientId) {
List<DicomStudy> resultStudies = new ArrayList<>();
try {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_STUDIES.toString();
if (!"".equals(dicomPatientId)) {
compositeQueryUrl += patientId + dicomPatientId;
}
ClientResponse response = queryConquest(compositeQueryUrl);
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
if (response.hasEntity()) {
JSONArray jsonStudies = getJsonEntityFromString(response, "Studies");
for (int i = 0; i < jsonStudies.length(); i++) {
DicomStudy study = new DicomStudy();
JSONObject jsonStudy = jsonStudies.getJSONObject(i);
unmarshalStudyProperties(study, jsonStudy);
resultStudies.add(study);
}
}
} catch (Exception err) {
String message = "Loading the DICOM series failed!\nThere appears to be a problem with the server connection.";
log.error(message, err);
}
return resultStudies;
}
/**
* {@inheritDoc}
*/
public List<DicomStudy> loadPatientStudies(String dicomPatientId, List<ItemData> dicomStudyUidList) {
List<DicomStudy> resultStudies = new ArrayList<>();
// Check if there are DICOM StudyInstanceUIDs stored in CRF items
boolean dicomStudyIsReferenced = false;
if (dicomStudyUidList != null) {
for (ItemData itemData : dicomStudyUidList) {
if (StringUtils.isNotEmpty(itemData.getValue())) {
dicomStudyIsReferenced = true;
break;
}
}
}
// If there is a patient to query and DICOM data is referenced
if (StringUtils.isNotEmpty(dicomPatientId) && dicomStudyIsReferenced) {
try {
// I have to think if PACS connection should depend on RPB study partner site or RPB user account partner site
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_STUDIES.toString() + patientId + dicomPatientId;
// If there is just one study in dicomStudyUidList load only this one (otherwise query all studies)
if (dicomStudyUidList.size() == 1) {
compositeQueryUrl += studyUid + dicomStudyUidList.get(0).getValue();
}
ClientResponse response = queryConquest(compositeQueryUrl);
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
if (response.hasEntity()) {
String jsonstring = response.getEntity(String.class);
jsonstring = JsonStringUtil.trimJsonString(jsonstring);
if (!"".equals(jsonstring)) {
JSONObject json = new JSONObject(jsonstring);
JSONArray jsonStudies = json.getJSONArray("Studies");
for (int i = 0; i < jsonStudies.length(); i++) {
JSONObject jsonStudy = jsonStudies.getJSONObject(i);
DicomStudy study = new DicomStudy();
study.setStudyInstanceUID(jsonStudy.getString("StudyInstanceUID"));
// filter to return only studies listed in parameter
boolean studyFound = false;
for (ItemData itemData : dicomStudyUidList) {
if (itemData.getValue() != null && itemData.getValue().equals(study.getStudyInstanceUID())) {
studyFound = true;
break;
}
}
if (!studyFound) {
continue;
}
study.setStudyDate(jsonStudy.optString("StudyDate"));
study.setStudyDescription(jsonStudy.optString("StudyDescription"));
JSONArray jsonSeries = jsonStudy.getJSONArray("Series");
study.setStudySeries(
this.unmarshalDicomSeries(jsonSeries)
);
resultStudies.add(study);
}
}
}
} catch (Exception err) {
String message = "Loading the DICOM series failed!\nThere appears to be a problem with the server connection.";
log.error(message, err);
}
}
return resultStudies;
}
/**
* {@inheritDoc}
*/
public void cacheDicomStudy(String dicomPatientId, String dicomStudyUid, int dicomSeriesCount) {
String url = this.baseUrl + mode + EnumConquestMode.CACHE_STUDIES.toString();
if (!"".equals(dicomPatientId)) {
url += patientId + dicomPatientId;
}
if (!"".equals(dicomStudyUid)) {
url += studyUid + dicomStudyUid;
}
url += seriesCount + dicomSeriesCount;
this.cacheDicom(url);
}
/**
* {@inheritDoc}
*/
public InputStream archivePatientStudy(String dicomPatientId, String dicomStudyUid) {
return this.archiveDicom(EnumConquestMode.ZIP_STUDY.toString(), archiveStudy, dicomPatientId, dicomStudyUid);
}
/**
* {@inheritDoc}
*/
public boolean moveDicomStudy(String dicomPatientId, String dicomStudyUid, String destinationAet) {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.MOVE_STUDIES.toString() + patientId + dicomPatientId + studyUid + dicomStudyUid + aet + destinationAet;
log.debug("Study move triggered with url " + compositeQueryUrl);
ClientResponse response = queryConquest(compositeQueryUrl);
try {
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
} catch (Exception e) {
log.error("Failed to process query: " + compositeQueryUrl);
log.debug(e.getMessage(), e);
return false;
}
return true;
}
//endregion
//region DICOM Series
/**
* {@inheritDoc}
*/
public ClientResponse loadStudySeriesResponse(String dicomPatientId, String dicomStudyUid, String dicomSeriesUid) {
ClientResponse result = null;
try {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_SERIES.toString();
if (!"".equals(dicomPatientId)) {
compositeQueryUrl += patientId + dicomPatientId;
}
if (!"".equals(dicomStudyUid)) {
compositeQueryUrl += studyUid + dicomStudyUid;
}
if (!"".equals(dicomSeriesUid)) {
compositeQueryUrl += seriesUid + dicomSeriesUid;
}
ClientResponse response = queryConquest(compositeQueryUrl);
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
if (response.hasEntity()) {
result = response;
}
} catch (Exception err) {
String message = "Loading the DICOM images failed!\nThere appears to be a problem with the server connection.";
log.error(message, err);
}
return result;
}
/**
* {@inheritDoc}
*/
public DicomSeries loadStudySeries(String dicomPatientId, String dicomStudyUid, String dicomSeriesUid) {
DicomSeries result = null;
try {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_SERIES.toString();
if (!"".equals(dicomPatientId)) {
compositeQueryUrl += patientId + dicomPatientId;
}
if (!"".equals(dicomStudyUid)) {
compositeQueryUrl += studyUid + dicomStudyUid;
}
if (!"".equals(dicomSeriesUid)) {
compositeQueryUrl += seriesUid + dicomSeriesUid;
}
ClientResponse response = queryConquest(compositeQueryUrl);
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
if (response.hasEntity()) {
JSONArray jsonSeries = getJsonEntityFromString(response, "Series");
for (int i = 0; i < jsonSeries.length(); i++) {
JSONObject jsonStudy = jsonSeries.getJSONObject(i);
result = new DicomSeries();
result.setSeriesInstanceUID(jsonStudy.getString("SeriesInstanceUID"));
result.setSeriesDescription(jsonStudy.optString("SeriesDescription"));
result.setSeriesModality(jsonStudy.optString("Modality"));
JSONArray jsonImages = jsonStudy.getJSONArray("Images");
result.setSeriesImages(
this.unmarshalDicomImages(jsonImages)
);
}
}
} catch (Exception err) {
String message = "Loading the DICOM images failed!\nThere appears to be a problem with the server connection.";
log.error(message, err);
}
return result;
}
/**
* {@inheritDoc}
*/
public void cacheDicomSeries(String dicomPatientId, String dicomStudyUid, String dicomSeriesUid, int dicomFilesCount) {
String url = this.baseUrl + mode + EnumConquestMode.CACHE_SERIES.toString();
if (!"".equals(dicomPatientId)) {
url += patientId + dicomPatientId;
}
if (!"".equals(dicomStudyUid)) {
url += studyUid + dicomStudyUid;
}
if (!"".equals(dicomSeriesUid)) {
url += seriesUid + dicomSeriesUid;
}
url += filesCount + dicomFilesCount;
this.cacheDicom(url);
}
/**
* {@inheritDoc}
*/
public InputStream archivePatientSeries(String dicomPatientId, String dicomSeriesUid) {
return this.archiveDicom(EnumConquestMode.ZIP_SERIES.toString(), archiveSeries, dicomPatientId, dicomSeriesUid);
}
/**
* {@inheritDoc}
*/
public boolean moveDicomSeries(String dicomPatientId, String dicomStudyUid, String dicomSeriesUid, String destinationAet) {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.MOVE_SERIES.toString() + patientId + dicomPatientId + studyUid + dicomStudyUid + seriesUid + dicomSeriesUid + aet + destinationAet;
log.debug("Series move triggered with url " + compositeQueryUrl);
ClientResponse response = queryConquest(compositeQueryUrl);
try {
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
} catch (Exception e) {
log.error("Failed to process query: " + compositeQueryUrl);
log.debug(e.getMessage(), e);
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean moveDicomSopInstance(String dicomPatientId, String dicomStudyUid, String dicomSeriesUid, String dicomSopInstanceId, String destinationAet) {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.MOVE_IMAGES.toString() + patientId + dicomPatientId + studyUid + dicomStudyUid + seriesUid + dicomSeriesUid + sopUid + dicomSopInstanceId + aet + destinationAet;
log.debug("SOP Instance move triggered with url " + compositeQueryUrl);
ClientResponse response = queryConquest(compositeQueryUrl);
try {
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
} catch (Exception e) {
log.error("Failed to process query: " + compositeQueryUrl);
log.debug(e.getMessage(), e);
return false;
}
return true;
}
//endregion
// region DICOM Images
public Future<String> getDicomImagesOfSeriesAsFuture(String dicomPatientId, String dicomStudyId, String dicomSeriesUid, ExecutorService service) {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_SERIES.toString();
if (!"".equals(dicomPatientId)) {
compositeQueryUrl += patientId + dicomPatientId;
}
if (!"".equals(dicomStudyId)) {
compositeQueryUrl += studyUid + dicomStudyId;
}
if (!"".equals(dicomSeriesUid)) {
compositeQueryUrl += seriesUid + dicomSeriesUid;
}
return service.submit(new CallableJerseyClient(compositeQueryUrl, this.username, this.password));
}
// endregion
//region DICOM SOP Instance
public boolean instanceExists(String dicomPatientId, String dicomStudyUid, String dicomSeriesUid, String dicomInstanceUid) {
boolean result = false;
try {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.FILE_EXISTS.toString();
if (!"".equals(dicomPatientId)) {
compositeQueryUrl += patientId + dicomPatientId;
}
if (!"".equals(dicomStudyUid)) {
compositeQueryUrl += studyUid + dicomStudyUid;
}
if (!"".equals(dicomSeriesUid)) {
compositeQueryUrl += seriesUid + dicomSeriesUid;
}
if (!"".equals(dicomInstanceUid)) {
compositeQueryUrl += sopUid + dicomSeriesUid;
}
ClientResponse response = queryConquest(compositeQueryUrl);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
} else {
result = true;
}
} catch (Exception err) {
log.error(err.getMessage(), err);
}
return result;
}
public List<DicomImage> loadStudySeriesImages(String dicomPatientId, String dicomStudyUid, String dicomSeriesUid) {
List<DicomImage> result = new ArrayList<>();
try {
String compositeQueryUrl = this.baseUrl + mode + EnumConquestMode.JSON_SERIES.toString();
if (!"".equals(dicomPatientId)) {
compositeQueryUrl += patientId + dicomPatientId;
}
if (!"".equals(dicomStudyUid)) {
compositeQueryUrl += studyUid + dicomStudyUid;
}
if (!"".equals(dicomSeriesUid)) {
compositeQueryUrl += seriesUid + dicomSeriesUid;
}
ClientResponse response = queryConquest(compositeQueryUrl);
throwIfResponseStatusIsNotTwoHundred(compositeQueryUrl, response);
if (response.hasEntity()) {
JSONArray jsonSeries = getJsonEntityFromString(response, "Series");
for (int i = 0; i < jsonSeries.length(); i++) {
JSONObject jsonStudy = jsonSeries.getJSONObject(i);
String seriesModality = jsonStudy.optString("Modality");
JSONArray jsonImages = jsonStudy.getJSONArray("Images");
try {
for (int j = 0; j < jsonImages.length(); j++) {
JSONObject jsonImage = jsonImages.getJSONObject(j);
DicomImage image = DicomImageFactory.getDicomImage(seriesModality, jsonImage);
result.add(image);
}
} catch (Exception err) {
String message = "There was a problem unmarshalling DICOM series from JSON!";
log.error(message, err);
}
}
}
} catch (Exception err) {
String message = "Loading the DICOM images failed!\nThere appears to be a problem with the server connection.";
log.error(message, err);
}
return result;
}
//endregion
//region DICOM RTSTRUCT
public DicomRtStructureSet loadDicomRtStructureSet(String studyInstanceUid, String seriesInstanceUid, String sopInstanceUid, RtTreatmentCase tc) {
DicomRtStructureSet structureSet = new DicomRtStructureSet();
// Load DICOM data
Attributes dcmAttributes = this.loadWadoDicomInstance(
studyInstanceUid,
seriesInstanceUid,
sopInstanceUid
);
// DICOM data exists
if (dcmAttributes != null) {
// Construct StructureSet object
structureSet.setLabel(dcmAttributes.getString(Tag.StructureSetLabel));
structureSet.setDate(dcmAttributes.getDate(Tag.StructureSetDateAndTime));
// Locate the name and number of each ROI
for (Attributes ssROIseq : dcmAttributes.getSequence(Tag.StructureSetROISequence)) {
DicomRtStructure structure = new DicomRtStructure();
structure.setRoiNumber(ssROIseq.getInt(Tag.ROINumber, -1));
structure.setRoiName(ssROIseq.getString(Tag.ROIName));
structureSet.put(structure.getRoiNumber(), new DicomRtStructureLayer(structure));
}
// Determine the observation type of each structure (PTV, organ, external, etc)
for (Attributes rtROIObsSeq : dcmAttributes.getSequence(Tag.RTROIObservationsSequence)) {
DicomRtStructureLayer layer = structureSet.get(rtROIObsSeq.getInt(Tag.ReferencedROINumber, -1));
if (layer != null) {
layer.getStructure().setObservationNumber(rtROIObsSeq.getInt(Tag.ObservationNumber, -1));
layer.getStructure().setRtRoiInterpretedType(rtROIObsSeq.getString(Tag.RTROIInterpretedType));
layer.getStructure().setRoiObservationLabel(rtROIObsSeq.getString(Tag.ROIObservationLabel));
}
}
// Coordinate data for each ROI
// The coordinate data of each ROI is stored within ROIContourSequence
for (Attributes roiContourSeq : dcmAttributes.getSequence(Tag.ROIContourSequence)) {
DicomRtStructureLayer layer = structureSet.get(roiContourSeq.getInt(Tag.ReferencedROINumber, -1));
if (layer == null) {
continue;
}
// Get the RGB color triplet for the current ROI if it exists
String[] valColors = roiContourSeq.getStrings(Tag.ROIDisplayColor);
int[] rgb;
if (valColors != null && valColors.length == 3) {
rgb = new int[]{Integer.parseInt(valColors[0]), Integer.parseInt(valColors[1]),
Integer.parseInt(valColors[2])};
} else {
Random rand = new Random();
rgb = new int[]{rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)};
}
Color color1 = getRGBColor(255, null, rgb);
Color color2 = new Color(color1.getRed(), color1.getGreen(), color1.getBlue(), this.structureFillTransparency);
layer.getStructure().setColor(color2);
// Contour planes
Map<Double, ArrayList<DicomRtContour>> planes = new HashMap<>();
Sequence cseq = roiContourSeq.getSequence(Tag.ContourSequence);
if (cseq != null) {
// Locate the contour sequence for each referenced ROI
for (Attributes contour : cseq) {
// For each plane, initialize a new plane dictionary
DicomRtContour plane = new DicomRtContour(layer);
// Determine all the plane properties
plane.setGeometricType(contour.getString(Tag.ContourGeometricType));
plane.setContourSlabThickness(contour.getDouble(Tag.ContourSlabThickness, -1));
plane.setContourOffsetVector(contour.getDoubles(Tag.ContourOffsetVector));
plane.setContourPoints(contour.getInt(Tag.NumberOfContourPoints, -1));
double[] points = contour.getDoubles(Tag.ContourData);
if (points != null && points.length % 3 == 0) {
plane.setPoints(points);
if (plane.getContourPoints() == -1) {
plane.setContourPoints(points.length / 3);
}
}
// Each plane which coincides with a image slice will have a unique ID
// take the first one
for (Attributes images : contour.getSequence(Tag.ContourImageSequence)) {
String sopUID = images.getString(Tag.ReferencedSOPInstanceUID);
if (sopUID != null && !sopUID.equals("")) {
ArrayList<DicomRtContour> pls;
if (tc.getContourMap() == null || tc.getContourMap().get(sopUID) == null) {
pls = new ArrayList<>();
} else {
pls = tc.getContourMap().get(sopUID);
}
pls.add(plane);
}
}
// Add each plane to the planes dictionary of the current ROI
double z = plane.getCoordinateZ();
// If there are no contour on specific z position
if (!planes.containsKey(z)) {
planes.put(z, new ArrayList<DicomRtContour>());
planes.get(z).add(plane);
}
}
}
// Calculate the plane thickness for the current ROI
layer.getStructure().setThickness(calculatePlaneThickness(planes));
// Add the planes dictionary to the current ROI
layer.getStructure().setPlanes(planes);
}
}
return structureSet;
}
//endregion
//region DICOM RTDOSE
public DicomSeriesRtDose loadDicomRtDose(String studyInstanceUid, String seriesInstanceUid, String sopInstanceUid) {
DicomSeriesRtDose rtDose = new DicomSeriesRtDose();
// Load DICOM data
Attributes dcmAttributes = this.loadWadoDicomInstance(
studyInstanceUid,
seriesInstanceUid,
sopInstanceUid
);
rtDose.setSopInstanceUid(
dcmAttributes.getString(Tag.SOPInstanceUID)
);
rtDose.setDoseUnits(
dcmAttributes.getString(Tag.DoseUnits)
);
rtDose.setDoseType(
dcmAttributes.getString(Tag.DoseType)
);
rtDose.setDoseSummationType(
dcmAttributes.getString(Tag.DoseSummationType)
);
rtDose.setDoseGridScaling(
dcmAttributes.getDouble(Tag.DoseGridScaling, 0.0)
);
// Check whether DVH is included
Sequence dvhSeq = dcmAttributes.getSequence(Tag.DVHSequence);
if (dvhSeq != null) {
List<DicomRtDvh> dvhs = new ArrayList<>();
for (Attributes dvhAttributes : dvhSeq) {
// Need to refer to delineated contour
DicomRtDvh rtDvh = null;
Sequence dvhRefRoiSeq = dvhAttributes.getSequence(Tag.DVHReferencedROISequence);
if (dvhRefRoiSeq == null) {
continue;
} else if (dvhRefRoiSeq.size() == 1) {
rtDvh = new DicomRtDvh();
Attributes dvhRefRoiAttributes = dvhRefRoiSeq.get(0);
rtDvh.setReferencedRoiNumber(
dvhRefRoiAttributes.getInt(Tag.ReferencedROINumber, -1)
);
log.debug("Found DVH for ROI: " + rtDvh.getReferencedRoiNumber());
}
if (rtDvh != null) {
// Convert Differential DVH to Cumulative
if (dvhSeq.get(0).getString(Tag.DVHType).equals("DIFFERENTIAL")) {
log.info("Not supported: converting differential DVH to cumulative");
//TODO: implement
double[] data = dvhAttributes.getDoubles(Tag.DVHData);
// dDVH = np.array(data)
// # Separate the dose and volume values into distinct arrays
// dose = data[0::2]
// volume = data[1::2]
//
// # Get the min and max dose and volume values
// mindose = int(dose[0]*100)
// maxdose = int(sum(dose)*100)
// maxvol = sum(volume)
//
// # Determine the dose values that are missing from the original data
// missingdose = np.ones(mindose) * maxvol
//
// # Generate the cumulative dose and cumulative volume data
// k = 0
// cumvol = []
// cumdose = []
// while k < len(dose):
// cumvol += [sum(volume[k:])]
// cumdose += [sum(dose[:k])]
// k += 1
//
// cumvol = np.array(cumvol)
// cumdose = np.array(cumdose)*100
//
// # Interpolate the dDVH data for 1 cGy bins
// interpdose = np.arange(mindose, maxdose+1)
// interpcumvol = np.interp(interpdose, cumdose, cumvol)
//
// # Append the interpolated values to the missing dose values
// cumDVH = np.append(missingdose, interpcumvol)
double[] cumDvhData;
//rtDvh.setDvhData(cumDvhData);
//rtDvh.setDvhNumberOfBins(cumDvhData.length);
}
// Cumulative
else {
//TODO Remove "filer" values from DVH data array (even values are DVH values) odd are filter
//dvhitem['data'] = np.array(item.DVHData[1::2])
rtDvh.setDvhData(
dvhAttributes.getDoubles(Tag.DVHData)
);
rtDvh.setDvhNumberOfBins(
dvhAttributes.getInt(Tag.DVHNumberOfBins, 0)
);
}
// Always cumulative - differential was converted
rtDvh.setType("CUMULATIVE");
rtDvh.setDoseUnit(
dvhAttributes.getString(Tag.DoseUnits)
);
rtDvh.setDoseType(
dvhAttributes.getString(Tag.DoseType)
);
rtDvh.setDvhDoseScaling(
dvhAttributes.getDouble(Tag.DVHDoseScaling, 1.0)
);
rtDvh.setDvhVolumeUnit(
dvhAttributes.getString(Tag.DVHVolumeUnits)
);