-
Notifications
You must be signed in to change notification settings - Fork 541
Expand file tree
/
Copy pathDatasetVersion.java
More file actions
2213 lines (1963 loc) · 91 KB
/
DatasetVersion.java
File metadata and controls
2213 lines (1963 loc) · 91 KB
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
package edu.harvard.iq.dataverse;
import edu.harvard.iq.dataverse.settings.JvmSettings;
import edu.harvard.iq.dataverse.util.MarkupChecker;
import edu.harvard.iq.dataverse.util.PersonOrOrgUtil;
import edu.harvard.iq.dataverse.util.BundleUtil;
import edu.harvard.iq.dataverse.util.DataFileComparator;
import edu.harvard.iq.dataverse.DatasetFieldType.FieldType;
import edu.harvard.iq.dataverse.branding.BrandingUtil;
import edu.harvard.iq.dataverse.dataset.DatasetUtil;
import edu.harvard.iq.dataverse.license.License;
import edu.harvard.iq.dataverse.util.FileUtil;
import edu.harvard.iq.dataverse.util.StringUtil;
import edu.harvard.iq.dataverse.util.SystemConfig;
import edu.harvard.iq.dataverse.util.DateUtil;
import edu.harvard.iq.dataverse.util.json.JsonUtil;
import edu.harvard.iq.dataverse.util.json.NullSafeJsonBuilder;
import edu.harvard.iq.dataverse.workflows.WorkflowComment;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import jakarta.json.Json;
import jakarta.json.JsonArray;
import jakarta.json.JsonArrayBuilder;
import jakarta.json.JsonObject;
import jakarta.json.JsonObjectBuilder;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.persistence.Transient;
import jakarta.persistence.UniqueConstraint;
import jakarta.persistence.Version;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Size;
import org.apache.commons.lang3.StringUtils;
/**
*
* @author skraffmiller
*/
@NamedQueries({
@NamedQuery(name = "DatasetVersion.findUnarchivedReleasedVersion",
query = "SELECT OBJECT(o) FROM DatasetVersion AS o WHERE o.dataset.harvestedFrom IS NULL and o.releaseTime IS NOT NULL and o.archivalCopyLocation IS NULL"
),
@NamedQuery(name = "DatasetVersion.findById",
query = "SELECT o FROM DatasetVersion o LEFT JOIN FETCH o.fileMetadatas WHERE o.id=:id"),
@NamedQuery(name = "DatasetVersion.findByDataset",
query = "SELECT o FROM DatasetVersion o WHERE o.dataset.id=:datasetId ORDER BY o.versionNumber DESC, o.minorVersionNumber DESC"),
@NamedQuery(name = "DatasetVersion.findReleasedByDataset",
query = "SELECT o FROM DatasetVersion o WHERE o.dataset.id=:datasetId AND o.versionState=edu.harvard.iq.dataverse.DatasetVersion.VersionState.RELEASED ORDER BY o.versionNumber DESC, o.minorVersionNumber DESC")/*,
@NamedQuery(name = "DatasetVersion.findVersionElements",
query = "SELECT o.id, o.versionState, o.versionNumber, o.minorVersionNumber FROM DatasetVersion o WHERE o.dataset.id=:datasetId ORDER BY o.versionNumber DESC, o.minorVersionNumber DESC")*/})
@Entity
@Table(indexes = {@Index(columnList="dataset_id")},
uniqueConstraints = @UniqueConstraint(columnNames = {"dataset_id,versionnumber,minorversionnumber"}))
@ValidateDeaccessionNote(deaccessionNote = "deaccessionNote", versionState = "versionState")
public class DatasetVersion implements Serializable {
private static final Logger logger = Logger.getLogger(DatasetVersion.class.getCanonicalName());
private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
/**
* Convenience comparator to compare dataset versions by their version number.
* The draft version is considered the latest.
*/
public static final Comparator<DatasetVersion> compareByVersion = new Comparator<DatasetVersion>() {
@Override
public int compare(DatasetVersion o1, DatasetVersion o2) {
if ( o1.isDraft() ) {
return o2.isDraft() ? 0 : 1;
} else {
return (int)Math.signum( (o1.getVersionNumber().equals(o2.getVersionNumber())) ?
o1.getMinorVersionNumber() - o2.getMinorVersionNumber()
: o1.getVersionNumber() - o2.getVersionNumber() );
}
}
};
public static final JsonObjectBuilder compareVersions(DatasetVersion originalVersion, DatasetVersion newVersion) {
DatasetVersionDifference diff = new DatasetVersionDifference(newVersion, originalVersion);
return diff.compareVersionsAsJson();
}
// TODO: Determine the UI implications of various version states
//IMPORTANT: If you add a new value to this enum, you will also have to modify the
// StudyVersionsFragment.xhtml in order to display the correct value from a Resource Bundle
public enum VersionState {
DRAFT, RELEASED, ARCHIVED, DEACCESSIONED
}
public static final int DEACCESSION_NOTE_MAX_LENGTH = 1000;
public static final int DEACCESSION_LINK_MAX_LENGTH = 1260; //Long enough to cover the case where a legacy deaccessionLink(256 char) and archiveNote (1000) are combined (with a space)
public static final int VERSION_NOTE_MAX_LENGTH = 1000;
//Archival copies: Status message required components
public static final String ARCHIVAL_STATUS = "status";
public static final String ARCHIVAL_STATUS_MESSAGE = "message";
//Archival Copies: Allowed Statuses
public static final String ARCHIVAL_STATUS_PENDING = "pending";
public static final String ARCHIVAL_STATUS_SUCCESS = "success";
public static final String ARCHIVAL_STATUS_FAILURE = "failure";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String UNF;
@Version
private Long version;
private Long versionNumber;
private Long minorVersionNumber;
//This is used for the deaccession reason
@Size(min=0, max=DEACCESSION_NOTE_MAX_LENGTH)
@Column(length = DEACCESSION_NOTE_MAX_LENGTH)
private String deaccessionNote;
//This is a plain text, optional reason for the version's creation
@Size(min=0, max=VERSION_NOTE_MAX_LENGTH)
@Column(length = VERSION_NOTE_MAX_LENGTH)
private String versionNote;
/*
* @todo versionState should never be null so when we are ready, uncomment
* the `nullable = false` below.
*/
// @Column(nullable = false)
@Enumerated(EnumType.STRING)
private VersionState versionState;
@ManyToOne
private Dataset dataset;
@OneToMany(mappedBy = "datasetVersion", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("label") // this is not our preferred ordering, which is with the AlphaNumericComparator, but does allow the files to be grouped by category
private List<FileMetadata> fileMetadatas = new ArrayList();
@OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}, orphanRemoval=true)
@JoinColumn(name = "termsOfUseAndAccess_id")
private TermsOfUseAndAccess termsOfUseAndAccess;
@OneToMany(mappedBy = "datasetVersion", orphanRemoval = true, cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
private List<DatasetField> datasetFields = new ArrayList();
@Temporal(value = TemporalType.TIMESTAMP)
@Column( nullable=false )
private Date createTime;
@Temporal(value = TemporalType.TIMESTAMP)
@Column( nullable=false )
private Date lastUpdateTime;
@Temporal(value = TemporalType.TIMESTAMP)
private Date releaseTime;
@Temporal(value = TemporalType.TIMESTAMP)
private Date archiveTime;
// Originally a simple string indicating the location of the archival copy. As
// of v5.12, repurposed to provide a more general json archival status (failure,
// pending, success) and message (serialized as a string). The archival copy
// location is now expected as the contents of the message for the status
// 'success'. See the /api/datasets/{id}/{version}/archivalStatus API calls for more details
@Column(nullable=true, columnDefinition = "TEXT")
private String archivalCopyLocation;
//This is used for the deaccession reason
@Size(min=0, max=DEACCESSION_LINK_MAX_LENGTH)
@Column(length = DEACCESSION_LINK_MAX_LENGTH)
private String deaccessionLink;
@Transient
private String contributorNames;
@Transient
private final String dataverseSiteUrl = SystemConfig.getDataverseSiteUrlStatic();
@Transient
private String jsonLd;
@OneToMany(mappedBy="datasetVersion", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
private List<DatasetVersionUser> datasetVersionUsers;
// Is this the right mapping and cascading for when the workflowcomments table is being used for objects other than DatasetVersion?
@OneToMany(mappedBy = "datasetVersion", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
private List<WorkflowComment> workflowComments;
@OneToMany(mappedBy = "datasetVersion", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("createTime DESC NULLS LAST")
private List<CurationStatus> curationStatuses = new ArrayList<>();
@Transient
private DatasetVersionDifference dvd;
@Transient
private JsonObject archivalStatus;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUNF() {
return UNF;
}
public void setUNF(String UNF) {
this.UNF = UNF;
}
/**
* This is JPA's optimistic locking mechanism, and has no semantic meaning in the DV object model.
* @return the object db version
*/
public Long getVersion() {
return this.version;
}
public void setVersion(Long version) {
}
public String getDataverseSiteUrl() {
return dataverseSiteUrl;
}
public List<FileMetadata> getFileMetadatas() {
return fileMetadatas;
}
public List<FileMetadata> getFileMetadatasSorted() {
/*
* fileMetadatas can sometimes be an
* org.eclipse.persistence.indirection.IndirectList When that happens, the
* comparator in the Collections.sort below is not called, possibly due to
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=446236 which is Java 1.8+
* specific Converting to an ArrayList solves the problem, but the longer term
* solution may be in avoiding the IndirectList or moving to a new version of
* the jar it is in.
*/
if(!(fileMetadatas instanceof ArrayList)) {
List<FileMetadata> newFMDs = new ArrayList<FileMetadata>();
for(FileMetadata fmd: fileMetadatas) {
newFMDs.add(fmd);
}
setFileMetadatas(newFMDs);
}
DataFileComparator dfc = new DataFileComparator();
Collections.sort(fileMetadatas, dfc.compareBy(true, null!=FileMetadata.getCategorySortOrder(), "name", true));
return fileMetadatas;
}
public List<FileMetadata> getFileMetadatasSortedByLabelAndFolder() {
ArrayList<FileMetadata> fileMetadatasCopy = new ArrayList<>();
fileMetadatasCopy.addAll(fileMetadatas);
DataFileComparator dfc = new DataFileComparator();
Collections.sort(fileMetadatasCopy, dfc.compareBy(true, null!=FileMetadata.getCategorySortOrder(), "name", true));
return fileMetadatasCopy;
}
public List<FileMetadata> getFileMetadatasFolderListing(String folderName) {
ArrayList<FileMetadata> fileMetadatasCopy = new ArrayList<>();
HashSet<String> subFolders = new HashSet<>();
for (FileMetadata fileMetadata : fileMetadatas) {
String thisFolder = fileMetadata.getDirectoryLabel() == null ? "" : fileMetadata.getDirectoryLabel();
if (folderName.equals(thisFolder)) {
fileMetadatasCopy.add(fileMetadata);
} else if (thisFolder.startsWith(folderName)) {
String subFolder = "".equals(folderName) ? thisFolder : thisFolder.substring(folderName.length() + 1);
if (subFolder.indexOf('/') > 0) {
subFolder = subFolder.substring(0, subFolder.indexOf('/'));
}
if (!subFolders.contains(subFolder)) {
fileMetadatasCopy.add(fileMetadata);
subFolders.add(subFolder);
}
}
}
Collections.sort(fileMetadatasCopy, FileMetadata.compareByFullPath);
return fileMetadatasCopy;
}
public void setFileMetadatas(List<FileMetadata> fileMetadatas) {
this.fileMetadatas = fileMetadatas;
}
public TermsOfUseAndAccess getTermsOfUseAndAccess() {
return termsOfUseAndAccess;
}
public void setTermsOfUseAndAccess(TermsOfUseAndAccess termsOfUseAndAccess) {
this.termsOfUseAndAccess = termsOfUseAndAccess;
}
public List<DatasetField> getDatasetFields() {
return datasetFields;
}
/**
* Sets the dataset fields for this version. Also updates the fields to
* have @{code this} as their dataset version.
* @param datasetFields
*/
public void setDatasetFields(List<DatasetField> datasetFields) {
for ( DatasetField dsf : datasetFields ) {
dsf.setDatasetVersion(this);
}
this.datasetFields = datasetFields;
}
/**
* The only time a dataset can be in review is when it is in draft.
* @return if the dataset is being reviewed
*/
public boolean isInReview() {
if (versionState != null && versionState.equals(VersionState.DRAFT)) {
return getDataset().isLockedFor(DatasetLock.Reason.InReview);
} else {
return false;
}
}
public Date getArchiveTime() {
return archiveTime;
}
public void setArchiveTime(Date archiveTime) {
this.archiveTime = archiveTime;
}
public String getArchivalCopyLocation() {
return archivalCopyLocation;
}
public String getArchivalCopyLocationStatus() {
populateArchivalStatus(false);
if(archivalStatus!=null) {
return archivalStatus.getString(ARCHIVAL_STATUS);
}
return null;
}
public String getArchivalCopyLocationMessage() {
populateArchivalStatus(false);
if(archivalStatus!=null) {
return archivalStatus.getString(ARCHIVAL_STATUS_MESSAGE);
}
return null;
}
private void populateArchivalStatus(boolean force) {
if(archivalStatus ==null || force) {
if(archivalCopyLocation!=null) {
try {
archivalStatus = JsonUtil.getJsonObject(archivalCopyLocation);
} catch(Exception e) {
logger.warning("DatasetVersion id: " + id + "has a non-JsonObject value, parsing error: " + e.getMessage());
logger.fine(archivalCopyLocation);
}
}
}
}
public void setArchivalCopyLocation(String location) {
this.archivalCopyLocation = location;
populateArchivalStatus(true);
}
public String getDeaccessionLink() {
return deaccessionLink;
}
public void setDeaccessionLink(String deaccessionLink) {
if (deaccessionLink != null && deaccessionLink.length() > DEACCESSION_LINK_MAX_LENGTH) {
throw new IllegalArgumentException("Error setting deaccessionLink: String length is greater than maximum (" + DEACCESSION_LINK_MAX_LENGTH + ")."
+ " StudyVersion id=" + id + ", deaccessionLink=" + deaccessionLink);
}
this.deaccessionLink = deaccessionLink;
}
public String getDeaccessionLinkAsURLString() {
String dLink = null;
try {
dLink = new URI(deaccessionLink).toURL().toExternalForm();
} catch (URISyntaxException | MalformedURLException e) {
logger.fine("Invalid deaccessionLink - not a URL: " + deaccessionLink);
}
return dLink;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
if (createTime == null) {
createTime = lastUpdateTime;
}
this.lastUpdateTime = lastUpdateTime;
}
public String getVersionDate() {
if (this.lastUpdateTime == null){
return null;
}
return DateUtil.formatDate(lastUpdateTime);
}
public String getVersionYear() {
return new SimpleDateFormat("yyyy").format(lastUpdateTime);
}
public Date getReleaseTime() {
return releaseTime;
}
public void setReleaseTime(Date releaseTime) {
this.releaseTime = releaseTime;
}
public List<DatasetVersionUser> getDatasetVersionUsers() {
return datasetVersionUsers;
}
public void setUserDatasets(List<DatasetVersionUser> datasetVersionUsers) {
this.datasetVersionUsers = datasetVersionUsers;
}
public List<String> getVersionContributorIdentifiers() {
if (this.getDatasetVersionUsers() == null) {
return Collections.emptyList();
}
List<String> ret = new LinkedList<>();
for (DatasetVersionUser contributor : this.getDatasetVersionUsers()) {
ret.add(contributor.getAuthenticatedUser().getIdentifier());
}
return ret;
}
public String getContributorNames() {
return contributorNames;
}
public void setContributorNames(String contributorNames) {
this.contributorNames = contributorNames;
}
public String getDeaccessionNote() {
return deaccessionNote;
}
public DatasetVersionDifference getDefaultVersionDifference() {
//Cache to avoid recalculating the difference many many times in the dataset-versions.xhtml page
if(dvd!=null) {
return dvd;
}
// if version is deaccessioned ignore it for differences purposes
int index = 0;
int size = this.getDataset().getVersions().size();
if (this.isDeaccessioned()) {
return null;
}
for (DatasetVersion dsv : this.getDataset().getVersions()) {
if (this.equals(dsv)) {
if ((index + 1) <= (size - 1)) {
for (DatasetVersion dvTest : this.getDataset().getVersions().subList(index + 1, size)) {
if (!dvTest.isDeaccessioned()) {
dvd = new DatasetVersionDifference(this, dvTest);
return dvd;
}
}
}
}
index++;
}
return null;
}
public VersionState getPriorVersionState() {
int index = 0;
int size = this.getDataset().getVersions().size();
if (this.isDeaccessioned()) {
return null;
}
for (DatasetVersion dsv : this.getDataset().getVersions()) {
if (this.equals(dsv)) {
if ((index + 1) <= (size - 1)) {
for (DatasetVersion dvTest : this.getDataset().getVersions().subList(index + 1, size)) {
return dvTest.getVersionState();
}
}
}
index++;
}
return null;
}
public void setDeaccessionNote(String note) {
if (note != null && note.length() > DEACCESSION_NOTE_MAX_LENGTH) {
throw new IllegalArgumentException("Error setting deaccessionNote: String length is greater than maximum (" + DEACCESSION_NOTE_MAX_LENGTH + ")."
+ " StudyVersion id=" + id + ", deaccessionNote=" + note);
}
this.deaccessionNote = note;
}
public Long getVersionNumber() {
return versionNumber;
}
public void setVersionNumber(Long versionNumber) {
this.versionNumber = versionNumber;
}
public Long getMinorVersionNumber() {
return minorVersionNumber;
}
public void setMinorVersionNumber(Long minorVersionNumber) {
this.minorVersionNumber = minorVersionNumber;
}
public String getFriendlyVersionNumber(){
if (this.isDraft()) {
return "DRAFT";
} else {
return versionNumber.toString() + "." + minorVersionNumber.toString();
}
}
public VersionState getVersionState() {
return versionState;
}
public void setVersionState(VersionState versionState) {
this.versionState = versionState;
}
public boolean isReleased() {
return versionState.equals(VersionState.RELEASED);
}
public boolean isPublished() {
return isReleased();
}
public boolean isDraft() {
return versionState.equals(VersionState.DRAFT);
}
public boolean isWorkingCopy() {
return versionState.equals(VersionState.DRAFT);
}
public boolean isArchived() {
return versionState.equals(VersionState.ARCHIVED);
}
public boolean isDeaccessioned() {
return versionState.equals(VersionState.DEACCESSIONED);
}
public boolean isRetiredCopy() {
return (versionState.equals(VersionState.ARCHIVED) || versionState.equals(VersionState.DEACCESSIONED));
}
public boolean isMinorUpdate() {
if (this.dataset.getLatestVersion().isWorkingCopy()) {
if (this.dataset.getVersions().size() > 1 && this.dataset.getVersions().get(1) != null) {
if (this.dataset.getVersions().get(1).isDeaccessioned()) {
return false;
}
}
}
if (this.getDataset().getReleasedVersion() != null) {
if (this.getFileMetadatas().size() != this.getDataset().getReleasedVersion().getFileMetadatas().size()){
return false;
} else {
List <DataFile> current = new ArrayList<>();
List <DataFile> previous = new ArrayList<>();
for (FileMetadata fmdc : this.getFileMetadatas()){
current.add(fmdc.getDataFile());
}
for (FileMetadata fmdc : this.getDataset().getReleasedVersion().getFileMetadatas()){
previous.add(fmdc.getDataFile());
}
for (DataFile fmd: current){
previous.remove(fmd);
}
return previous.isEmpty();
}
}
return true;
}
public boolean isHasPackageFile(){
if (this.fileMetadatas.isEmpty()){
return false;
}
if(this.fileMetadatas.size() > 1){
return false;
}
return this.fileMetadatas.get(0).getDataFile().getContentType().equals(DataFileServiceBean.MIME_TYPE_PACKAGE_FILE);
}
public boolean isHasNonPackageFile(){
if (this.fileMetadatas.isEmpty()){
return false;
}
// The presence of any non-package file means that HTTP Upload was used (no mixing allowed) so we just check the first file.
return !this.fileMetadatas.get(0).getDataFile().getContentType().equals(DataFileServiceBean.MIME_TYPE_PACKAGE_FILE);
}
public boolean isHasRestrictedFile(){
if (this.fileMetadatas == null || this.fileMetadatas.isEmpty()){
return false;
}
return this.fileMetadatas.stream().anyMatch(fm -> (fm.isRestricted()));
}
public void updateDefaultValuesFromTemplate(Template template) {
if (!template.getDatasetFields().isEmpty()) {
this.setDatasetFields(this.copyDatasetFields(template.getDatasetFields()));
}
if (template.getTermsOfUseAndAccess() != null) {
TermsOfUseAndAccess terms = template.getTermsOfUseAndAccess().copyTermsOfUseAndAccess();
terms.setDatasetVersion(this);
this.setTermsOfUseAndAccess(terms);
}
}
public DatasetVersion cloneDatasetVersion(){
DatasetVersion dsv = new DatasetVersion();
dsv.setVersionState(this.getPriorVersionState());
dsv.setFileMetadatas(new ArrayList<>());
if (this.getUNF() != null){
dsv.setUNF(this.getUNF());
}
if (this.getDatasetFields() != null && !this.getDatasetFields().isEmpty()) {
dsv.setDatasetFields(dsv.copyDatasetFields(this.getDatasetFields()));
}
/*
adding file metadatas here and updating terms
because the terms need to know about the files
in a pre-save validation SEK 12/6/2021
*/
for (FileMetadata fm : this.getFileMetadatas()) {
FileMetadata newFm = new FileMetadata();
// TODO:
// the "category" will be removed, shortly.
// (replaced by multiple, tag-like categories of
// type DataFileCategory) -- L.A. beta 10
//newFm.setCategory(fm.getCategory());
// yep, these are the new categories:
newFm.setCategories(fm.getCategories());
newFm.setDescription(fm.getDescription());
newFm.setLabel(fm.getLabel());
newFm.setDirectoryLabel(fm.getDirectoryLabel());
newFm.setRestricted(fm.isRestricted());
newFm.setDataFile(fm.getDataFile());
newFm.setDatasetVersion(dsv);
newFm.setProvFreeForm(fm.getProvFreeForm());
dsv.getFileMetadatas().add(newFm);
}
if (this.getTermsOfUseAndAccess()!= null){
TermsOfUseAndAccess terms = this.getTermsOfUseAndAccess().copyTermsOfUseAndAccess();
terms.setDatasetVersion(dsv);
dsv.setTermsOfUseAndAccess(terms);
} else {
TermsOfUseAndAccess terms = new TermsOfUseAndAccess();
terms.setDatasetVersion(dsv);
// terms.setLicense(TermsOfUseAndAccess.License.CC0);
dsv.setTermsOfUseAndAccess(terms);
}
dsv.setDataset(this.getDataset());
return dsv;
}
public void initDefaultValues(License license) {
//first clear then initialize - in case values were present
// from template or user entry
this.setDatasetFields(new ArrayList<>());
this.setDatasetFields(this.initDatasetFields());
TermsOfUseAndAccess terms = new TermsOfUseAndAccess();
terms.setDatasetVersion(this);
terms.setLicense(license);
terms.setFileAccessRequest(true);
this.setTermsOfUseAndAccess(terms);
}
public DatasetVersion getMostRecentlyReleasedVersion() {
if (this.isReleased()) {
return this;
} else {
if (this.getDataset().isReleased()) {
for (DatasetVersion testVersion : this.dataset.getVersions()) {
if (testVersion.isReleased()) {
return testVersion;
}
}
}
}
return null;
}
public DatasetVersion getLargestMinorRelease() {
if (this.getDataset().isReleased()) {
for (DatasetVersion testVersion : this.dataset.getVersions()) {
if (testVersion.getVersionNumber() != null && testVersion.getVersionNumber().equals(this.getVersionNumber())) {
return testVersion;
}
}
}
return this;
}
public Dataset getDataset() {
return dataset;
}
public void setDataset(Dataset dataset) {
this.dataset = dataset;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DatasetVersion)) {
return false;
}
DatasetVersion other = (DatasetVersion) object;
return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
}
@Override
public String toString() {
return "[DatasetVersion id:" + getId() + "]";
}
public boolean isLatestVersion() {
return this.equals(this.getDataset().getLatestVersion());
}
public String getTitle() {
String retVal = "";
for (DatasetField dsfv : this.getDatasetFields()) {
if (dsfv.getDatasetFieldType().getName().equals(DatasetFieldConstant.title)) {
retVal = dsfv.getDisplayValue();
}
}
return retVal;
}
public String getProductionDate() {
String retVal = null;
for (DatasetField dsfv : this.getDatasetFields()) {
if (dsfv.getDatasetFieldType().getName().equals(DatasetFieldConstant.productionDate)) {
retVal = dsfv.getDisplayValue();
}
}
return retVal;
}
/**
* @return A string with the description of the dataset as-is from the
* database (if available, or empty string) without passing it through
* methods such as stripAllTags, sanitizeBasicHTML or similar.
*/
public String getDescription() {
for (DatasetField dsf : this.getDatasetFields()) {
if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.description)) {
String descriptionString = "";
if (dsf.getDatasetFieldCompoundValues() != null && dsf.getDatasetFieldCompoundValues().get(0) != null) {
DatasetFieldCompoundValue descriptionValue = dsf.getDatasetFieldCompoundValues().get(0);
for (DatasetField subField : descriptionValue.getChildDatasetFields()) {
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.descriptionText) && !subField.isEmptyForDisplay()) {
descriptionString = subField.getValue();
}
}
}
logger.log(Level.FINE, "pristine description: {0}", descriptionString);
return descriptionString;
}
}
return "";
}
public List<String> getDescriptions() {
List<String> descriptions = new ArrayList<>();
for (DatasetField dsf : this.getDatasetFields()) {
if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.description)) {
String descriptionString = "";
if (dsf.getDatasetFieldCompoundValues() != null && !dsf.getDatasetFieldCompoundValues().isEmpty()) {
for (DatasetFieldCompoundValue descriptionValue : dsf.getDatasetFieldCompoundValues()) {
for (DatasetField subField : descriptionValue.getChildDatasetFields()) {
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.descriptionText) && !subField.isEmptyForDisplay()) {
descriptionString = subField.getValue();
}
}
logger.log(Level.FINE, "pristine description: {0}", descriptionString);
descriptions.add(descriptionString);
}
}
}
}
return descriptions;
}
/**
* @return Strip out all A string with the description of the dataset that
* has been passed through the stripAllTags method to remove all HTML tags.
*/
public String getDescriptionPlainText() {
return MarkupChecker.stripAllTags(getDescription());
}
/* This method is (only) used in creating schema.org json-jd where Google requires a text description <5000 chars.
*
* @returns - a single string composed of all descriptions (joined with \n if more than one) truncated with a trailing '...' if >=5000 chars
*/
public String getDescriptionsPlainTextTruncated() {
List<String> plainTextDescriptions = new ArrayList<String>();
for (String htmlDescription : getDescriptions()) {
plainTextDescriptions.add(MarkupChecker.stripAllTags(htmlDescription));
}
String description = String.join("\n", plainTextDescriptions);
if (description.length() >= 5000) {
int endIndex = description.substring(0, 4997).lastIndexOf(" ");
if (endIndex == -1) {
//There are no spaces so just break anyway
endIndex = 4997;
}
description = description.substring(0, endIndex) + "...";
}
return description;
}
/**
* @return A string with the description of the dataset that has been passed
* through the escapeHtml method to change the "less than" sign to "<"
* for example.
*/
public String getDescriptionHtmlEscaped() {
return MarkupChecker.escapeHtml(getDescription());
}
public List<String[]> getDatasetContacts() {
boolean getDisplayValues = true;
return getDatasetContacts(getDisplayValues);
}
/**
* @param getDisplayValues Instead of the retrieving pristine value in the
* database, run the value through special formatting.
*/
public List<String[]> getDatasetContacts(boolean getDisplayValues) {
List <String[]> retList = new ArrayList<>();
for (DatasetField dsf : this.getDatasetFields()) {
Boolean addContributor = true;
String contributorName = "";
String contributorAffiliation = "";
if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContact)) {
for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) {
for (DatasetField subField : authorValue.getChildDatasetFields()) {
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContactName)) {
if (subField.isEmptyForDisplay()) {
addContributor = false;
}
// There is no use case yet for getting the non-display value for contributorName.
contributorName = subField.getDisplayValue();
}
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContactAffiliation)) {
contributorAffiliation = getDisplayValues ? subField.getDisplayValue() : subField.getValue();
}
}
if (addContributor) {
String[] datasetContributor = new String[] {contributorName, contributorAffiliation};
retList.add(datasetContributor);
}
}
}
}
return retList;
}
public List<String[]> getDatasetProducers(){
List <String[]> retList = new ArrayList<>();
for (DatasetField dsf : this.getDatasetFields()) {
Boolean addContributor = true;
String contributorName = "";
String contributorAffiliation = "";
if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.producer)) {
for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) {
for (DatasetField subField : authorValue.getChildDatasetFields()) {
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerName)) {
if (subField.isEmptyForDisplay()) {
addContributor = false;
}
contributorName = subField.getDisplayValue();
}
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerAffiliation)) {
contributorAffiliation = subField.getDisplayValue();
}
}
if (addContributor) {
String[] datasetContributor = new String[] {contributorName, contributorAffiliation};
retList.add(datasetContributor);
}
}
}
}
return retList;
}
public List<DatasetAuthor> getDatasetAuthors() {
//TODO get "List of Authors" from datasetfieldvalue table
List <DatasetAuthor> retList = new ArrayList<>();
for (DatasetField dsf : this.getDatasetFields()) {
Boolean addAuthor = true;
if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.author)) {
for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) {
DatasetAuthor datasetAuthor = new DatasetAuthor();
for (DatasetField subField : authorValue.getChildDatasetFields()) {
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorName)) {
if (subField.isEmptyForDisplay()) {
addAuthor = false;
}
datasetAuthor.setName(subField);
}
if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorAffiliation)) {
datasetAuthor.setAffiliation(subField);
}