/
StudyServiceBean.java
2596 lines (2132 loc) · 106 KB
/
StudyServiceBean.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) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
/*
* StudyServiceBean.java
*
* Created on August 14, 2006, 11:47 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.iq.dvn.core.study;
import edu.harvard.iq.dvn.core.admin.RoleServiceLocal;
import edu.harvard.iq.dvn.core.admin.UserServiceLocal;
import edu.harvard.iq.dvn.core.admin.VDCRole;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.ddi.DDIServiceLocal;
import edu.harvard.iq.dvn.core.gnrs.GNRSServiceLocal;
import edu.harvard.iq.dvn.core.harvest.HarvestFormatType;
import edu.harvard.iq.dvn.core.harvest.HarvestStudyServiceLocal;
import edu.harvard.iq.dvn.core.index.IndexServiceLocal;
import edu.harvard.iq.dvn.core.mail.MailServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyVersion.VersionState;
import edu.harvard.iq.dvn.core.util.FileUtil;
import edu.harvard.iq.dvn.core.util.StringUtil;
import edu.harvard.iq.dvn.core.util.TwitterUtil;
import edu.harvard.iq.dvn.core.vdc.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
/**
*
* @author Ellen Kraffmiller
*/
@Stateless
public class StudyServiceBean implements edu.harvard.iq.dvn.core.study.StudyServiceLocal, java.io.Serializable {
@PersistenceContext(unitName = "VDCNet-ejbPU")
EntityManager em;
@Resource(mappedName = "jms/DSBIngest")
Queue queue;
@Resource(mappedName = "jms/DSBQueueConnectionFactory")
QueueConnectionFactory factory;
@EJB
GNRSServiceLocal gnrsService;
@EJB
VDCNetworkServiceLocal vdcNetworkService;
@EJB
DDIServiceLocal ddiService;
@EJB
UserServiceLocal userService;
@EJB
IndexServiceLocal indexService;
@EJB
VariableServiceLocal variableService;
@EJB
StudyExporterFactoryLocal studyExporterFactory;
@EJB
MailServiceLocal mailService;
private static final Logger logger = Logger.getLogger("edu.harvard.iq.dvn.core.study.StudyServiceBean");
private static final SimpleDateFormat exportLogFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
@EJB
StudyServiceLocal studyService; // used to force new transaction during import
@EJB
HarvestStudyServiceLocal harvestStudyService;
@EJB
VDCServiceLocal vdcService;
@EJB
StudyFileServiceLocal studyFileService;
@EJB
RoleServiceLocal roleService;
@EJB
GuestBookResponseServiceBean guestBookResponseServiceBean;
/**
* Creates a new instance of StudyServiceBean
*/
public StudyServiceBean() {
}
public void updateStudy(Study detachedStudy) {
em.merge(detachedStudy);
}
public void updateStudyVersion(StudyVersion studyVersion) {
em.merge(studyVersion);
}
public void setReadyForReview(Long studyId) {
setReadyForReview(studyId, null);
}
public void setReadyForReview(Long studyId, String versionNote) {
Study study = em.find(Study.class, studyId);
StudyVersion sv = study.getLatestVersion();
setReadyForReview(sv, versionNote);
}
public void setReadyForReview(StudyVersion sv) {
setReadyForReview(sv, null);
}
public void setReadyForReview(StudyVersion sv, String versionNote) {
sv.setVersionState(StudyVersion.VersionState.IN_REVIEW);
if (versionNote != null) {
sv.setVersionNote(versionNote);
}
Study study = sv.getStudy();
VDCUser user = study.getCreator();
// If the user adding the study is a Contributor, send notification to all Curators in this VDC
// and send an email to the Contributor about the status of the study
if (user.getVDCRole(study.getOwner()) != null && user.getVDCRole(study.getOwner()).getRole().getName().equals(RoleServiceLocal.CONTRIBUTOR)) {
mailService.sendStudyInReviewNotification(user.getEmail(), sv.getMetadata().getTitle());
// Notify all curators and admins that study is in review
for (Iterator it = study.getOwner().getVdcRoles().iterator(); it.hasNext();) {
VDCRole elem = (VDCRole) it.next();
if (elem.getRole().getName().equals(RoleServiceLocal.CURATOR) || elem.getRole().getName().equals(RoleServiceLocal.ADMIN)) {
mailService.sendStudyAddedCuratorNotification(elem.getVdcUser().getEmail(), user.getUserName(), sv.getMetadata().getTitle(), study.getOwner().getName());
}
}
}
}
public void saveVersionNote(Long studyId, Long versionNumber, String newVersionNote) {
Study study = em.find(Study.class, studyId);
StudyVersion sv = null;
if ( study != null ) {
if (versionNumber != null) {
sv = study.getStudyVersionByNumber(versionNumber);
} else {
sv = study.getLatestVersion();
}
if ( sv != null ) {
sv.setVersionNote(newVersionNote);
}
}
}
public void saveVersionNote(Long studyVersionId, String newVersionNote) {
StudyVersion sv = em.find(StudyVersion.class, studyVersionId);
if ( sv != null ) {
sv.setVersionNote(newVersionNote);
}
}
public void setReleased(Long studyId) {
setReleased(studyId, null);
}
public void setReleased(Long studyId, String versionNote) {
Study study = em.find(Study.class, studyId);
StudyVersion latestVersion = study.getLatestVersion();
if (!latestVersion.isWorkingCopy()) {
throw new EJBException("Cannot release latestVersion, incorrect state: "+latestVersion.getVersionState());
}
Date releaseDate = new Date();
// Archive the previously released or deaccessioned version
StudyVersion releasedVersion = study.getReleasedVersion();
if (releasedVersion!=null) {
releasedVersion.setVersionState(StudyVersion.VersionState.ARCHIVED);
releasedVersion.setArchiveTime(releaseDate);
releasedVersion.setArchiveNote("Replaced by version " + latestVersion.getVersionNumber());
} else {
StudyVersion deaccessionedVersion = study.getDeaccessionedVersion();
if (deaccessionedVersion!=null) {
deaccessionedVersion.setVersionState(StudyVersion.VersionState.ARCHIVED);
}
}
latestVersion.setVersionState(StudyVersion.VersionState.RELEASED);
latestVersion.setReleaseTime(releaseDate);
if (versionNote != null) {
latestVersion.setVersionNote(versionNote);
}
VDCRole studyCreatorRole = study.getCreator().getVDCRole(study.getOwner());
if (studyCreatorRole != null && studyCreatorRole.getRole().getName().equals(RoleServiceLocal.CONTRIBUTOR)) {
mailService.sendStudyReleasedNotification(study.getCreator().getEmail(), latestVersion.getMetadata().getTitle(), study.getOwner().getName());
}
// tweet release of study
TwitterCredentials tc = study.getOwner().getTwitterCredentials();
if (tc != null) {
String message = latestVersion.getVersionNumber() == 1 ? "New study released: " : "Study updated: ";
message += latestVersion.getMetadata().getTitle();
URL url = new GlobalId(latestVersion.getStudy().getProtocol(),latestVersion.getStudy().getAuthority(),latestVersion.getStudy().getStudyId()).toURL();
TwitterUtil.tweet(tc, message, url);
}
// finally, re-index the study metadata:
indexService.updateStudy(studyId);
}
public void deaccessionStudy(StudyVersion sv) {
sv.setVersionState(StudyVersion.VersionState.DEACCESSIONED);
sv.setArchiveTime(new Date());
em.merge(sv);
indexService.deleteStudy(sv.getStudy().getId());
}
public Study getStudyByHarvestInfo(VDC dataverse, String harvestIdentifier) {
String queryStr = "SELECT s FROM Study s WHERE s.owner.id = '" + dataverse.getId() + "' and s.harvestIdentifier = '" + harvestIdentifier + "'";
Query query = em.createQuery(queryStr);
List resultList = query.getResultList();
Study study = null;
if (resultList.size() > 1) {
throw new EJBException("More than one study found with owner_id= " + dataverse.getId() + " and harvestIdentifier= " + harvestIdentifier);
}
if (resultList.size() == 1) {
study = (Study) resultList.get(0);
}
return study;
}
public void deleteStudy(Long studyId) {
deleteStudy(studyId, true);
}
public void deleteStudyList(List<Long> studyIds) {
indexService.deleteIndexList(studyIds);
for (Long studyId : studyIds) {
studyService.deleteStudyInNewTransaction(studyId, false);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void deleteStudyInNewTransaction(Long studyId, boolean deleteFromIndex) {
deleteStudy(studyId, deleteFromIndex);
}
public void deleteStudy(Long studyId, boolean deleteFromIndex) {
long start = new Date().getTime();
//System.out.println("DEBUG: 0\t - deleteStudy - BEGIN");
Study study = em.find(Study.class, studyId);
if (study == null) {
return;
}
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - remove from collections");
for (Iterator<VDCCollection> it = study.getStudyColls().iterator(); it.hasNext();) {
VDCCollection elem = it.next();
elem.getStudies().remove(study);
}
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - delete data variables");
studyService.deleteDataVariables(study.getId());
//force cascade delete of
deleteGuestBookResponses(study.getId());
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - delete relationships");
study.getAllowedGroups().clear();
study.getAllowedUsers().clear();
for (Iterator<StudyFile> it = study.getStudyFiles().iterator(); it.hasNext();) {
StudyFile elem = it.next();
elem.getAllowedGroups().clear();
elem.getAllowedUsers().clear();
elem.clearData();
}
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - delete physical files");
File studyDir = new File(FileUtil.getStudyFileDir() + File.separator + study.getAuthority() + File.separator + study.getStudyId());
if (studyDir.exists()) {
File[] files = studyDir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
studyDir.delete();
}
// remove from HarvestStudy table
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - delete from HarvestStudy");
harvestStudyService.markHarvestStudiesAsRemoved( harvestStudyService.findHarvestStudiesByGlobalId( study.getGlobalId() ), new Date() );
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - delete from DB and gnrs");
em.remove(study);
gnrsService.delete(study.getAuthority(), study.getStudyId());
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - delete from Index");
if (deleteFromIndex) {
indexService.deleteStudy(studyId);
}
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - right before flush");
em.flush(); // Force study deletion to the database, for cases when we are calling this before deleting the owning Dataverse
//System.out.println("DEBUG: " + (new Date().getTime() - start) + "\t - deleteStudy - FINISH");
logger.log(Level.INFO, "Successfully deleted Study " + studyId + "!");
}
public void destroyWorkingCopyVersion(Long studyVersionId) {
long start = new Date().getTime();
StudyVersion studyVersion = em.find(StudyVersion.class, studyVersionId);
if (studyVersion == null) {
return;
}
// We need to determine if there are already released versions of this
// study. If so, we can destroy this version and leave the older versions
// and the study intact. However, if this working version is the first
// version of the study, we have to destroy the study as well -- otherwise
// we'll have that version-less study shell left behind, which can mess up
// ManageStudies page and possibly other partds of the system.
Long studyId = null;
if (studyVersion.getStudy() != null) {
studyId = studyVersion.getStudy().getId();
}
if (studyId != null) {
if (getStudyVersion(studyId, null) == null) {
deleteStudy(studyId, true);
} else {
// We need to make sure to delete all the Study Files that would
// otherwise become "orphans" -- meaning, the files that were
// only added in this working version, that are not part of
// the released version of the study.
//
// I'm going to simply retrieve the lists of file metadata
// for both versions, ordered by file Id, and delete the "tail"
// of the working version list.
StudyVersion releasedVersion = getStudyVersion(studyId, null);
List<FileMetadata> fileMetadataList = new ArrayList<FileMetadata>();
List<FileMetadata> fileMetadataListReleased = new ArrayList<FileMetadata>();
fileMetadataList = studyFileService.getFilesByStudyVersionOrderedById(studyVersion.getId());
fileMetadataListReleased = studyFileService.getFilesByStudyVersionOrderedById(releasedVersion.getId());
int i = fileMetadataList.size();
if ( i > 0 ) {
FileMetadata fm1 = fileMetadataList.get(i-1);
Long lastReleasedStudyFileId = new Long (0);
if (fileMetadataListReleased.size() > 0) {
lastReleasedStudyFileId = fileMetadataListReleased.get(fileMetadataListReleased.size()-1).getStudyFile().getId();
}
while ( i > 0 &&
fm1 != null &&
fm1.getStudyFile().getId().compareTo(lastReleasedStudyFileId) > 0 ) {
StudyFile studyFile = fm1.getStudyFile();
String fileSystemLocation = studyFile.getFileSystemLocation();
if ( fileSystemLocation != null ) {
File fileToDelete = new File (fileSystemLocation);
// For subsettable files, also remove the preserved
// originals and cached format conversions:
if (studyFile.isSubsettable()) {
if (fileToDelete != null) {
// original:
File originalDataFile = new File(fileToDelete.getParent(), "_" + studyFile.getFileSystemName());
if (originalDataFile != null) {
originalDataFile.delete();
}
// cached alternative formats (including .RData file
// that we create for Network Data files):
File fileDir = new File (fileToDelete.getParent());
File[] formatConvertedFiles =
fileDir.listFiles(
new ConvertedFilenamesFilter(
studyFile.getFileSystemName()));
for (int j = 0; j < formatConvertedFiles.length; j++) {
formatConvertedFiles[j].delete();
}
}
}
// End of subsettable file special case;
// For image files, we may have thumbnail files
// cached on disk as well:
if (studyFile.getFileType().substring(0, 6).equalsIgnoreCase("image/")) {
File imageThumbnailFile = new File(fileSystemLocation + ".thumb");
if (imageThumbnailFile != null) {
imageThumbnailFile.delete();
}
}
// End of image file special case.
// And now delete the file itself:
if (fileToDelete != null) {
fileToDelete.delete();
}
}
i--;
if (i > 0) {
fm1 = fileMetadataList.get(i-1);
}
}
}
em.remove(studyVersion);
em.flush(); // Force deletion to the database, for cases when we are calling this before deleting the owning Dataverse
logger.log(Level.INFO, "Successfully deleted StudyVersion " + studyVersionId + "!");
}
}
}
/* these delete queires seem to take too long, so we are currently trying testing something different for deleting variables
private static final String DELETE_VARIABLE_CATEGORIES = " delete from variablecategory where datavariable_id in ( " +
"select dv.id from study s, filecategory fc, studyfile sf, datatable dt, datavariable dv" +
" where s.id= ? " +
" and s.id = fc.study_id " +
" and fc.id= sf.filecategory_id " +
" and sf.id=dt.studyfile_id " +
" and dt.id= dv.datatable_id )";
private static final String DELETE_SUMMARY_STATISTICS = " delete from summarystatistic where datavariable_id in ( " +
"select dv.id from study s, filecategory fc, studyfile sf, datatable dt, datavariable dv" +
" where s.id= ? " +
" and s.id = fc.study_id " +
" and fc.id= sf.filecategory_id " +
" and sf.id=dt.studyfile_id " +
" and dt.id= dv.datatable_id )";
private static final String DELETE_VARIABLE_RANGE_ITEMS = " delete from variablerangeitem where datavariable_id in ( " +
"select dv.id from study s, filecategory fc, studyfile sf, datatable dt, datavariable dv" +
" where s.id= ? " +
" and s.id = fc.study_id " +
" and fc.id= sf.filecategory_id " +
" and sf.id=dt.studyfile_id " +
" and dt.id= dv.datatable_id )";
private static final String DELETE_VARIABLE_RANGES = " delete from variablerange where datavariable_id in ( " +
"select dv.id from study s, filecategory fc, studyfile sf, datatable dt, datavariable dv" +
" where s.id= ? " +
" and s.id = fc.study_id " +
" and fc.id= sf.filecategory_id " +
" and sf.id=dt.studyfile_id " +
" and dt.id= dv.datatable_id )";
private static final String DELETE_DATA_VARIABLES = " delete from datavariable where id in ( " +
"select dv.id from study s, filecategory fc, studyfile sf, datatable dt, datavariable dv" +
" where s.id= ? " +
" and s.id = fc.study_id " +
" and fc.id= sf.filecategory_id " +
" and sf.id=dt.studyfile_id " +
" and dt.id= dv.datatable_id )";
private static final String SELECT_DATAVARIABLE_IDS = "select dv.id from study s, filecategory fc, studyfile sf, datatable dt, datavariable dv" +
" where s.id= ? " +
" and s.id = fc.study_id " +
" and fc.id= sf.filecategory_id " +
" and sf.id=dt.studyfile_id " +
" and dt.id= dv.datatable_id ";
*/
private static final String DELETE_VARIABLE_CATEGORIES_PREFIX = "delete from variablecategory where datavariable_id in ";
private static final String DELETE_SUMMARY_STATISTICS_PREFIX = " delete from summarystatistic where datavariable_id in ";
private static final String DELETE_VARIABLE_RANGE_ITEMS_PREFIX = " delete from variablerangeitem where datavariable_id in ";
private static final String DELETE_VARIABLE_RANGES_PREFIX = "delete from variablerange where datavariable_id in ";
private static final String DELETE_DATA_VARIABLES_PREFIX = "delete from datavariable where id in ";
private static final String DELETE_DATA_VARIABLE_MAPPINGS_PREFIX = "delete from datavariablemapping where datavariable_id in ";
private static final String SELECT_DATATABLE_IDS = "select dt.id from study s, studyfile sf, datatable dt " +
"where s.id= ? " +
"and s.id = sf.study_id " +
"and sf.id=dt.studyfile_id ";
private static final String SELECT_DATAVARIABLE_IDS_PREFIX = "select dv.id from datavariable dv where dv.datatable_id in ";
public void deleteDataVariables(Long studyId) {
// because the delte was taking a while, we tested spearate queires to get the info and it seemed to work much
// faster, so now this delete goes in steps
// step 1: determine dtIds
List dtIdList = new ArrayList();
Query query = em.createNativeQuery(SELECT_DATATABLE_IDS).setParameter(1, studyId);
for (Object currentResult : query.getResultList()) {
dtIdList.add(new Long(((Integer)currentResult).longValue()));
}
if ( !dtIdList.isEmpty() ) {
// step 2: determine variables
List varList = new ArrayList();
query = em.createNativeQuery(SELECT_DATAVARIABLE_IDS_PREFIX + "(" + generateTempTableString(dtIdList) + ")");
for (Object currentResult : query.getResultList()) {
varList.add(new Long(((Integer)currentResult).longValue()));
}
if ( !varList.isEmpty() ) {
// step 3: delete!
String varString = "(" + generateTempTableString(varList) + ")";
em.createNativeQuery(DELETE_VARIABLE_CATEGORIES_PREFIX + varString).executeUpdate();
em.createNativeQuery(DELETE_SUMMARY_STATISTICS_PREFIX + varString).executeUpdate();
em.createNativeQuery(DELETE_VARIABLE_RANGE_ITEMS_PREFIX + varString).executeUpdate();
em.createNativeQuery(DELETE_VARIABLE_RANGES_PREFIX + varString).executeUpdate();
em.createNativeQuery(DELETE_DATA_VARIABLE_MAPPINGS_PREFIX + varString).executeUpdate();
em.createNativeQuery(DELETE_DATA_VARIABLES_PREFIX + varString).executeUpdate();
}
}
//em.createNativeQuery(DELETE_VARIABLE_CATEGORIES).setParameter(1, studyId).executeUpdate();
//em.createNativeQuery(DELETE_SUMMARY_STATISTICS).setParameter(1, studyId).executeUpdate();
//em.createNativeQuery(DELETE_VARIABLE_RANGE_ITEMS).setParameter(1, studyId).executeUpdate();
//em.createNativeQuery(DELETE_VARIABLE_RANGES).setParameter(1, studyId).executeUpdate();
//em.createNativeQuery(DELETE_DATA_VARIABLES).setParameter(1, studyId).executeUpdate();
}
private static final String DELETE_CUSTOMQUESTIONRESPONSE_PREFIX = "delete from customquestionresponse where guestbookresponse_id in ";
private static final String DELETE_GUESTBOOKRESPONSE_PREFIX = "delete from guestbookresponse where id in ";
private static final String SELECT_GUESTBOOK_RESPONSE_IDS = "select gbr.id from study s, guestbookresponse gbr " +
"where s.id= ? " +
"and s.id = gbr.study_id " ;
public void deleteGuestBookResponses(Long studyId) {
// because the delte was taking a while, we tested spearate queires to get the info and it seemed to work much
// faster, so now this delete goes in steps
// step 1: determine dtIds
List gbrIdList = new ArrayList();
Query query = em.createNativeQuery(SELECT_GUESTBOOK_RESPONSE_IDS).setParameter(1, studyId);
for (Object currentResult : query.getResultList()) {
gbrIdList.add(new Long(((Integer)currentResult).longValue()));
}
if ( !gbrIdList.isEmpty() ) {
// step 2: determine variables
String varString = "(" + generateTempTableString(gbrIdList) + ")";
em.createNativeQuery(DELETE_CUSTOMQUESTIONRESPONSE_PREFIX + varString).executeUpdate();
em.createNativeQuery(DELETE_GUESTBOOKRESPONSE_PREFIX + varString).executeUpdate();
}
}
/**
* Gets Study without any of its dependent objects
*
*/
public Study getStudy(Long studyId) {
Study study = em.find(Study.class, studyId);
if (study == null) {
throw new IllegalArgumentException("Unknown studyId: " + studyId);
}
return study;
}
/**
* Gets Study and dependent objects based on Map parameter;
* Should only be used for studies with Released versions
* used by studyListingPage
*
*/
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Study getStudyForSearch(Long studyId, Map studyFields) {
Study study = em.find(Study.class, studyId);
if (study == null) {
throw new IllegalArgumentException("Unknown studyId: " + studyId);
}
Metadata metadata = null;
if (study.getReleasedVersion() != null) {
metadata = study.getReleasedVersion().getMetadata();
} else {
throw new IllegalArgumentException("No released version available for this study: " + studyId);
}
if (studyFields != null) {
for (Object studyField : studyFields.keySet()) {
String fieldName = (String) studyField;
if ("authorName".equals(fieldName)) {
for (Iterator<StudyAuthor> it = metadata.getStudyAuthors().iterator(); it.hasNext();) {
StudyAuthor elem = it.next();
elem.getId();
}
} else if ("abstractText".equals(fieldName)) {
for (Iterator<StudyAbstract> it = metadata.getStudyAbstracts().iterator(); it.hasNext();) {
StudyAbstract elem = it.next();
elem.getId();
}
} else if ("producerName".equals(fieldName)) {
for (Iterator<StudyProducer> it = metadata.getStudyProducers().iterator(); it.hasNext();) {
StudyProducer elem = it.next();
elem.getId();
}
} else if ("distributorName".equals(fieldName)) {
for (Iterator<StudyDistributor> it = metadata.getStudyDistributors().iterator(); it.hasNext();) {
StudyDistributor elem = it.next();
elem.getId();
}
} else if ("relatedStudies".equals(fieldName)) {
for (Iterator<StudyRelStudy> it = metadata.getStudyRelStudies().iterator(); it.hasNext();) {
StudyRelStudy elem = it.next();
elem.getId();
}
} else if ("relatedMaterial".equals(fieldName)) {
for (Iterator<StudyRelMaterial> it = metadata.getStudyRelMaterials().iterator(); it.hasNext();) {
StudyRelMaterial elem = it.next();
elem.getId();
}
} else if ("relatedPublications".equals(fieldName)) {
for (Iterator<StudyRelPublication> it = metadata.getStudyRelPublications().iterator(); it.hasNext();) {
StudyRelPublication elem = it.next();
elem.getId();
}
}
}
}
return study;
}
public List getStudies() {
String query = "SELECT s FROM Study s ORDER BY s.id";
return (List) em.createQuery(query).getResultList();
}
public List getStudiesByIdRange(long begin, long end) {
String query = "SELECT s FROM Study s WHERE s.id > " + begin + " AND s.id < " + end + " ORDER BY s.id";
logger.info("query: "+query);
try {
return (List) em.createQuery(query).getResultList();
} catch (Exception ex) {
return null;
}
}
public List getRecentStudies(Long vdcId, int numResults) {
String query = "SELECT s FROM Study s " +
"ORDER BY s.createTime desc";
if (vdcId != null){
query = "SELECT s FROM Study s WHERE s.owner.id = " + vdcId + " ORDER BY s.createTime desc";
}
if (numResults == -1) {
return (List) em.createQuery(query).getResultList();
} else {
return (List) em.createQuery(query).setMaxResults(numResults).getResultList();
}
}
public List getRecentlyReleasedStudyIds(Long vdcId, Long vdcNetworkId, int numResults) {
String linkedStudyClause = "";
String networkClause = "";
if (vdcNetworkId != null && !vdcNetworkId.equals(vdcNetworkService.findRootNetwork().getId())) {
networkClause = " and v.vdcnetwork_id = " + vdcNetworkId + " ";
VDCNetwork vdcNetwork = vdcNetworkService.findById(vdcNetworkId);
List<Study> linkedStudys = (List) vdcNetwork.getLinkedStudies();
List<Long> studyIdList = new ArrayList<Long>();
for (Study study : linkedStudys) {
studyIdList.add(study.getId());
}
if (studyIdList != null && studyIdList.size() > 0) {
String studyIds = generateTempTableString(studyIdList);
linkedStudyClause = " or sv.study_id in (" + studyIds + ") ";
}
}
String queryStr = " SELECT sv.study_id FROM StudyVersion sv where sv.versionstate = "
+ "'" + StudyVersion.VersionState.RELEASED + "'"
+ " and (sv.study_id in ( "
+ " select s.id FROM VDC v, Study s, StudyVersion sv where s.id = sv.study_id and sv.versionstate = "
+ "'" + StudyVersion.VersionState.RELEASED + "'"
+ " and s.owner_id = v.id and v.restricted = false "
+ networkClause
+ ") "
+ linkedStudyClause
+ ") ORDER BY sv.releaseTime desc";
if (vdcId != null) {
queryStr = "SELECT s.id FROM Study s, StudyVersion sv where s.id = sv.study_id "
+ " and sv.versionstate = '" + StudyVersion.VersionState.RELEASED + "'" + " and s.owner_id = " + vdcId
+ " ORDER BY sv.releaseTime desc";
}
//System.out.print("release data query " + queryStr);
Query query = em.createNativeQuery(queryStr);
List<Long> returnList = new ArrayList<Long>();
if (numResults == -1) {
for (Object currentResult : query.getResultList()) {
if (currentResult instanceof Integer) { // convert results into Longs
returnList.add(new Long(((Integer) currentResult).longValue()));
} else {
returnList.add(new Long(((Long) currentResult).longValue()));
}
}
} else {
int i = 0;
for (Object currentResult : query.getResultList()) {
i++;
if (i > numResults) {
break;
} else {
if (currentResult instanceof Integer) { // convert results into Longs
returnList.add(new Long(((Integer) currentResult).longValue()));
} else {
returnList.add(new Long(((Long) currentResult).longValue()));
}
}
}
}
return returnList;
}
public List getMostDownloadedStudyIds(Long vdcId, Long vdcNetworkId, int numResults) {
String dataverseClause = "";
if (vdcId != null) {
dataverseClause = " and s.owner_id = " + vdcId + " ";
}
String linkedStudyClause = "";
String networkClause = "";
if (vdcNetworkId != null && !vdcNetworkId.equals(vdcNetworkService.findRootNetwork().getId())) {
networkClause = " and v.vdcnetwork_id = " + vdcNetworkId + " ";
VDCNetwork vdcNetwork = vdcNetworkService.findById(vdcNetworkId);
List<Study> linkedStudys = (List) vdcNetwork.getLinkedStudies();
List<Long> studyIdList = new ArrayList<Long>();
for (Study study : linkedStudys) {
studyIdList.add(study.getId());
}
if (studyIdList != null && studyIdList.size() > 0) {
String studyIds = generateTempTableString(studyIdList);
linkedStudyClause = " or s.id in (" + studyIds + ") ";
}
}
String queryStr = "select s.id "
+ "from Study s "
+ "left outer JOIN StudyFileActivity sfa on s.id = sfa.study_id "
+ "where s.id in ( select s.id from Study s, VDC v, StudyVersion sv "
+ " where s.id = sv.study_id "
+ " and s.owner_id = v.id "
+ " and v.restricted = false "
+ " and sv.versionstate = '" + StudyVersion.VersionState.RELEASED + "'"
+ dataverseClause
+ networkClause
+ ")"
+ linkedStudyClause
+ " group by s.id "
+ " order by "
+ "(CASE WHEN sum(downloadcount) is null THEN -1 ELSE sum(downloadcount) END) desc";
//System.out.print("Download count query " + queryStr);
Query query = em.createNativeQuery(queryStr);
List<Long> returnList = new ArrayList<Long>();
if (numResults == -1) {
for (Object currentResult : query.getResultList()) {
// convert results into Longs
returnList.add(new Long(((Integer) currentResult).longValue()));
}
} else {
int i = 0;
for (Object currentResult : query.getResultList()) {
i++;
if (i > numResults) {
break;
} else {
returnList.add(new Long(((Integer) currentResult).longValue()));
}
}
}
return returnList;
}
public List<Long> getStudyIdsForExport() {
String queryStr = "select s.id from study s, studyversion sv where s.id = sv.study_id and sv.versionstate = '"+ StudyVersion.VersionState.RELEASED +
"' and s.isharvested='false' and (sv.releasetime > s.lastexporttime or s.lastexporttime is null)";
Query query = em.createNativeQuery(queryStr);
List<Long> returnList = new ArrayList<Long>();
for (Object currentResult : query.getResultList()) {
// convert results into Longs
returnList.add(new Long(((Integer)currentResult).longValue()));
}
return returnList;
}
public List<Long> getAllStudyIds() {
String queryStr = "select id from study order by id";
Query query = em.createNativeQuery(queryStr);
List<Long> returnList = new ArrayList<Long>();
for (Object currentResult : query.getResultList()) {
// convert results into Longs
returnList.add(new Long(((Integer)currentResult).longValue()));
}
return returnList;
}
// This method is used by the IndexServiceBean in order to find and
// reindex the studies that are no longer cross-linked by any foreign
// subnetworks.
public List<Long> getAllLinkedStudyIds() {
List<Long> returnList = new ArrayList<Long>();
String queryStr = "SELECT DISTINCT study_id FROM linked_network_studies ORDER BY study_id";
Query query = em.createNativeQuery(queryStr);
for (Object currentResult : query.getResultList()) {
// convert results into Longs
returnList.add((Long)currentResult);
}
return returnList;
}
public List<Long> getAllNonHarvestedStudyIds() {
String queryStr = "select id from study where isharvested='false'";
Query query = em.createNativeQuery(queryStr);
List<Long> returnList = new ArrayList<Long>();
for (Object currentResult : query.getResultList()) {
// convert results into Longs
returnList.add(new Long(((Integer)currentResult).longValue()));
}
return returnList;
}
/**
* this method only returns released studies
* @param studyIdList
* @param orderBy
* @return list of oredered ids
*/
public List getOrderedStudies(List studyIdList, String orderBy) {
if (orderBy == null || studyIdList == null || studyIdList.size() == 0) {
return studyIdList;
}
String studyIds = generateTempTableString(studyIdList);
String queryStr = null;
if (orderBy.equals("globalId")) {
queryStr = "SELECT s.id " +
"from study s " +
"where s.id in (" + studyIds + ") " +
"ORDER BY s.protocol, s.authority, s.studyId";
} else if (orderBy.equals("title")) {
queryStr = "SELECT s.id " +
"from metadata m, studyversion sv, study s " +
"where sv.metadata_id = m.id " +
"and s.id = sv.study_id " +
"and sv.versionstate = '" + StudyVersion.VersionState.RELEASED + "'" +
"and s.id in (" + studyIds + ") " +
"ORDER BY m.title";
} else if (orderBy.equals("releaseTime")) {
queryStr = "SELECT s.id " +
"from studyversion sv, study s " +
"where s.id = sv.study_id " +
"and sv.versionstate = '" + StudyVersion.VersionState.RELEASED + "'" +
"and s.id in (" + studyIds + ") " +
"ORDER BY sv.releasetime desc";
} else if (orderBy.equals("productionDate")) {
queryStr = "SELECT s.id " +
"from metadata m, studyversion sv, study s " +
"where sv.metadata_id = m.id " +
"and s.id = sv.study_id " +
"and sv.versionstate = '" + StudyVersion.VersionState.RELEASED + "'" +
"and s.id in (" + studyIds + ") " +
"ORDER BY m.productionDate desc";
} else if (orderBy.equals("downloadCount")) {
// this query runs fine in Postgres, but will need to be tested with other DBs if they are used
queryStr = "select s.id " +
"from metadata m, studyversion sv, study s " +
"LEFT OUTER JOIN studyfileactivity sfa on s.id = sfa.study_id " +
"where sv.metadata_id = m.id " +
"and s.id = sv.study_id " +
"and sv.versionstate = '" + StudyVersion.VersionState.RELEASED + "'" +
"and s.id in (" + studyIds + ")" +
"group by s.id, m.title " +
"order by " +
"(CASE WHEN sum(downloadcount) is null THEN -1 ELSE sum(downloadcount) END) desc, m.title" ;
}
if (queryStr != null) {
Query query = em.createNativeQuery(queryStr);
System.out.print("sort " + queryStr);
List<Long> returnList = new ArrayList<Long>();
for (Object currentResult : query.getResultList()) {
// convert results into Longs
returnList.add(new Long(((Integer)currentResult).longValue()));
}
return returnList;
} else {
return studyIdList; // invalid order by
}
}
public List getDvOrderedStudyVersionIds(Long vdcId, String orderBy, boolean ascending) {
List<Long> returnList = new ArrayList<Long>();
String queryStr = "SELECT v.id" +
" from studyversion v, study s, metadata m, vdcuser cr" +
" WHERE v.study_id = s.id" +
" and v.metadata_id = m.id" +
" and s.creator_id = cr.id" +
" and s.owner_id = " + vdcId +
" and v.id in (SELECT max(v.id) from studyversion v group by v.study_id)" +
" ORDER BY " + orderBy;
if (!ascending) {
queryStr += " desc";
}