diff --git a/src/main/java/Bundle.properties b/src/main/java/Bundle.properties
index 02fbce1af3d..e768e4c6b99 100755
--- a/src/main/java/Bundle.properties
+++ b/src/main/java/Bundle.properties
@@ -1060,7 +1060,7 @@ dataset.cite.title.released=DRAFT VERSION will be replaced in the citation with
dataset.cite.title.draft=DRAFT VERSION will be replaced in the citation with the selected version once the dataset has been published.
dataset.cite.title.deassessioned=DEACCESSIONED VERSION has been added to the citation for this version since it is no longer available.
dataset.cite.standards.tip=Learn about Data Citation Standards .
-dataset.cite.downloadBtn=Cite Data
+dataset.cite.downloadBtn=Cite Dataset
dataset.cite.downloadBtn.xml=EndNote XML
dataset.cite.downloadBtn.ris=RIS
dataset.cite.downloadBtn.bib=BibTeX
@@ -1201,6 +1201,7 @@ file.spss-porExtraLabels=Variable Labels
file.spss-porExtraLabels.title=Upload an additional text file with extra variable labels.
file.spss-porExtraLabels.selectToAddBtn=Select File to Add
file.ingestFailed=Tabular Data Ingest Failed
+file.explore.twoRavens=TwoRavens
file.mapData=Map Data
file.mapData.viewMap=WorldMap
file.mapData.unpublished.header=Data Not Published
@@ -1218,7 +1219,7 @@ file.requestAccess.dialog.msg=You need to Sign Up or Log In to request access to this file.
file.accessRequested=Access Requested
-file.ingestInproGress=Ingest in progress...
+file.ingestInProgress=Ingest in progress...
file.dataFilesTab.metadata.header=Metadata
file.dataFilesTab.metadata.addBtn=Add + Edit Metadata
@@ -1390,11 +1391,16 @@ dataset.widgets.advanced.success.message=Successfully updated your Personal Webs
dataset.widgets.advanced.failure.message=The dataverse Personal Website URL has not been updated.
# file.xhtml
+file.share.fileShare=Share File
+file.share.fileShare.tip=Share this file on your favorite social media networks.
+file.share.fileShare.shareText=View this file.
file.title.label=Title
file.citation.label=Citation
+file.cite.downloadBtn=Cite Data File
file.general.metadata.label=General Metadata
file.description.label=Description
file.tags.label=Tags
+file.lastupdated.label=Last Updated
file.metadataTab.fileMetadata.header=File Metadata
file.metadataTab.fileMetadata.persistentid.label=Data File Persistent ID
@@ -1402,6 +1408,8 @@ file.metadataTab.fileMetadata.unf.label=UNF
file.metadataTab.fileMetadata.size.label=Size
file.metadataTab.fileMetadata.type.label=Type
file.metadataTab.fileMetadata.description.label=Description
+file.metadataTab.fileMetadata.publicationDate.label=Publication Date
+file.metadataTab.fileMetadata.depositDate.label=Deposit Date
file.metadataTab.fitsMetadata.header=FITS Metadata
file.metadataTab.provenance.header=File Provenance
file.metadataTab.provenance.body=File Provenance information coming in a later release...
diff --git a/src/main/java/Bundle_zh_CN.properties b/src/main/java/Bundle_zh_CN.properties
index d2a8589d2e7..640f504a274 100644
--- a/src/main/java/Bundle_zh_CN.properties
+++ b/src/main/java/Bundle_zh_CN.properties
@@ -361,7 +361,7 @@ file.downloadBtn.format.original=\u539f\u59cb\u6587\u4ef6\u683c\u5f0f\uff08{0}\u
file.downloadBtn.format.rdata=RDATA\u683c\u5f0f
file.downloadBtn.format.var=\u53ef\u53d8\u5143
file.downloadBtn.format.citation=\u6570\u636e\u6587\u4ef6\u5f15\u7528
-file.ingestInproGress=\u6444\u53d6\u4e2d...
+file.ingestInProgress=\u6444\u53d6\u4e2d...
file.dataFilesTab.metadata.header=\u5143\u6570\u636e
file.dataFilesTab.metadata.addBtn=\u6dfb\u52a0+\u7f16\u8f91\u5143\u6570\u636e
file.dataFilesTab.terms.header=\u8bb8\u53ef+\u6761\u6b3e
diff --git a/src/main/java/edu/harvard/iq/dataverse/DataCitation.java b/src/main/java/edu/harvard/iq/dataverse/DataCitation.java
index 3e6bba7e434..c969d4c29a1 100644
--- a/src/main/java/edu/harvard/iq/dataverse/DataCitation.java
+++ b/src/main/java/edu/harvard/iq/dataverse/DataCitation.java
@@ -172,7 +172,7 @@ public String toString(boolean html) {
// append UNF
if (!StringUtils.isEmpty(UNF)) {
- citation.append(" [").append(UNF).append("]");
+ citation.append(", ").append(UNF);
}
for (DatasetField dsf : optionalValues) {
diff --git a/src/main/java/edu/harvard/iq/dataverse/DataFile.java b/src/main/java/edu/harvard/iq/dataverse/DataFile.java
index 76ca90e8038..e8dfe1a18c8 100644
--- a/src/main/java/edu/harvard/iq/dataverse/DataFile.java
+++ b/src/main/java/edu/harvard/iq/dataverse/DataFile.java
@@ -17,6 +17,7 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
+import java.text.SimpleDateFormat;
import java.util.Arrays;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
@@ -693,4 +694,19 @@ public boolean hasGeospatialTag(){
}
return false;
}
+
+ public String getPublicationDateFormattedYYYYMMDD() {
+ if (getPublicationDate() != null){
+ return new SimpleDateFormat("yyyy-MM-dd").format(getPublicationDate());
+ }
+ return null;
+ }
+
+ public String getCreateDateFormattedYYYYMMDD() {
+ if (getCreateDate() != null){
+ return new SimpleDateFormat("yyyy-MM-dd").format(getCreateDate());
+ }
+ return null;
+ }
+
}
diff --git a/src/main/java/edu/harvard/iq/dataverse/DataFileServiceBean.java b/src/main/java/edu/harvard/iq/dataverse/DataFileServiceBean.java
index 90878c394a6..aabb1d4bb15 100644
--- a/src/main/java/edu/harvard/iq/dataverse/DataFileServiceBean.java
+++ b/src/main/java/edu/harvard/iq/dataverse/DataFileServiceBean.java
@@ -435,7 +435,7 @@ public void findFileMetadataOptimizedExperimental(Dataset owner, DatasetVersion
int i = 0;
- List dataTableResults = em.createNativeQuery("SELECT t0.ID, t0.DATAFILE_ID, t0.UNF, t0.CASEQUANTITY, t0.VARQUANTITY, t0.ORIGINALFILEFORMAT FROM dataTable t0, dataFile t1, dvObject t2 WHERE ((t0.DATAFILE_ID = t1.ID) AND (t1.ID = t2.ID) AND (t2.OWNER_ID = " + owner.getId() + "))").getResultList();
+ List dataTableResults = em.createNativeQuery("SELECT t0.ID, t0.DATAFILE_ID, t0.UNF, t0.CASEQUANTITY, t0.VARQUANTITY, t0.ORIGINALFILEFORMAT FROM dataTable t0, dataFile t1, dvObject t2 WHERE ((t0.DATAFILE_ID = t1.ID) AND (t1.ID = t2.ID) AND (t2.OWNER_ID = " + owner.getId() + ")) ORDER BY t0.ID").getResultList();
for (Object[] result : dataTableResults) {
DataTable dataTable = new DataTable();
@@ -476,7 +476,7 @@ public void findFileMetadataOptimizedExperimental(Dataset owner, DatasetVersion
i = 0;
- List fileResults = em.createNativeQuery("SELECT t0.ID, t0.CREATEDATE, t0.INDEXTIME, t0.MODIFICATIONTIME, t0.PERMISSIONINDEXTIME, t0.PERMISSIONMODIFICATIONTIME, t0.PUBLICATIONDATE, t0.CREATOR_ID, t0.RELEASEUSER_ID, t1.CONTENTTYPE, t1.FILESYSTEMNAME, t1.FILESIZE, t1.INGESTSTATUS, t1.CHECKSUMVALUE, t1.RESTRICTED, t1.CHECKSUMTYPE FROM DVOBJECT t0, DATAFILE t1 WHERE ((t0.OWNER_ID = " + owner.getId() + ") AND ((t1.ID = t0.ID) AND (t0.DTYPE = 'DataFile')))").getResultList();
+ List fileResults = em.createNativeQuery("SELECT t0.ID, t0.CREATEDATE, t0.INDEXTIME, t0.MODIFICATIONTIME, t0.PERMISSIONINDEXTIME, t0.PERMISSIONMODIFICATIONTIME, t0.PUBLICATIONDATE, t0.CREATOR_ID, t0.RELEASEUSER_ID, t1.CONTENTTYPE, t1.FILESYSTEMNAME, t1.FILESIZE, t1.INGESTSTATUS, t1.CHECKSUMVALUE, t1.RESTRICTED, t1.CHECKSUMTYPE FROM DVOBJECT t0, DATAFILE t1 WHERE ((t0.OWNER_ID = " + owner.getId() + ") AND ((t1.ID = t0.ID) AND (t0.DTYPE = 'DataFile'))) ORDER BY t0.ID").getResultList();
for (Object[] result : fileResults) {
Integer file_id = (Integer) result[0];
@@ -599,7 +599,6 @@ public void findFileMetadataOptimizedExperimental(Dataset owner, DatasetVersion
filesMap.put(dataFile.getId(), i++);
}
- owner.setFiles(dataFiles);
fileResults = null;
logger.fine("Retrieved and cached "+i+" datafiles.");
@@ -613,13 +612,14 @@ public void findFileMetadataOptimizedExperimental(Dataset owner, DatasetVersion
logger.fine("Retreived "+i+" file categories attached to the dataset.");
if (requestedVersion != null) {
- requestedVersion.setFileMetadatas(retrieveFileMetadataForVersion(owner, requestedVersion, filesMap, categoryMap));
+ requestedVersion.setFileMetadatas(retrieveFileMetadataForVersion(owner, requestedVersion, dataFiles, filesMap, categoryMap));
} else {
for (DatasetVersion version : owner.getVersions()) {
- version.setFileMetadatas(retrieveFileMetadataForVersion(owner, version, filesMap, categoryMap));
+ version.setFileMetadatas(retrieveFileMetadataForVersion(owner, version, dataFiles, filesMap, categoryMap));
logger.fine("Retrieved "+version.getFileMetadatas().size()+" filemetadatas for the version "+version.getId());
}
}
+ owner.setFiles(dataFiles);
}
private List retrieveFileAccessRequesters(DataFile fileIn){
@@ -638,7 +638,7 @@ private List retrieveFileAccessRequesters(DataFile fileIn){
return retList;
}
- private List retrieveFileMetadataForVersion(Dataset dataset, DatasetVersion version, Map filesMap, Map categoryMap) {
+ private List retrieveFileMetadataForVersion(Dataset dataset, DatasetVersion version, List dataFiles, Map filesMap, Map categoryMap) {
List retList = new ArrayList<>();
Map> categoryMetaMap = new HashMap<>();
@@ -656,7 +656,7 @@ private List retrieveFileMetadataForVersion(Dataset dataset, Datas
logger.fine("Retrieved and mapped "+i+" file categories attached to files in the version "+version.getId());
categoryResults = null;
- List metadataResults = em.createNativeQuery("select id, datafile_id, DESCRIPTION, LABEL, RESTRICTED, DIRECTORYLABEL from FileMetadata where datasetversion_id = "+version.getId()).getResultList();
+ List metadataResults = em.createNativeQuery("select id, datafile_id, DESCRIPTION, LABEL, RESTRICTED, DIRECTORYLABEL from FileMetadata where datasetversion_id = "+version.getId() + " ORDER BY LABEL").getResultList();
for (Object[] result : metadataResults) {
Integer filemeta_id = (Integer) result[0];
@@ -688,7 +688,8 @@ private List retrieveFileMetadataForVersion(Dataset dataset, Datas
fileMetadata.setDatasetVersion(version);
- fileMetadata.setDataFile(dataset.getFiles().get(file_list_id));
+ //fileMetadata.setDataFile(dataset.getFiles().get(file_list_id));
+ fileMetadata.setDataFile(dataFiles.get(file_list_id));
String description = (String) result[2];
@@ -720,7 +721,14 @@ private List retrieveFileMetadataForVersion(Dataset dataset, Datas
logger.fine("Retrieved "+retList.size()+" file metadatas for version "+version.getId()+" (inside the retrieveFileMetadataForVersion method).");
- Collections.sort(retList, FileMetadata.compareByLabel);
+ /*
+ We no longer perform this sort here, just to keep this filemetadata
+ list as identical as possible to when it's produced by the "traditional"
+ EJB method. When it's necessary to have the filemetadatas sorted by
+ FileMetadata.compareByLabel, the DatasetVersion.getFileMetadatasSorted()
+ method should be called.
+
+ Collections.sort(retList, FileMetadata.compareByLabel); */
return retList;
}
@@ -1226,4 +1234,4 @@ public void populateFileSearchCard(SolrSearchResult solrSearchResult) {
solrSearchResult.setEntity(this.findCheapAndEasy(solrSearchResult.getEntityId()));
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/edu/harvard/iq/dataverse/Dataset.java b/src/main/java/edu/harvard/iq/dataverse/Dataset.java
index cc5c241740e..d005ee5a970 100644
--- a/src/main/java/edu/harvard/iq/dataverse/Dataset.java
+++ b/src/main/java/edu/harvard/iq/dataverse/Dataset.java
@@ -10,6 +10,7 @@
import java.util.Date;
import java.util.List;
import java.util.Objects;
+import java.util.logging.Logger;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -41,6 +42,7 @@
@Index(columnList = "thumbnailfile_id")},
uniqueConstraints = @UniqueConstraint(columnNames = {"authority,protocol,identifier,doiseparator"}))
public class Dataset extends DvObjectContainer {
+ private static final Logger logger = Logger.getLogger(Dataset.class.getCanonicalName());
// public static final String REDIRECT_URL = "/dataset.xhtml?persistentId=";
public static final String TARGET_URL = "/citation?persistentId=";
@@ -185,10 +187,12 @@ public String getGlobalId() {
}
public List getFiles() {
+ logger.info("getFiles() on dataset "+this.getId());
return files;
}
public void setFiles(List files) {
+ logger.info("setFiles() on dataset "+this.getId());
this.files = files;
}
diff --git a/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java b/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java
index 436a4b9a009..0c228a087ba 100644
--- a/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java
+++ b/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java
@@ -78,11 +78,14 @@
import java.util.HashSet;
import javax.faces.model.SelectItem;
import java.util.logging.Level;
+import edu.harvard.iq.dataverse.datasetutility.TwoRavensHelper;
+import edu.harvard.iq.dataverse.datasetutility.WorldMapPermissionHelper;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.event.AjaxBehaviorEvent;
+import javax.faces.context.ExternalContext;
import org.apache.commons.lang.StringEscapeUtils;
import org.primefaces.component.tabview.TabView;
@@ -148,6 +151,8 @@ public enum DisplayMode {
@EJB
GuestbookResponseServiceBean guestbookResponseService;
@EJB
+ FileDownloadServiceBean fileDownloadService;
+ @EJB
DataverseLinkingServiceBean dvLinkingService;
@EJB
DatasetLinkingServiceBean dsLinkingService;
@@ -162,8 +167,11 @@ public enum DisplayMode {
@Inject
DatasetVersionUI datasetVersionUI;
@Inject PermissionsWrapper permissionsWrapper;
+ @Inject FileDownloadHelper fileDownloadHelper;
+ @Inject TwoRavensHelper twoRavensHelper;
+ @Inject WorldMapPermissionHelper worldMapPermissionHelper;
+
- private final DateFormat displayDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
private Dataset dataset = new Dataset();
private EditMode editMode;
@@ -186,6 +194,7 @@ public enum DisplayMode {
private List dataverseTemplates = new ArrayList();
private Template defaultTemplate;
private Template selectedTemplate;
+ private String globalId;
private String persistentId;
private String version;
private String protocol = "";
@@ -210,10 +219,8 @@ public enum DisplayMode {
// Used to store results of permissions checks
private final Map datasetPermissionMap = new HashMap<>(); // { Permission human_name : Boolean }
- private final Map fileDownloadPermissionMap = new HashMap<>(); // { FileMetadata.id : Boolean }
+
- private final Map fileMetadataTwoRavensExploreMap = new HashMap<>(); // { FileMetadata.id : Boolean }
- private final Map fileMetadataWorldMapExplore = new HashMap<>(); // { FileMetadata.id : Boolean }
private DataFile selectedDownloadFile;
@@ -266,7 +273,7 @@ public void setFileMetadatasSearch(List fileMetadatasSearch) {
}
public void updateFileSearch(){
- logger.info("updading file search list");
+ logger.info("updating file search list");
if (readOnly) {
this.fileMetadatasSearch = selectFileMetadatasForDisplay(this.fileLabelSearchTerm);
} else {
@@ -301,7 +308,7 @@ private List selectFileMetadatasForDisplay(String searchTerm) {
List retList = new ArrayList<>();
- for (FileMetadata fileMetadata : workingVersion.getFileMetadatas()) {
+ for (FileMetadata fileMetadata : workingVersion.getFileMetadatasSorted()) {
if (searchResultsIdSet == null || searchResultsIdSet.contains(fileMetadata.getId())) {
retList.add(fileMetadata);
}
@@ -320,7 +327,11 @@ public Long getMaxFileUploadSizeInBytes(){
}
public boolean isUnlimitedUploadFileSize(){
- return (this.maxFileUploadSizeInBytes == null);
+
+ if (this.maxFileUploadSizeInBytes == null){
+ return true;
+ }
+ return false;
}
public boolean isMetadataExportEnabled() {
@@ -445,88 +456,15 @@ public boolean isNoDVsRemaining() {
return noDVsRemaining;
}
- /**
- * Convenience method for "Download File" button display logic
- *
- * Used by the dataset.xhtml render logic when listing files
- * Assumes user already has view access to the file list.
- *
- * @param fileMetadata
- * @return boolean
- */
- public boolean canDownloadFile(FileMetadata fileMetadata){
-
- if (fileMetadata == null){
- return false;
- }
-
- if ((fileMetadata.getId() == null) || (fileMetadata.getDataFile().getId() == null)){
- return false;
- }
-
- // --------------------------------------------------------------------
- // Grab the fileMetadata.id and restriction flag
- // --------------------------------------------------------------------
- Long fid = fileMetadata.getId();
- //logger.info("calling candownloadfile on filemetadata "+fid);
- boolean isRestrictedFile = fileMetadata.isRestricted();
-
-
- // --------------------------------------------------------------------
- // Has this file been checked? Look at the DatasetPage hash
- // --------------------------------------------------------------------
- if (this.fileDownloadPermissionMap.containsKey(fid)){
- // Yes, return previous answer
- //logger.info("using cached result for candownloadfile on filemetadata "+fid);
- return this.fileDownloadPermissionMap.get(fid);
- }
- // --------------------------------------------------------------------
- // (1) Is the file Unrestricted ?
- // --------------------------------------------------------------------
- if (!isRestrictedFile){
- // Yes, save answer and return true
- this.fileDownloadPermissionMap.put(fid, true);
- return true;
- }
-
- // --------------------------------------------------------------------
- // Conditions (2) through (3) are for Restricted files
- // --------------------------------------------------------------------
-
- // --------------------------------------------------------------------
- // (2) Does the User have DownloadFile Permission at the **Dataset** level
- // Michael: Leaving this in for now, but shouldn't this be alredy resolved
- // by the premission system, given that files are never permission roots?
- // --------------------------------------------------------------------
- if (this.doesSessionUserHaveDataSetPermission(Permission.DownloadFile)){
- // Yes, save answer and return true
- this.fileDownloadPermissionMap.put(fid, true);
- return true;
- }
-
- // --------------------------------------------------------------------
- // (3) Does the user has DownloadFile permission on the DataFile
- // --------------------------------------------------------------------
- if (this.permissionService.on(fileMetadata.getDataFile()).has(Permission.DownloadFile)){
- this.fileDownloadPermissionMap.put(fid, true);
- return true;
- }
-
- // --------------------------------------------------------------------
- // (4) No download for you! Come back with permissions!
- // --------------------------------------------------------------------
- this.fileDownloadPermissionMap.put(fid, false);
-
- return false;
- }
public boolean isThumbnailAvailable(FileMetadata fileMetadata) {
// new and optimized logic:
// - check download permission here (should be cached - so it's free!)
// - only then ask the file service if the thumbnail is available/exists.
// the service itself no longer checks download permissions.
- if (!this.canDownloadFile(fileMetadata)) {
+
+ if (!this.fileDownloadHelper.canDownloadFile(fileMetadata)) {
return false;
}
@@ -537,28 +475,14 @@ public boolean isThumbnailAvailable(FileMetadata fileMetadata) {
public boolean canUpdateDataset() {
return permissionsWrapper.canUpdateDataset(dvRequestService.getDataverseRequest(), this.dataset);
}
-
public boolean canPublishDataverse() {
return permissionsWrapper.canIssuePublishDataverseCommand(dataset.getOwner());
}
-
- //public boolean canIssuePublishDatasetCommand() {
- // replacing permissionsWrapper.canIssuePublishDatasetCommand(DatasetPage.dataset) on the page
- // return true;
- //}
-
- //public boolean canIssueDeleteCommand() {
- // return true;
- //}
-
- //public boolean canManagePermissions() {
- // return true;
- //}
-
+
public boolean canViewUnpublishedDataset() {
return permissionsWrapper.canViewUnpublishedDataset( dvRequestService.getDataverseRequest(), dataset);
}
-
+
/*
* 4.2.1 optimization.
* HOWEVER, this doesn't appear to be saving us anything!
@@ -657,15 +581,7 @@ public void reset() {
dataset.setGuestbook(null);
}
- public void guestbookResponseValidator(FacesContext context, UIComponent toValidate, Object value) {
- String response = (String) value;
- if (response != null && response.length() > 255) {
- ((UIInput) toValidate).setValid(false);
- FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, JH.localize("dataset.guestbookResponse.guestbook.responseTooLong"), null);
- context.addMessage(toValidate.getClientId(context), message);
- }
- }
public String getGlobalId() {
return persistentId;
@@ -1025,213 +941,6 @@ private void msg(String s){
// System.out.println(s);
}
- /**
- * See table in: https://github.com/IQSS/dataverse/issues/1618
- *
- * Can the user see a reminder to publish button?
- * (0) The application has to be set to Create Edit Maps - true
- * (1) Logged in user
- * (2) Is geospatial file?
- * (3) File has NOT been released
- * (4) No existing Map
- * (5) Can Edit Dataset
- *
- * @param FileMetadata fm
- * @return boolean
- */
- public boolean canSeeMapButtonReminderToPublish(FileMetadata fm){
- if (fm==null){
-
- return false;
- }
-
- // (0) Is the view GeoconnectViewMaps
- if (!settingsService.isTrueForKey(SettingsServiceBean.Key.GeoconnectCreateEditMaps, false)){
- return false;
- }
-
-
- // (1) Is there an authenticated user?
- //
- if (!(isSessionUserAuthenticated())){
- return false;
- }
-
-
- // Is this file a Shapefile or a Tabular file tagged as Geospatial?
- //
- if (!(this.isPotentiallyMappableFileType(fm))){
- return false;
- }
-
- // (3) Is this DataFile released? Yes, don't need reminder
- //
- if (fm.getDataFile().isReleased()){
- return false;
- }
-
- // (4) Does a map already exist? Yes, don't need reminder
- //
- if (this.hasMapLayerMetadata(fm)){
- return false;
- }
-
- // (5) If so, can the logged in user edit the Dataset to which this FileMetadata belongs?
- if (!this.doesSessionUserHaveDataSetPermission(Permission.EditDataset)){
- return false;
- }
-
- // Looks good
- //
- return true;
- }
-
- /**
- * Should there be a Map Data Button for this file?
- * see table in: https://github.com/IQSS/dataverse/issues/1618
- * (1) Is the user logged in?
- * (2) Is this file a Shapefile or a Tabular file tagged as Geospatial?
- * (3) Does the logged in user have permission to edit the Dataset to which this FileMetadata belongs?
- * (4) Is the create Edit Maps flag set to true?
- * (5) Any of these conditions:
- * 9a) File Published
- * (b) Draft: File Previously published
- * @param fm FileMetadata
- * @return boolean
- */
- public boolean canUserSeeMapDataButton(FileMetadata fm){
-
- if (fm==null){
- return false;
- }
-
-
- // (1) Is there an authenticated user?
- if (!(isSessionUserAuthenticated())){
- return false;
- }
-
- // (2) Is this file a Shapefile or a Tabular file tagged as Geospatial?
- // TO DO: EXPAND FOR TABULAR FILES TAGGED AS GEOSPATIAL!
- //
- if (!(this.isPotentiallyMappableFileType(fm))){
- return false;
- }
-
- // (3) Does the user have Edit Dataset permissions?
- //
- if (!this.doesSessionUserHaveDataSetPermission(Permission.EditDataset)){
- return false;
- }
-
- // (4) Is the view GeoconnectViewMaps
- if (!settingsService.isTrueForKey(SettingsServiceBean.Key.GeoconnectCreateEditMaps, false)){
- return false;
- }
-
- // (5) Is File released?
- //
- if (fm.getDataFile().isReleased()){
- return true;
- }
-
- // Nope
- return false;
- }
-
-
- /**
- * Used in the .xhtml file to check whether a tabular file
- * may be viewed via TwoRavens
- *
- * @param fm
- * @return
- */
- public boolean canSeeTwoRavensExploreButton(FileMetadata fm){
-
- if (fm == null){
- return false;
- }
-
- // Has this already been checked?
- if (this.fileMetadataTwoRavensExploreMap.containsKey(fm.getId())){
- // Yes, return previous answer
- //logger.info("using cached result for candownloadfile on filemetadata "+fid);
- return this.fileMetadataTwoRavensExploreMap.get(fm.getId());
- }
-
-
- // (1) Is TwoRavens active via the "setting" table?
- // Nope: get out
- //
- if (!settingsService.isTrueForKey(SettingsServiceBean.Key.TwoRavensTabularView, false)){
- this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
- return false;
- }
-
- // (2) Does the user have download permission?
- // Nope: get out
- //
- if (!(this.canDownloadFile(fm))){
- this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
- return false;
- }
- // (3) Is the DataFile object there and persisted?
- // Nope: scat
- //
- if ((fm.getDataFile() == null)||(fm.getDataFile().getId()==null)){
- this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
- return false;
- }
-
- // (4) Is there tabular data or is the ingest in progress?
- // Yes: great
- //
- if ((fm.getDataFile().isTabularData())||(fm.getDataFile().isIngestInProgress())){
- this.fileMetadataTwoRavensExploreMap.put(fm.getId(), true);
- return true;
- }
-
- // Nope
- this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
- return false;
-
- // (empty fileMetadata.dataFile.id) and (fileMetadata.dataFile.tabularData or fileMetadata.dataFile.ingestInProgress)
- // and DatasetPage.canDownloadFile(fileMetadata)
- }
-
- /**
- * Check if this is a mappable file type.
- *
- * Currently (2/2016)
- * - Shapefile (zipped shapefile)
- * - Tabular file with Geospatial Data tag
- *
- * @param fm
- * @return
- */
- private boolean isPotentiallyMappableFileType(FileMetadata fm){
- if (fm==null){
- return false;
- }
-
- // Yes, it's a shapefile
- //
- if (this.isShapefileType(fm)){
- return true;
- }
-
- // Yes, it's tabular with a geospatial tag
- //
- if (fm.getDataFile().isTabularData()){
- if (fm.getDataFile().hasGeospatialTag()){
- return true;
- }
- }
- return false;
- }
-
-
/**
* For development
*
@@ -1253,61 +962,6 @@ public boolean isGeoconnectDebugAvailable(){
return false;
}
-
-
- /**
- * Should there be a Explore WorldMap Button for this file?
- * See table in: https://github.com/IQSS/dataverse/issues/1618
- *
- * (1) Does the file have MapLayerMetadata?
- * (2) Is there DownloadFile permission for this file?
- *
- * @param fm FileMetadata
- * @return boolean
- */
- public boolean canUserSeeExploreWorldMapButton(FileMetadata fm){
- if (fm==null){
- return false;
- }
-
- if (this.fileMetadataWorldMapExplore.containsKey(fm.getId())){
- // Yes, return previous answer
- //logger.info("using cached result for candownloadfile on filemetadata "+fid);
- return this.fileMetadataWorldMapExplore.get(fm.getId());
- }
-
- /* -----------------------------------------------------
- Does a Map Exist?
- ----------------------------------------------------- */
- if (!(this.hasMapLayerMetadata(fm))){
- // Nope: no button
- this.fileMetadataWorldMapExplore.put(fm.getId(), false);
- return false;
- }
-
- /*
- Is setting for GeoconnectViewMaps true?
- Nope? no button
- */
- if (!settingsService.isTrueForKey(SettingsServiceBean.Key.GeoconnectViewMaps, false)){
- this.fileMetadataWorldMapExplore.put(fm.getId(), false);
- return false;
- }
-
- /* -----------------------------------------------------
- Does user have DownloadFile permission for this file?
- Yes: User can view button!
- ----------------------------------------------------- */
- if (this.canDownloadFile(fm)){
- this.fileMetadataWorldMapExplore.put(fm.getId(), true);
- return true;
- }
-
- // Nope: Can't see button
- //
- this.fileMetadataWorldMapExplore.put(fm.getId(), false);
- return false;
- }
/**
* Create a hashmap consisting of { DataFile.id : MapLayerMetadata object}
@@ -1317,7 +971,6 @@ public boolean canUserSeeExploreWorldMapButton(FileMetadata fm){
*/
private void loadMapLayerMetadataLookup() {
if (this.dataset == null) {
- return;
}
if (this.dataset.getId() == null) {
return;
@@ -1471,22 +1124,19 @@ private String init(boolean initFull) {
// init the citation
displayCitation = dataset.getCitation(true, workingVersion);
-
+
if (initFull) {
- // init the files
- //fileMetadatas = populateFileMetadatas();
+ // init the list of FileMetadatas
if (workingVersion.isDraft() && canUpdateDataset()) {
readOnly = false;
- fileMetadatasSearch = workingVersion.getFileMetadatasSorted();
} else {
// an attempt to retreive both the filemetadatas and datafiles early on, so that
// we don't have to do so later (possibly, many more times than necessary):
-
datafileService.findFileMetadataOptimizedExperimental(dataset);
- fileMetadatasSearch = workingVersion.getFileMetadatas();
}
-
+ fileMetadatasSearch = workingVersion.getFileMetadatasSorted();
+
ownerId = dataset.getOwner().getId();
datasetNextMajorVersion = this.dataset.getNextMajorVersionString();
datasetNextMinorVersion = this.dataset.getNextMinorVersionString();
@@ -1501,6 +1151,8 @@ private String init(boolean initFull) {
// lazyModel = new LazyFileMetadataDataModel(workingVersion.getId(), datafileService );
// populate MapLayerMetadata
this.loadMapLayerMetadataLookup(); // A DataFile may have a related MapLayerMetadata object
+ this.guestbookResponse = guestbookResponseService.initGuestbookResponseForFragment(dataset, null, session);
+
}
} else if (ownerId != null) {
// create mode for a new child dataset
@@ -1565,181 +1217,6 @@ public boolean isReadOnly() {
return readOnly;
}
- public String saveGuestbookResponse(String type) {
- boolean valid = true;
- if (dataset.getGuestbook() != null) {
- if (dataset.getGuestbook().isNameRequired()) {
- if (this.guestbookResponse.getName() == null) {
- valid = false;
- } else {
- valid &= !this.guestbookResponse.getName().isEmpty();
- }
- }
- if (dataset.getGuestbook().isEmailRequired()) {
- if (this.guestbookResponse.getEmail() == null) {
- valid = false;
- } else {
- valid &= !this.guestbookResponse.getEmail().isEmpty();
- }
- }
- if (dataset.getGuestbook().isInstitutionRequired()) {
- if (this.guestbookResponse.getInstitution() == null) {
- valid = false;
- } else {
- valid &= !this.guestbookResponse.getInstitution().isEmpty();
- }
- }
- if (dataset.getGuestbook().isPositionRequired()) {
- if (this.guestbookResponse.getPosition() == null) {
- valid = false;
- } else {
- valid &= !this.guestbookResponse.getPosition().isEmpty();
- }
- }
- }
-
- if (dataset.getGuestbook() != null && !dataset.getGuestbook().getCustomQuestions().isEmpty()) {
- for (CustomQuestion cq : dataset.getGuestbook().getCustomQuestions()) {
- if (cq.isRequired()) {
- for (CustomQuestionResponse cqr : this.guestbookResponse.getCustomQuestionResponses()) {
- if (cqr.getCustomQuestion().equals(cq)) {
- valid &= (cqr.getResponse() != null && !cqr.getResponse().isEmpty());
- }
- }
- }
- }
- }
-
- if (!valid) {
- FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Validation Error", "Please complete required fields for download and re-try."));
- return "";
- }
-
- Command cmd;
- try {
- if (this.guestbookResponse != null) {
- if (!type.equals("multiple")) {
- cmd = new CreateGuestbookResponseCommand(dvRequestService.getDataverseRequest(), this.guestbookResponse, dataset);
- commandEngine.submit(cmd);
- } else {
- for (FileMetadata fmd : this.selectedDownloadableFiles) {
- DataFile df = fmd.getDataFile();
- if (df != null) {
- this.guestbookResponse.setDataFile(df);
- cmd = new CreateGuestbookResponseCommand(dvRequestService.getDataverseRequest(), this.guestbookResponse, dataset);
- commandEngine.submit(cmd);
- }
- }
- }
- }
- } catch (CommandException ex) {
- FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Guestbook Response Save Failed", " - " + ex.toString()));
- logger.severe(ex.getMessage());
- }
-
- if (type.equals("multiple")){
- //return callDownloadServlet(getSelectedFilesIdsString());
- callDownloadServlet(getDownloadableFilesIdsString());
- }
-
- if ((type.equals("download") || type.isEmpty())) {
- //return callDownloadServlet(downloadFormat, this.selectedDownloadFile.getId());
- if(type.isEmpty()){
- downloadFormat = "download";
- }
- callDownloadServlet(downloadFormat, this.selectedDownloadFile.getId());
- }
-
- if (type.equals("explore")) {
- String retVal = getDataExploreURLComplete(this.selectedDownloadFile.getId());
- try {
- FacesContext.getCurrentInstance().getExternalContext().redirect(retVal);
- return retVal;
- } catch (IOException ex) {
- logger.info("Failed to issue a redirect to file download url.");
- }
- }
- return "";
- }
-
- public String exploreOutputLink(FileMetadata fm, String type){
- createSilentGuestbookEntry(fm, type);
- String retVal = getDataExploreURLComplete(fm.getDataFile().getId());
- try {
- FacesContext.getCurrentInstance().getExternalContext().redirect(retVal);
- } catch (IOException ex) {
- logger.info("Failed to issue a redirect to file download url.");
- }
- return "";
- }
-
- //private String callDownloadServlet(String multiFileString){
- private void callDownloadServlet(String multiFileString){
-
- String fileDownloadUrl = "/api/access/datafiles/" + multiFileString;
- try {
- FacesContext.getCurrentInstance().getExternalContext().redirect(fileDownloadUrl);
- } catch (IOException ex) {
- logger.info("Failed to issue a redirect to file download url.");
- }
-
- //return fileDownloadUrl;
- }
-
- //private String callDownloadServlet( String downloadType, Long fileId){
- private void callDownloadServlet( String downloadType, Long fileId){
-
- String fileDownloadUrl = "/api/access/datafile/" + fileId;
-
- if (downloadType != null && downloadType.equals("bundle")){
- fileDownloadUrl = "/api/access/datafile/bundle/" + this.selectedDownloadFile.getId();
- }
- if (downloadType != null && downloadType.equals("original")){
- fileDownloadUrl = "/api/access/datafile/" + this.selectedDownloadFile.getId() + "?format=original";
- }
- if (downloadType != null && downloadType.equals("RData")){
- fileDownloadUrl = "/api/access/datafile/" + this.selectedDownloadFile.getId() + "?format=RData";
- }
- if (downloadType != null && downloadType.equals("var")){
- fileDownloadUrl = "/api/meta/datafile/" + this.selectedDownloadFile.getId();
- }
- if (downloadType != null && downloadType.equals("tab")){
- fileDownloadUrl = "/api/access/datafile/" + this.selectedDownloadFile.getId()+ "?format=tab";
- }
- logger.fine("Returning file download url: " + fileDownloadUrl);
- try {
- FacesContext.getCurrentInstance().getExternalContext().redirect(fileDownloadUrl);
- } catch (IOException ex) {
- logger.info("Failed to issue a redirect to file download url.");
- }
- //return fileDownloadUrl;
- }
-
- public String getApiTokenKey() {
- ApiToken apiToken;
-
- if (session.getUser() == null) {
- // ?
- return null;
- }
- if (isSessionUserAuthenticated()) {
- AuthenticatedUser au = (AuthenticatedUser) session.getUser();
- apiToken = authService.findApiTokenByUser(au);
- if (apiToken != null) {
- return "key=" + apiToken.getTokenString();
- }
- // Generate if not available?
- // Or should it just be generated inside the authService
- // automatically?
- apiToken = authService.generateApiTokenForUser(au);
- if (apiToken != null) {
- return "key=" + apiToken.getTokenString();
- }
- }
- return "";
-
- }
-
private void resetVersionUI() {
datasetVersionUI = datasetVersionUI.initDatasetVersionUI(workingVersion, true);
@@ -2133,13 +1610,10 @@ public void refresh() {
-
if (readOnly) {
datafileService.findFileMetadataOptimizedExperimental(dataset);
- fileMetadatasSearch = workingVersion.getFileMetadatas();
- } else {
- fileMetadatasSearch = workingVersion.getFileMetadatasSorted();
- }
+ }
+ fileMetadatasSearch = workingVersion.getFileMetadatasSorted();
displayCitation = dataset.getCitation(true, workingVersion);
stateChanged = false;
@@ -2241,7 +1715,6 @@ public void setSelectedNonDownloadableFiles(List selectedNonDownlo
this.selectedNonDownloadableFiles = selectedNonDownloadableFiles;
}
-
public void validateFilesForDownload(boolean guestbookRequired){
setSelectedDownloadableFiles(new ArrayList<>());
@@ -2255,7 +1728,7 @@ public void validateFilesForDownload(boolean guestbookRequired){
for (FileMetadata fmd : this.selectedFiles){
- if(canDownloadFile(fmd)){
+ if(this.fileDownloadHelper.canDownloadFile(fmd)){
getSelectedDownloadableFiles().add(fmd);
} else {
getSelectedNonDownloadableFiles().add(fmd);
@@ -2264,9 +1737,9 @@ public void validateFilesForDownload(boolean guestbookRequired){
if(!getSelectedDownloadableFiles().isEmpty() && getSelectedNonDownloadableFiles().isEmpty()){
if (guestbookRequired){
- initGuestbookMultipleResponse();
+ modifyGuestbookMultipleResponse();
} else{
- startMultipleFileDownload();
+ startMultipleFileDownload(false);
}
}
@@ -2331,6 +1804,18 @@ public String getSelectedFilesIdsString() {
return downloadIdString;
}
+ // helper Method
+ public String getSelectedDownloadableFilesIdsString() {
+ String downloadIdString = "";
+ for (FileMetadata fmd : this.selectedDownloadableFiles){
+ if (!StringUtil.isEmpty(downloadIdString)) {
+ downloadIdString += ",";
+ }
+ downloadIdString += fmd.getDataFile().getId();
+ }
+ return downloadIdString;
+ }
+
// helper Method
public String getSelectedFilesIdsStringForDownload() {
String downloadIdString = "";
@@ -2788,37 +2273,6 @@ public String cancel() {
return returnToLatestVersion();
}
- public boolean isDuplicate(FileMetadata fileMetadata) {
- String thisMd5 = fileMetadata.getDataFile().getChecksumValue();
- if (thisMd5 == null) {
- return false;
- }
-
- Map MD5Map = new HashMap();
-
- // TODO:
- // think of a way to do this that doesn't involve populating this
- // map for every file on the page?
- // man not be that much of a problem, if we paginate and never display
- // more than a certain number of files... Still, needs to be revisited
- // before the final 4.0.
- // -- L.A. 4.0
- Iterator fmIt = workingVersion.getFileMetadatas().iterator();
- while (fmIt.hasNext()) {
- FileMetadata fm = fmIt.next();
- String md5 = fm.getDataFile().getChecksumValue();
- if (md5 != null) {
- if (MD5Map.get(md5) != null) {
- MD5Map.put(md5, MD5Map.get(md5).intValue() + 1);
- } else {
- MD5Map.put(md5, 1);
- }
- }
- }
-
- return MD5Map.get(thisMd5) != null && MD5Map.get(thisMd5).intValue() > 1;
- }
-
private HttpClient getClient() {
// TODO:
// cache the http client? -- L.A. 4.0 alpha
@@ -2906,7 +2360,7 @@ public List getVersionTabListForPostLoad(){
}
public void setVersionTabListForPostLoad(List versionTabListForPostLoad) {
-
+
this.versionTabListForPostLoad = versionTabListForPostLoad;
}
@@ -2927,11 +2381,10 @@ public Integer getCompareVersionsCount() {
* See: dataset-versions.xhtml, remoteCommand 'postLoadVersionTablList'
*/
public void postLoadSetVersionTabList(){
-
- if (this.getVersionTabList().isEmpty()){
+
+ if (this.getVersionTabList().isEmpty() && workingVersion.isDeaccessioned()){
setVersionTabList(resetVersionTabList());
}
-
this.setVersionTabListForPostLoad(this.getVersionTabList());
@@ -2985,60 +2438,13 @@ public DatasetVersionDifference getDatasetVersionDifference() {
public void setDatasetVersionDifference(DatasetVersionDifference datasetVersionDifference) {
this.datasetVersionDifference = datasetVersionDifference;
}
-
- private void createSilentGuestbookEntry(FileMetadata fileMetadata, String format){
- initGuestbookResponse(fileMetadata, format, null);
- Command cmd;
- try {
- if (this.guestbookResponse != null) {
- cmd = new CreateGuestbookResponseCommand(dvRequestService.getDataverseRequest(), guestbookResponse, dataset);
- commandEngine.submit(cmd);
- } else {
- logger.severe("No Silent/Default Guestbook response made. No response to save - probably because version is DRAFT - not certain ");
- }
- } catch (CommandException ex) {
- FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Guestbook Response Save Failed", " - " + ex.toString()));
- logger.severe(ex.getMessage());
- }
- }
-
- //public String startMultipleFileDownload (){
- public void startMultipleFileDownload (){
+ public void startMultipleFileDownload (Boolean writeGuestbook){
-
- for (FileMetadata fmd : this.selectedDownloadableFiles) {
- if (canDownloadFile(fmd)) {
- // todo: cleanup this: "create" method doesn't necessarily
- // mean a response wikk be created (e.g. when dataset in draft)
- createSilentGuestbookEntry(fmd, "");
- }
- }
+ fileDownloadService.callDownloadServlet(getDownloadableFilesIdsString(), writeGuestbook);
- //return
- callDownloadServlet(getDownloadableFilesIdsString());
-
- }
-
- //public String startFileDownload(FileMetadata fileMetadata, String format) {
- public void startFileDownload(FileMetadata fileMetadata, String format) {
- logger.fine("starting file download for filemetadata "+fileMetadata.getId()+", datafile "+fileMetadata.getDataFile().getId());
- createSilentGuestbookEntry(fileMetadata, format);
- logger.fine("created guestbook entry for filemetadata "+fileMetadata.getId()+", datafile "+fileMetadata.getDataFile().getId());
- callDownloadServlet(format, fileMetadata.getDataFile().getId());
- logger.fine("issued file download redirect for filemetadata "+fileMetadata.getId()+", datafile "+fileMetadata.getDataFile().getId());
- }
-
- private String downloadFormat;
-
- public String getDownloadFormat() {
- return downloadFormat;
- }
-
- public void setDownloadFormat(String downloadFormat) {
- this.downloadFormat = downloadFormat;
}
-
+
private String downloadType = "";
public String getDownloadType() {
@@ -3049,23 +2455,17 @@ public void setDownloadType(String downloadType) {
this.downloadType = downloadType;
}
-
- public void initGuestbookResponse(FileMetadata fileMetadata){
- initGuestbookResponse(fileMetadata, "", null);
- }
-
- public void initGuestbookResponse(FileMetadata fileMetadata, String downloadType){
- initGuestbookResponse(fileMetadata, downloadType, null);
- }
- public void initGuestbookMultipleResponse(){
+ public void modifyGuestbookMultipleResponse(){
if (this.selectedFiles.isEmpty()) {
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("PF('selectFilesForDownload').show()");
return;
}
- initGuestbookResponse(null, "download", null);
+ this.guestbookResponse = this.guestbookResponseService.modifySelectedFileIds(guestbookResponse, getSelectedDownloadableFilesIdsString());
+ this.guestbookResponse.setDownloadtype("Download");
+ this.guestbookResponse.setFileFormat("Download");
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("PF('downloadPopup').show();handleResizeDialog('downloadPopup');");
}
@@ -3075,84 +2475,11 @@ public void initGuestbookMultipleResponse(String selectedFileIds){
}
public void initGuestbookResponse(FileMetadata fileMetadata, String downloadFormat, String selectedFileIds) {
- if (fileMetadata != null){
- this.setSelectedDownloadFile(fileMetadata.getDataFile());
- }
- setDownloadFormat(downloadFormat);
- if (fileMetadata == null){
- setDownloadType("multiple");
- } else {
- setDownloadType("download");
- }
- if(this.workingVersion != null && this.workingVersion.isDraft()){
- this.guestbookResponse = null;
- return;
- }
- this.guestbookResponse = new GuestbookResponse();
- User user = session.getUser();
- if (this.dataset.getGuestbook() != null) {
- this.guestbookResponse.setGuestbook(this.dataset.getGuestbook());
- this.guestbookResponse.setName("");
- this.guestbookResponse.setEmail("");
- this.guestbookResponse.setInstitution("");
- this.guestbookResponse.setPosition("");
- this.guestbookResponse.setSessionId(session.toString());
- if (user.isAuthenticated()) {
- AuthenticatedUser aUser = (AuthenticatedUser) user;
- this.guestbookResponse.setName(aUser.getName());
- this.guestbookResponse.setAuthenticatedUser(aUser);
- this.guestbookResponse.setEmail(aUser.getEmail());
- this.guestbookResponse.setInstitution(aUser.getAffiliation());
- this.guestbookResponse.setPosition(aUser.getPosition());
- this.guestbookResponse.setSessionId(session.toString());
- }
- if (fileMetadata != null){
- this.guestbookResponse.setDataFile(fileMetadata.getDataFile());
- }
- } else {
- if (fileMetadata != null){
- this.guestbookResponse = guestbookResponseService.initDefaultGuestbookResponse(dataset, fileMetadata.getDataFile(), user, session);
- } else {
- this.guestbookResponse = guestbookResponseService.initDefaultGuestbookResponse(dataset, null, user, session);
- }
- }
- if (this.dataset.getGuestbook() != null && !this.dataset.getGuestbook().getCustomQuestions().isEmpty()) {
- this.guestbookResponse.setCustomQuestionResponses(new ArrayList());
- for (CustomQuestion cq : this.dataset.getGuestbook().getCustomQuestions()) {
- CustomQuestionResponse cqr = new CustomQuestionResponse();
- cqr.setGuestbookResponse(guestbookResponse);
- cqr.setCustomQuestion(cq);
- cqr.setResponse("");
- if (cq.getQuestionType().equals("options")) {
- //response select Items
- cqr.setResponseSelectItems(setResponseUISelectItems(cq));
- }
- this.guestbookResponse.getCustomQuestionResponses().add(cqr);
- }
- }
- this.guestbookResponse.setDownloadtype("Download");
- if(downloadFormat.toLowerCase().equals("subset")){
- this.guestbookResponse.setDownloadtype("Subset");
- setDownloadFormat("subset");
- setDownloadType("subset");
- }
- if(downloadFormat.toLowerCase().equals("explore")){
- setDownloadFormat("explore");
- setDownloadType("explore");
- this.guestbookResponse.setDownloadtype("Explore");
- }
- this.guestbookResponse.setDataset(dataset);
+ this.guestbookResponse = guestbookResponseService.initGuestbookResponse(fileMetadata, downloadFormat, selectedFileIds, session);
}
- private List setResponseUISelectItems(CustomQuestion cq) {
- List retList = new ArrayList();
- for (CustomQuestionValue cqv : cq.getCustomQuestionValues()) {
- SelectItem si = new SelectItem(cqv.getValueString(), cqv.getValueString());
- retList.add(si);
- }
- return retList;
- }
+
public void compareVersionDifferences() {
RequestContext requestContext = RequestContext.getCurrentInstance();
@@ -3247,118 +2574,6 @@ private List resetReleasedVersionTabList() {
return retList;
}
- public void downloadDatasetCitationXML() {
- downloadCitationXML(null);
- }
-
- public void downloadDatafileCitationXML(FileMetadata fileMetadata) {
- downloadCitationXML(fileMetadata);
- }
-
- public void downloadCitationXML(FileMetadata fileMetadata) {
-
- String xml = datasetService.createCitationXML(workingVersion, fileMetadata);
- FacesContext ctx = FacesContext.getCurrentInstance();
- HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
- response.setContentType("text/xml");
- String fileNameString = "";
- if (fileMetadata == null || fileMetadata.getLabel() == null) {
- // Dataset-level citation:
- fileNameString = "attachment;filename=" + getFileNameDOI() + ".xml";
- } else {
- // Datafile-level citation:
- fileNameString = "attachment;filename=" + getFileNameDOI() + "-" + fileMetadata.getLabel().replaceAll("\\.tab$", "-endnote.xml");
- }
- response.setHeader("Content-Disposition", fileNameString);
- try {
- ServletOutputStream out = response.getOutputStream();
- out.write(xml.getBytes());
- out.flush();
- ctx.responseComplete();
- } catch (Exception e) {
-
- }
- }
-
- private String getFileNameDOI() {
- Dataset ds = workingVersion.getDataset();
- return "DOI:" + ds.getAuthority() + "_" + ds.getIdentifier().toString();
- }
-
- public void downloadDatasetCitationRIS() {
-
- downloadCitationRIS(null);
-
- }
-
- public void downloadDatafileCitationRIS(FileMetadata fileMetadata) {
- downloadCitationRIS(fileMetadata);
- }
-
- public void downloadCitationRIS(FileMetadata fileMetadata) {
-
- String risFormatDowload = datasetService.createCitationRIS(workingVersion, fileMetadata);
- FacesContext ctx = FacesContext.getCurrentInstance();
- HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
- response.setContentType("application/download");
-
- String fileNameString = "";
- if (fileMetadata == null || fileMetadata.getLabel() == null) {
- // Dataset-level citation:
- fileNameString = "attachment;filename=" + getFileNameDOI() + ".ris";
- } else {
- // Datafile-level citation:
- fileNameString = "attachment;filename=" + getFileNameDOI() + "-" + fileMetadata.getLabel().replaceAll("\\.tab$", ".ris");
- }
- response.setHeader("Content-Disposition", fileNameString);
-
- try {
- ServletOutputStream out = response.getOutputStream();
- out.write(risFormatDowload.getBytes());
- out.flush();
- ctx.responseComplete();
- } catch (Exception e) {
-
- }
- }
-
- public void downloadDatasetCitationBibtex() {
-
- downloadCitationBibtex(null);
-
- }
-
- public void downloadDatafileCitationBibtex(FileMetadata fileMetadata) {
- downloadCitationBibtex(fileMetadata);
- }
-
- public void downloadCitationBibtex(FileMetadata fileMetadata) {
-
- String bibFormatDowload = new BibtexCitation(workingVersion).toString();
- FacesContext ctx = FacesContext.getCurrentInstance();
- HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
- response.setContentType("application/download");
-
- String fileNameString = "";
- if (fileMetadata == null || fileMetadata.getLabel() == null) {
- // Dataset-level citation:
- fileNameString = "attachment;filename=" + getFileNameDOI() + ".bib";
- } else {
- // Datafile-level citation:
- fileNameString = "attachment;filename=" + getFileNameDOI() + "-" + fileMetadata.getLabel().replaceAll("\\.tab$", ".bib");
- }
- response.setHeader("Content-Disposition", fileNameString);
-
- try {
- ServletOutputStream out = response.getOutputStream();
- out.write(bibFormatDowload.getBytes());
- out.flush();
- ctx.responseComplete();
- } catch (Exception e) {
-
- }
- }
-
public String getDatasetPublishCustomText(){
String datasetPublishCustomText = settingsService.getValueForKey(SettingsServiceBean.Key.DatasetPublishPopupCustomText);
if( datasetPublishCustomText!= null && !datasetPublishCustomText.isEmpty()){
@@ -3372,41 +2587,6 @@ public Boolean isDatasetPublishPopupCustomTextOnAllVersions(){
return settingsService.isTrueForKey(SettingsServiceBean.Key.DatasetPublishPopupCustomTextOnAllVersions, false);
}
- public String getDataExploreURL() {
- String TwoRavensUrl = settingsService.getValueForKey(SettingsServiceBean.Key.TwoRavensUrl);
-
- if (TwoRavensUrl != null && !TwoRavensUrl.equals("")) {
- return TwoRavensUrl;
- }
-
- return "";
- }
-
- public String getDataExploreURLComplete(Long fileid) {
- String TwoRavensUrl = settingsService.getValueForKey(SettingsServiceBean.Key.TwoRavensUrl);
- String TwoRavensDefaultLocal = "/dataexplore/gui.html?dfId=";
-
- if (TwoRavensUrl != null && !TwoRavensUrl.equals("")) {
- // If we have TwoRavensUrl set up as, as an optional
- // configuration service, it must mean that TwoRavens is sitting
- // on some remote server. And that in turn means that we must use
- // full URLs to pass data and metadata to it.
- // update: actually, no we don't want to use this "dataurl" notation.
- // switching back to the dfId=:
- // -- L.A. 4.1
- /*
- String tabularDataURL = getTabularDataFileURL(fileid);
- String tabularMetaURL = getVariableMetadataURL(fileid);
- return TwoRavensUrl + "?ddiurl=" + tabularMetaURL + "&dataurl=" + tabularDataURL + "&" + getApiTokenKey();
- */
- return TwoRavensUrl + "?dfId=" + fileid + "&" + getApiTokenKey();
- }
-
- // For a local TwoRavens setup it's enough to call it with just
- // the file id:
- return TwoRavensDefaultLocal + fileid + "&" + getApiTokenKey();
- }
-
public String getVariableMetadataURL(Long fileid) {
String myHostURL = getDataverseSiteUrl();
String metaURL = myHostURL + "/api/meta/datafile/" + fileid;
@@ -3469,7 +2649,15 @@ public void setFileMetadataSelected(FileMetadata fm){
public void setFileMetadataSelected(FileMetadata fm, String guestbook) {
if (guestbook != null) {
if (guestbook.equals("create")) {
- createSilentGuestbookEntry(fm, "Subset");
+ //
+ /*
+ FIX ME guestbook entry for subsetting
+ */
+
+
+
+
+ // guestbookResponseService.createSilentGuestbookEntry(fm, "Subset");
} else {
initGuestbookResponse(fm, "Subset", null);
}
@@ -4029,33 +3217,10 @@ public void saveAdvancedOptions() {
fileMetadataSelectedForIngestOptionsPopup = null;
}
- public String getFileDateToDisplay(FileMetadata fileMetadata) {
- Date fileDate = null;
- DataFile datafile = fileMetadata.getDataFile();
- if (datafile != null) {
- boolean fileHasBeenReleased = datafile.isReleased();
- if (fileHasBeenReleased) {
- Timestamp filePublicationTimestamp = datafile.getPublicationDate();
- if (filePublicationTimestamp != null) {
- fileDate = filePublicationTimestamp;
- }
- } else {
- Timestamp fileCreateTimestamp = datafile.getCreateDate();
- if (fileCreateTimestamp != null) {
- fileDate = fileCreateTimestamp;
- }
- }
- }
- if (fileDate != null) {
- return displayDateFormat.format(fileDate);
- }
-
- return "";
- }
public boolean isDownloadButtonAvailable(){
for (FileMetadata fmd : workingVersion.getFileMetadatas()) {
- if (canDownloadFile(fmd)) {
+ if (this.fileDownloadHelper.canDownloadFile(fmd)) {
return true;
}
}
@@ -4073,7 +3238,7 @@ public boolean isFileAccessRequestMultiButtonRequired(){
// return false;
}
for (FileMetadata fmd : workingVersion.getFileMetadatas()){
- if (!canDownloadFile(fmd)){
+ if (!this.fileDownloadHelper.canDownloadFile(fmd)){
return true;
}
}
@@ -4088,7 +3253,7 @@ public boolean isFileAccessRequestMultiButtonEnabled(){
return false;
}
for (FileMetadata fmd : this.selectedRestrictedFiles){
- if (!canDownloadFile(fmd)){
+ if (!this.fileDownloadHelper.canDownloadFile(fmd)){
return true;
}
}
@@ -4101,7 +3266,7 @@ public boolean isDownloadAllButtonEnabled() {
if (downloadButtonAllEnabled == null) {
for (FileMetadata fmd : workingVersion.getFileMetadatas()) {
- if (!canDownloadFile(fmd)) {
+ if (!this.fileDownloadHelper.canDownloadFile(fmd)) {
downloadButtonAllEnabled = false;
break;
}
@@ -4117,7 +3282,7 @@ public boolean isDownloadSelectedButtonEnabled(){
return false;
}
for (FileMetadata fmd : this.selectedFiles){
- if (canDownloadFile(fmd)){
+ if (this.fileDownloadHelper.canDownloadFile(fmd)){
return true;
}
}
@@ -4133,7 +3298,7 @@ public boolean isFileAccessRequestMultiSignUpButtonRequired(){
return false;
}
for (FileMetadata fmd : workingVersion.getFileMetadatas()){
- if (!canDownloadFile(fmd)){
+ if (!this.fileDownloadHelper.canDownloadFile(fmd)){
return true;
}
}
@@ -4152,7 +3317,7 @@ public boolean isFileAccessRequestMultiSignUpButtonEnabled(){
return false;
}
for (FileMetadata fmd : this.selectedRestrictedFiles){
- if (!canDownloadFile(fmd)){
+ if (!this.fileDownloadHelper.canDownloadFile(fmd)){
return true;
}
}
@@ -4160,33 +3325,7 @@ public boolean isFileAccessRequestMultiSignUpButtonEnabled(){
}
public boolean isDownloadPopupRequired() {
- // Each of these conditions is sufficient reason to have to
- // present the user with the popup:
-
- //0. if version is draft then Popup "not required"
- if (!workingVersion.isReleased()){
- return false;
- }
- // 1. License and Terms of Use:
- if (workingVersion.getTermsOfUseAndAccess() != null) {
- if (!TermsOfUseAndAccess.License.CC0.equals(workingVersion.getTermsOfUseAndAccess().getLicense())
- && !(workingVersion.getTermsOfUseAndAccess().getTermsOfUse() == null
- || workingVersion.getTermsOfUseAndAccess().getTermsOfUse().equals(""))) {
- return true;
- }
-
- // 2. Terms of Access:
- if (!(workingVersion.getTermsOfUseAndAccess().getTermsOfAccess() == null) && !workingVersion.getTermsOfUseAndAccess().getTermsOfAccess().equals("")) {
- return true;
- }
- }
-
- // 3. Guest Book:
- if (dataset.getGuestbook() != null && dataset.getGuestbook().isEnabled() && dataset.getGuestbook().getDataverse() != null ) {
- return true;
- }
-
- return false;
+ return fileDownloadService.isDownloadPopupRequired(workingVersion);
}
public String requestAccessMultipleFiles(String fileIdString) {
@@ -4375,5 +3514,49 @@ public boolean isUserCanCreatePrivateURL() {
public String getPrivateUrlLink(PrivateUrl privateUrl) {
return privateUrl.getLink();
}
+
+
+ public FileDownloadHelper getFileDownloadHelper() {
+ return fileDownloadHelper;
+ }
+
+ public void setFileDownloadHelper(FileDownloadHelper fileDownloadHelper) {
+ this.fileDownloadHelper = fileDownloadHelper;
+ }
+
+
+ public FileDownloadServiceBean getFileDownloadService() {
+ return fileDownloadService;
+ }
+
+ public void setFileDownloadService(FileDownloadServiceBean fileDownloadService) {
+ this.fileDownloadService = fileDownloadService;
+ }
+
+
+ public GuestbookResponseServiceBean getGuestbookResponseService() {
+ return guestbookResponseService;
+ }
+
+ public void setGuestbookResponseService(GuestbookResponseServiceBean guestbookResponseService) {
+ this.guestbookResponseService = guestbookResponseService;
+ }
+
+
+ public WorldMapPermissionHelper getWorldMapPermissionHelper() {
+ return worldMapPermissionHelper;
+ }
+
+ public void setWorldMapPermissionHelper(WorldMapPermissionHelper worldMapPermissionHelper) {
+ this.worldMapPermissionHelper = worldMapPermissionHelper;
+ }
+
+ public TwoRavensHelper getTwoRavensHelper() {
+ return twoRavensHelper;
+ }
+
+ public void setTwoRavensHelper(TwoRavensHelper twoRavensHelper) {
+ this.twoRavensHelper = twoRavensHelper;
+ }
}
diff --git a/src/main/java/edu/harvard/iq/dataverse/DatasetVersionDifference.java b/src/main/java/edu/harvard/iq/dataverse/DatasetVersionDifference.java
index 09cc4ad50b2..20df6c378a4 100644
--- a/src/main/java/edu/harvard/iq/dataverse/DatasetVersionDifference.java
+++ b/src/main/java/edu/harvard/iq/dataverse/DatasetVersionDifference.java
@@ -69,6 +69,17 @@ public DatasetVersionDifference(DatasetVersion newVersion, DatasetVersion origin
}
}
+
+ // TODO: ?
+ // It looks like we are going through the filemetadatas in both versions,
+ // *sequentially* (i.e. at the cost of O(N*M)), to select the lists of
+ // changed, deleted and added files between the 2 versions... But why
+ // are we doing it, if we are doing virtually the same thing inside
+ // the initDatasetFilesDifferenceList(), below - but in a more efficient
+ // way (sorting both lists, then goint through them in parallel, at the
+ // cost of (N+M) max.?
+ // -- 4.6 Nov. 2016
+
for (FileMetadata fmdo : originalVersion.getFileMetadatas()) {
boolean deleted = true;
for (FileMetadata fmdn : newVersion.getFileMetadatas()) {
@@ -648,6 +659,7 @@ private void initDatasetFilesDifferencesList() {
// same study file, the file metadatas ARE version-specific, so some of
// the fields there (filename, etc.) may be different. If this is the
// case, we want to display these differences as well.
+
if (originalVersion.getFileMetadatas().size() == 0 && newVersion.getFileMetadatas().size() == 0) {
noFileDifferencesFoundLabel = "No data files in either version of the study";
return;
@@ -659,50 +671,62 @@ private void initDatasetFilesDifferencesList() {
FileMetadata fm1;
FileMetadata fm2;
- Collections.sort(originalVersion.getFileMetadatas(), new Comparator() {
- public int compare(FileMetadata l1, FileMetadata l2) {
- FileMetadata fm1 = l1; //(DatasetField[]) l1.get(0);
- FileMetadata fm2 = l2;
- int a = fm1.getDataFile().getId().intValue();
- int b = fm2.getDataFile().getId().intValue();
- return Integer.valueOf(a).compareTo(Integer.valueOf(b));
- }
- });
-
- // Here's a potential problem: this new version may have been created
- // specifically because new files are being added to the dataset.
- // In which case there may be files associated with this new version
- // with no database ids - since they haven't been saved yet.
- // So if we try to sort the files in the version the way we did above,
- // by ID, it may fail with a null pointer.
- // To solve this, we should simply check if the file has the id; and if not,
- // sort it higher than any file with an id - because it is a most recently
- // added file. Since we are only doing this for the purposes of generating
- // version differences, this should be OK.
- // -- L.A. Aug. 2014
-
- Collections.sort(newVersion.getFileMetadatas(), new Comparator() {
- public int compare(FileMetadata l1, FileMetadata l2) {
- FileMetadata fm1 = l1; //(DatasetField[]) l1.get(0);
- FileMetadata fm2 = l2;
- Long a = fm1.getDataFile().getId();
- Long b = fm2.getDataFile().getId();
-
- if (a == null && b == null) {
- return 0;
- } else if (a == null) {
- return 1;
- } else if (b == null) {
- return -1;
- }
- return a.compareTo(b);
+ // We also have to be careful sorting this FileMetadatas. If we sort the
+ // lists as they are still attached to their respective versions, we may end
+ // up messing up the page, which was rendered based on the specific order
+ // of these in the working version!
+ // So the right way of doing this is to create defensive copies of the
+ // lists; extra memory, but safer.
+ // -- L.A. Nov. 2016
+
+ List fileMetadatasNew = new ArrayList<>(newVersion.getFileMetadatas());
+ List fileMetadatasOriginal = new ArrayList<>(originalVersion.getFileMetadatas());
+
+ Collections.sort(fileMetadatasOriginal, new Comparator() {
+ public int compare(FileMetadata l1, FileMetadata l2) {
+ FileMetadata fm1 = l1; //(DatasetField[]) l1.get(0);
+ FileMetadata fm2 = l2;
+ int a = fm1.getDataFile().getId().intValue();
+ int b = fm2.getDataFile().getId().intValue();
+ return Integer.valueOf(a).compareTo(Integer.valueOf(b));
+ }
+ });
+
+ // Here's a potential problem: this new version may have been created
+ // specifically because new files are being added to the dataset.
+ // In which case there may be files associated with this new version
+ // with no database ids - since they haven't been saved yet.
+ // So if we try to sort the files in the version the way we did above,
+ // by ID, it may fail with a null pointer.
+ // To solve this, we should simply check if the file has the id; and if not,
+ // sort it higher than any file with an id - because it is a most recently
+ // added file. Since we are only doing this for the purposes of generating
+ // version differences, this should be OK.
+ // -- L.A. Aug. 2014
+
+
+ Collections.sort(fileMetadatasNew, new Comparator() {
+ public int compare(FileMetadata l1, FileMetadata l2) {
+ FileMetadata fm1 = l1; //(DatasetField[]) l1.get(0);
+ FileMetadata fm2 = l2;
+ Long a = fm1.getDataFile().getId();
+ Long b = fm2.getDataFile().getId();
+
+ if (a == null && b == null) {
+ return 0;
+ } else if (a == null) {
+ return 1;
+ } else if (b == null) {
+ return -1;
}
- });
+ return a.compareTo(b);
+ }
+ });
- while (i < originalVersion.getFileMetadatas().size()
- && j < newVersion.getFileMetadatas().size()) {
- fm1 = originalVersion.getFileMetadatas().get(i);
- fm2 = newVersion.getFileMetadatas().get(j);
+ while (i < fileMetadatasOriginal.size()
+ && j < fileMetadatasNew.size()) {
+ fm1 = fileMetadatasOriginal.get(i);
+ fm2 = fileMetadatasNew.get(j);
if (fm2.getDataFile().getId() != null && fm1.getDataFile().getId().compareTo(fm2.getDataFile().getId()) == 0) {
// The 2 versions share the same study file;
@@ -739,8 +763,8 @@ public int compare(FileMetadata l1, FileMetadata l2) {
// We've reached the end of at least one file list.
// Whatever files are left on either of the 2 lists are automatically "different"
// between the 2 versions.
- while (i < originalVersion.getFileMetadatas().size()) {
- fm1 = originalVersion.getFileMetadatas().get(i);
+ while (i < fileMetadatasOriginal.size()) {
+ fm1 = fileMetadatasOriginal.get(i);
datasetFileDifferenceItem fdi = selectFileMetadataDiffs(fm1, null);
fdi.setFileId(fm1.getDataFile().getId().toString());
fdi.setFileChecksumType(fm1.getDataFile().getChecksumType());
@@ -750,8 +774,8 @@ public int compare(FileMetadata l1, FileMetadata l2) {
i++;
}
- while (j < newVersion.getFileMetadatas().size()) {
- fm2 = newVersion.getFileMetadatas().get(j);
+ while (j < fileMetadatasNew.size()) {
+ fm2 = fileMetadatasNew.get(j);
datasetFileDifferenceItem fdi = selectFileMetadataDiffs(null, fm2);
if (fm2.getDataFile().getId() != null) {
fdi.setFileId(fm2.getDataFile().getId().toString());
diff --git a/src/main/java/edu/harvard/iq/dataverse/EditDatafilesPage.java b/src/main/java/edu/harvard/iq/dataverse/EditDatafilesPage.java
index 86696771258..1e612a33cee 100644
--- a/src/main/java/edu/harvard/iq/dataverse/EditDatafilesPage.java
+++ b/src/main/java/edu/harvard/iq/dataverse/EditDatafilesPage.java
@@ -149,6 +149,9 @@ public enum FileEditMode {
private String persistentId;
+ private String versionString = "";
+
+
private boolean saveEnabled = false;
// Used to store results of permissions checks
@@ -416,6 +419,13 @@ public String init() {
if (fileMetadatas.size() < 1) {
return permissionsWrapper.notFound();
}
+
+ if (FileEditMode.SINGLE == mode){
+ if (fileMetadatas.get(0).getDatasetVersion().getId() != null){
+ versionString = "DRAFT";
+ }
+ }
+
}
saveEnabled = true;
@@ -988,7 +998,8 @@ public String save() {
// the individual File Landing page, we want to redirect back to
// the landing page. BUT ONLY if the file still exists - i.e., if
// the user hasn't just deleted it!
- return returnToFileLandingPage(fileMetadatas.get(0).getId());
+ versionString = "DRAFT";
+ return returnToFileLandingPage();
}
//if (newDraftVersion) {
@@ -1009,24 +1020,29 @@ private String returnToDraftVersion(){
return "/dataset.xhtml?persistentId=" + dataset.getGlobalId() + "&version=DRAFT&faces-redirect=true";
}
- private String returnToDraftVersionById() {
- return "/dataset.xhtml?versionId=" + workingVersion.getId() + "&faces-redirect=true";
- }
-
private String returnToDatasetOnly(){
dataset = datasetService.find(dataset.getId());
return "/dataset.xhtml?persistentId=" + dataset.getGlobalId() + "&faces-redirect=true";
}
- private String returnToFileLandingPage(Long fileId) {
- return "/file.xhtml?fileId=" + fileId + "&datasetVersionId=" + workingVersion.getId() + "&faces-redirect=true";
+ private String returnToFileLandingPage() {
+
+ Long fileId = fileMetadatas.get(0).getDataFile().getId();
+ if (versionString.equals("DRAFT")){
+ return "/file.xhtml?fileId=" + fileId + "&version=DRAFT&faces-redirect=true";
+ }
+ return "/file.xhtml?fileId=" + fileId + "&faces-redirect=true";
+
}
public String cancel() {
+ if (mode == FileEditMode.SINGLE) {
+ return returnToFileLandingPage();
+ }
if (workingVersion.getId() != null) {
return returnToDraftVersion();
}
- return returnToDatasetOnly();
+ return returnToDatasetOnly();
}
public boolean isDuplicate(FileMetadata fileMetadata) {
@@ -1849,30 +1865,6 @@ public void saveAdvancedOptions() {
fileMetadataSelectedForIngestOptionsPopup = null;
}
- public String getFileDateToDisplay(FileMetadata fileMetadata) {
- Date fileDate = null;
- DataFile datafile = fileMetadata.getDataFile();
- if (datafile != null) {
- boolean fileHasBeenReleased = datafile.isReleased();
- if (fileHasBeenReleased) {
- Timestamp filePublicationTimestamp = datafile.getPublicationDate();
- if (filePublicationTimestamp != null) {
- fileDate = filePublicationTimestamp;
- }
- } else {
- Timestamp fileCreateTimestamp = datafile.getCreateDate();
- if (fileCreateTimestamp != null) {
- fileDate = fileCreateTimestamp;
- }
- }
- }
- if (fileDate != null) {
- return displayDateFormat.format(fileDate);
- }
-
- return "";
- }
-
private void populateFileMetadatas() {
if (selectedFileIdsList != null) {
diff --git a/src/main/java/edu/harvard/iq/dataverse/FileDownloadHelper.java b/src/main/java/edu/harvard/iq/dataverse/FileDownloadHelper.java
new file mode 100644
index 00000000000..b6e34997008
--- /dev/null
+++ b/src/main/java/edu/harvard/iq/dataverse/FileDownloadHelper.java
@@ -0,0 +1,202 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package edu.harvard.iq.dataverse;
+
+import edu.harvard.iq.dataverse.authorization.Permission;
+import edu.harvard.iq.dataverse.authorization.users.GuestUser;
+import java.util.HashMap;
+import java.util.Map;
+import javax.ejb.EJB;
+import javax.faces.view.ViewScoped;
+import javax.inject.Inject;
+import javax.inject.Named;
+
+/**
+ *
+ * @author skraffmi
+ *
+ *
+ */
+ @ViewScoped
+ @Named
+public class FileDownloadHelper implements java.io.Serializable {
+
+ @Inject
+ DataverseSession session;
+
+ @EJB
+ PermissionServiceBean permissionService;
+
+
+ private final Map fileDownloadPermissionMap = new HashMap<>(); // { FileMetadata.id : Boolean }
+ private final Map datasetPermissionMap = new HashMap<>(); // { Permission human_name : Boolean }
+
+
+
+ /**
+ * WARNING: Before calling this, make sure the user has download
+ * permission for the file!! (See DatasetPage.canDownloadFile())
+ *
+ * Should there be a Explore WorldMap Button for this file?
+ * See table in: https://github.com/IQSS/dataverse/issues/1618
+ *
+ * (1) Does the file have MapLayerMetadata?
+ * (2) Are the proper settings in place
+ *
+ * @param fm fileMetadata
+ * @return boolean
+ */
+ public boolean canDownloadFile(FileMetadata fileMetadata){
+ if (fileMetadata == null){
+ return false;
+ }
+
+ if ((fileMetadata.getId() == null) || (fileMetadata.getDataFile().getId() == null)){
+ return false;
+ }
+
+ // --------------------------------------------------------------------
+ // Grab the fileMetadata.id and restriction flag
+ // --------------------------------------------------------------------
+ Long fid = fileMetadata.getId();
+ //logger.info("calling candownloadfile on filemetadata "+fid);
+ boolean isRestrictedFile = fileMetadata.isRestricted();
+
+ // --------------------------------------------------------------------
+ // Has this file been checked? Look at the DatasetPage hash
+ // --------------------------------------------------------------------
+ if (this.fileDownloadPermissionMap.containsKey(fid)){
+ // Yes, return previous answer
+ //logger.info("using cached result for candownloadfile on filemetadata "+fid);
+ return this.fileDownloadPermissionMap.get(fid);
+ }
+ //----------------------------------------------------------------------
+ //(0) Before we do any testing - if version is deaccessioned and user
+ // does not have edit dataset permission then may download
+ //----------------------------------------------------------------------
+
+ if (fileMetadata.getDatasetVersion().isDeaccessioned()) {
+ if (this.doesSessionUserHavePermission(Permission.EditDataset, fileMetadata)) {
+ // Yes, save answer and return true
+ this.fileDownloadPermissionMap.put(fid, true);
+ return true;
+ } else {
+ this.fileDownloadPermissionMap.put(fid, false);
+ return false;
+ }
+ }
+
+ // --------------------------------------------------------------------
+ // (1) Is the file Unrestricted ?
+ // --------------------------------------------------------------------
+ if (!isRestrictedFile){
+ // Yes, save answer and return true
+ this.fileDownloadPermissionMap.put(fid, true);
+ return true;
+ }
+
+ // --------------------------------------------------------------------
+ // Conditions (2) through (4) are for Restricted files
+ // --------------------------------------------------------------------
+
+ // --------------------------------------------------------------------
+ // (2) In Dataverse 4.3 and earlier we required that users be authenticated
+ // to download files, but in developing the Private URL feature, we have
+ // added a new subclass of "User" called "PrivateUrlUser" that returns false
+ // for isAuthenticated but that should be able to download restricted files
+ // when given the Member role (which includes the DownloadFile permission).
+ // This is consistent with how Builtin and Shib users (both are
+ // AuthenticatedUsers) can download restricted files when they are granted
+ // the Member role. For this reason condition 2 has been changed. Previously,
+ // we required isSessionUserAuthenticated to return true. Now we require
+ // that the User is not an instance of GuestUser, which is similar in
+ // spirit to the previous check.
+ // --------------------------------------------------------------------
+
+ if (session.getUser() instanceof GuestUser){
+ this.fileDownloadPermissionMap.put(fid, false);
+ return false;
+ }
+
+
+ // --------------------------------------------------------------------
+ // (3) Does the User have DownloadFile Permission at the **Dataset** level
+ // --------------------------------------------------------------------
+
+
+ if (this.doesSessionUserHavePermission(Permission.DownloadFile, fileMetadata)){
+ // Yes, save answer and return true
+ this.fileDownloadPermissionMap.put(fid, true);
+ return true;
+ }
+
+
+ // --------------------------------------------------------------------
+ // (4) Does the user has DownloadFile permission on the DataFile
+ // --------------------------------------------------------------------
+ /*
+ if (this.permissionService.on(fileMetadata.getDataFile()).has(Permission.DownloadFile)){
+ this.fileDownloadPermissionMap.put(fid, true);
+ return true;
+ }
+ */
+
+ // --------------------------------------------------------------------
+ // (6) No download....
+ // --------------------------------------------------------------------
+ this.fileDownloadPermissionMap.put(fid, false);
+
+ return false;
+ }
+
+ public boolean doesSessionUserHavePermission(Permission permissionToCheck, FileMetadata fileMetadata){
+ if (permissionToCheck == null){
+ return false;
+ }
+
+ DvObject objectToCheck = null;
+
+ if (permissionToCheck.equals(Permission.EditDataset)){
+ objectToCheck = fileMetadata.getDatasetVersion().getDataset();
+ } else if (permissionToCheck.equals(Permission.DownloadFile)){
+ objectToCheck = fileMetadata.getDataFile();
+ }
+
+ if (objectToCheck == null){
+ return false;
+ }
+
+
+
+ String permName = permissionToCheck.getHumanName();
+
+ // Has this check already been done?
+ //
+ if (this.datasetPermissionMap.containsKey(permName)){
+ // Yes, return previous answer
+ return this.datasetPermissionMap.get(permName);
+ }
+
+ // Check the permission
+ //
+ boolean hasPermission = this.permissionService.userOn(this.session.getUser(), objectToCheck).has(permissionToCheck);
+
+ // Save the permission
+ this.datasetPermissionMap.put(permName, hasPermission);
+
+ // return true/false
+ return hasPermission;
+ }
+
+ public DataverseSession getSession() {
+ return session;
+ }
+
+ public void setSession(DataverseSession session) {
+ this.session = session;
+ }
+
+}
diff --git a/src/main/java/edu/harvard/iq/dataverse/FileDownloadServiceBean.java b/src/main/java/edu/harvard/iq/dataverse/FileDownloadServiceBean.java
new file mode 100644
index 00000000000..5fb8a48b147
--- /dev/null
+++ b/src/main/java/edu/harvard/iq/dataverse/FileDownloadServiceBean.java
@@ -0,0 +1,421 @@
+package edu.harvard.iq.dataverse;
+
+import edu.harvard.iq.dataverse.authorization.Permission;
+import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
+import edu.harvard.iq.dataverse.datasetutility.TwoRavensHelper;
+import edu.harvard.iq.dataverse.datasetutility.WorldMapPermissionHelper;
+import edu.harvard.iq.dataverse.engine.command.Command;
+import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
+import edu.harvard.iq.dataverse.engine.command.impl.CreateGuestbookResponseCommand;
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.logging.Logger;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.faces.context.ExternalContext;
+import javax.faces.context.FacesContext;
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import org.primefaces.context.RequestContext;
+
+/**
+ *
+ * @author skraffmi
+ * Handles All File Download processes
+ * including Guestbook responses
+ */
+@Stateless
+@Named
+public class FileDownloadServiceBean implements java.io.Serializable {
+
+ @PersistenceContext(unitName = "VDCNet-ejbPU")
+ private EntityManager em;
+
+ @EJB
+ GuestbookResponseServiceBean guestbookResponseService;
+ @EJB
+ DatasetServiceBean datasetService;
+ @EJB
+ DatasetVersionServiceBean datasetVersionService;
+ @EJB
+ DataFileServiceBean datafileService;
+ @EJB
+ PermissionServiceBean permissionService;
+ @EJB
+ DataverseServiceBean dataverseService;
+ @EJB
+ UserNotificationServiceBean userNotificationService;
+
+ @Inject
+ DataverseSession session;
+
+ @EJB
+ EjbDataverseEngine commandEngine;
+
+ @Inject
+ DataverseRequestServiceBean dvRequestService;
+
+ @Inject TwoRavensHelper twoRavensHelper;
+ @Inject WorldMapPermissionHelper worldMapPermissionHelper;
+
+ private static final Logger logger = Logger.getLogger(FileDownloadServiceBean.class.getCanonicalName());
+
+
+ public void writeGuestbookAndStartDownload(GuestbookResponse guestbookResponse){
+ if (guestbookResponse != null && guestbookResponse.getDataFile() != null ){
+ writeGuestbookResponseRecord(guestbookResponse);
+ callDownloadServlet(guestbookResponse.getFileFormat(), guestbookResponse.getDataFile().getId(), guestbookResponse.isWriteResponse());
+ }
+
+ if (guestbookResponse != null && guestbookResponse.getSelectedFileIds() != null ){
+ List list = new ArrayList<>(Arrays.asList(guestbookResponse.getSelectedFileIds().split(",")));
+
+ for (String idAsString : list) {
+ DataFile df = datafileService.findCheapAndEasy(new Long(idAsString)) ;
+ if (df != null) {
+ guestbookResponse.setDataFile(df);
+ writeGuestbookResponseRecord(guestbookResponse);
+ }
+ }
+
+ callDownloadServlet(guestbookResponse.getSelectedFileIds(), true);
+ }
+
+
+ }
+
+ public void writeGuestbookResponseRecord(GuestbookResponse guestbookResponse) {
+
+ try {
+ Command cmd = new CreateGuestbookResponseCommand(dvRequestService.getDataverseRequest(), guestbookResponse, guestbookResponse.getDataset());
+ commandEngine.submit(cmd);
+ } catch (CommandException e) {
+ //if an error occurs here then download won't happen no need for response recs...
+
+ }
+
+ }
+
+ public void callDownloadServlet(String multiFileString, Boolean gbRecordsWritten){
+
+ String fileDownloadUrl = "/api/access/datafiles/" + multiFileString;
+ if (gbRecordsWritten){
+ fileDownloadUrl += "?gbrecs=true";
+ }
+ try {
+ FacesContext.getCurrentInstance().getExternalContext().redirect(fileDownloadUrl);
+ } catch (IOException ex) {
+ logger.info("Failed to issue a redirect to file download url.");
+ }
+
+ //return fileDownloadUrl;
+ }
+
+ //private String callDownloadServlet( String downloadType, Long fileId){
+ public void callDownloadServlet( String downloadType, Long fileId, Boolean gbRecordsWritten){
+
+ String fileDownloadUrl = "/api/access/datafile/" + fileId;
+
+ if (downloadType != null && downloadType.equals("bundle")){
+ fileDownloadUrl = "/api/access/datafile/bundle/" + fileId;
+ }
+ if (downloadType != null && downloadType.equals("original")){
+ fileDownloadUrl = "/api/access/datafile/" + fileId + "?format=original";
+ }
+ if (downloadType != null && downloadType.equals("RData")){
+ fileDownloadUrl = "/api/access/datafile/" + fileId + "?format=RData";
+ }
+ if (downloadType != null && downloadType.equals("var")){
+ fileDownloadUrl = "/api/meta/datafile/" + fileId;
+ }
+ if (downloadType != null && downloadType.equals("tab")){
+ fileDownloadUrl = "/api/access/datafile/" + fileId+ "?format=tab";
+ }
+ if (gbRecordsWritten){
+ if(downloadType != null && ( downloadType.equals("original") || downloadType.equals("RData") || downloadType.equals("tab")) ){
+ fileDownloadUrl += "&gbrecs=true";
+ } else {
+ fileDownloadUrl += "?gbrecs=true";
+ }
+
+ }
+ logger.fine("Returning file download url: " + fileDownloadUrl);
+ try {
+ FacesContext.getCurrentInstance().getExternalContext().redirect(fileDownloadUrl);
+ } catch (IOException ex) {
+ logger.info("Failed to issue a redirect to file download url.");
+ }
+ //return fileDownloadUrl;
+ }
+
+ //public String startFileDownload(FileMetadata fileMetadata, String format) {
+ public void startFileDownload(GuestbookResponse guestbookResponse, FileMetadata fileMetadata, String format) {
+ boolean recordsWritten = false;
+ if(!fileMetadata.getDatasetVersion().isDraft()){
+ guestbookResponse = guestbookResponseService.modifyDatafileAndFormat(guestbookResponse, fileMetadata, format);
+ writeGuestbookResponseRecord(guestbookResponse);
+ recordsWritten = true;
+ }
+ callDownloadServlet(format, fileMetadata.getDataFile().getId(), recordsWritten);
+ logger.fine("issued file download redirect for filemetadata "+fileMetadata.getId()+", datafile "+fileMetadata.getDataFile().getId());
+ }
+
+ public String startExploreDownloadLink(GuestbookResponse guestbookResponse, FileMetadata fmd){
+
+ if (guestbookResponse != null && guestbookResponse.isWriteResponse()
+ && (( fmd != null && fmd.getDataFile() != null) || guestbookResponse.getDataFile() != null)){
+ if(guestbookResponse.getDataFile() == null && fmd != null){
+ guestbookResponse.setDataFile(fmd.getDataFile());
+ }
+ if (fmd == null || !fmd.getDatasetVersion().isDraft()){
+ writeGuestbookResponseRecord(guestbookResponse);
+ }
+ }
+
+ Long datafileId;
+
+ if (fmd == null && guestbookResponse != null && guestbookResponse.getDataFile() != null){
+ datafileId = guestbookResponse.getDataFile().getId();
+ } else {
+ datafileId = fmd.getDataFile().getId();
+ }
+ String retVal = twoRavensHelper.getDataExploreURLComplete(datafileId);
+
+ try {
+ FacesContext.getCurrentInstance().getExternalContext().redirect(retVal);
+ return retVal;
+ } catch (IOException ex) {
+ logger.info("Failed to issue a redirect to file download url.");
+ }
+ return retVal;
+ }
+
+ public String startWorldMapDownloadLink(GuestbookResponse guestbookResponse, FileMetadata fmd){
+
+ if (guestbookResponse != null && guestbookResponse.isWriteResponse() && ((fmd != null && fmd.getDataFile() != null) || guestbookResponse.getDataFile() != null)){
+ if(guestbookResponse.getDataFile() == null && fmd != null){
+ guestbookResponse.setDataFile(fmd.getDataFile());
+ }
+ if (fmd == null || !fmd.getDatasetVersion().isDraft()){
+ writeGuestbookResponseRecord(guestbookResponse);
+ }
+ }
+ DataFile file = null;
+ if (fmd != null){
+ file = fmd.getDataFile();
+ }
+ if (guestbookResponse != null && guestbookResponse.getDataFile() != null){
+ file = guestbookResponse.getDataFile();
+ }
+
+
+ String retVal = worldMapPermissionHelper.getMapLayerMetadata(file).getLayerLink();
+
+ try {
+ FacesContext.getCurrentInstance().getExternalContext().redirect(retVal);
+ return retVal;
+ } catch (IOException ex) {
+ logger.info("Failed to issue a redirect to file download url.");
+ }
+ return retVal;
+ }
+
+ public boolean isDownloadPopupRequired(DatasetVersion datasetVersion) {
+ // Each of these conditions is sufficient reason to have to
+ // present the user with the popup:
+ if (datasetVersion == null){
+ return false;
+ }
+ //0. if version is draft then Popup "not required"
+ if (!datasetVersion.isReleased()){
+ return false;
+ }
+ // 1. License and Terms of Use:
+ if (datasetVersion.getTermsOfUseAndAccess() != null) {
+ if (!TermsOfUseAndAccess.License.CC0.equals(datasetVersion.getTermsOfUseAndAccess().getLicense())
+ && !(datasetVersion.getTermsOfUseAndAccess().getTermsOfUse() == null
+ || datasetVersion.getTermsOfUseAndAccess().getTermsOfUse().equals(""))) {
+ return true;
+ }
+
+ // 2. Terms of Access:
+ if (!(datasetVersion.getTermsOfUseAndAccess().getTermsOfAccess() == null) && !datasetVersion.getTermsOfUseAndAccess().getTermsOfAccess().equals("")) {
+ return true;
+ }
+ }
+
+ // 3. Guest Book:
+ if (datasetVersion.getDataset().getGuestbook() != null && datasetVersion.getDataset().getGuestbook().isEnabled() && datasetVersion.getDataset().getGuestbook().getDataverse() != null ) {
+ return true;
+ }
+
+ return false;
+ }
+
+ public Boolean canSeeTwoRavensExploreButton(){
+ return false;
+ }
+
+
+ public Boolean canUserSeeExploreWorldMapButton(){
+ return false;
+ }
+
+ public void downloadDatasetCitationXML(Dataset dataset) {
+ downloadCitationXML(null, dataset);
+ }
+
+ public void downloadDatafileCitationXML(FileMetadata fileMetadata) {
+ downloadCitationXML(fileMetadata, null);
+ }
+
+ public void downloadCitationXML(FileMetadata fileMetadata, Dataset dataset) {
+ DatasetVersion workingVersion;
+ if (dataset != null){
+ workingVersion = dataset.getLatestVersion();
+ } else {
+ workingVersion = fileMetadata.getDatasetVersion();
+ }
+ String xml = datasetService.createCitationXML(workingVersion, fileMetadata);
+ FacesContext ctx = FacesContext.getCurrentInstance();
+ HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
+ response.setContentType("text/xml");
+ String fileNameString = "";
+ if (fileMetadata == null || fileMetadata.getLabel() == null) {
+ // Dataset-level citation:
+ fileNameString = "attachment;filename=" + getFileNameDOI(workingVersion) + ".xml";
+ } else {
+ // Datafile-level citation:
+ fileNameString = "attachment;filename=" + getFileNameDOI(workingVersion) + "-" + fileMetadata.getLabel().replaceAll("\\.tab$", "-endnote.xml");
+ }
+ response.setHeader("Content-Disposition", fileNameString);
+ try {
+ ServletOutputStream out = response.getOutputStream();
+ out.write(xml.getBytes());
+ out.flush();
+ ctx.responseComplete();
+ } catch (Exception e) {
+
+ }
+ }
+
+ public void downloadDatasetCitationRIS(Dataset dataset) {
+
+ downloadCitationRIS(null, dataset);
+
+ }
+
+ public void downloadDatafileCitationRIS(FileMetadata fileMetadata) {
+ downloadCitationRIS(fileMetadata, null);
+ }
+
+ public void downloadCitationRIS(FileMetadata fileMetadata, Dataset dataset) {
+ DatasetVersion workingVersion;
+ if (dataset != null){
+ workingVersion = dataset.getLatestVersion();
+ } else {
+ workingVersion = fileMetadata.getDatasetVersion();
+ }
+ String risFormatDowload = datasetService.createCitationRIS(workingVersion, fileMetadata);
+ FacesContext ctx = FacesContext.getCurrentInstance();
+ HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
+ response.setContentType("application/download");
+
+ String fileNameString = "";
+ if (fileMetadata == null || fileMetadata.getLabel() == null) {
+ // Dataset-level citation:
+ fileNameString = "attachment;filename=" + getFileNameDOI(workingVersion) + ".ris";
+ } else {
+ // Datafile-level citation:
+ fileNameString = "attachment;filename=" + getFileNameDOI(workingVersion) + "-" + fileMetadata.getLabel().replaceAll("\\.tab$", ".ris");
+ }
+ response.setHeader("Content-Disposition", fileNameString);
+
+ try {
+ ServletOutputStream out = response.getOutputStream();
+ out.write(risFormatDowload.getBytes());
+ out.flush();
+ ctx.responseComplete();
+ } catch (Exception e) {
+
+ }
+ }
+
+ private String getFileNameDOI(DatasetVersion workingVersion) {
+ Dataset ds = workingVersion.getDataset();
+ return "DOI:" + ds.getAuthority() + "_" + ds.getIdentifier().toString();
+ }
+
+ public void downloadDatasetCitationBibtex(Dataset dataset) {
+
+ downloadCitationBibtex(null, dataset);
+
+ }
+
+ public void downloadDatafileCitationBibtex(FileMetadata fileMetadata) {
+ downloadCitationBibtex(fileMetadata, null);
+ }
+
+ public void downloadCitationBibtex(FileMetadata fileMetadata, Dataset dataset) {
+ DatasetVersion workingVersion;
+ if (dataset != null){
+ workingVersion = dataset.getLatestVersion();
+ } else {
+ workingVersion = fileMetadata.getDatasetVersion();
+ }
+ String bibFormatDowload = new BibtexCitation(workingVersion).toString();
+ FacesContext ctx = FacesContext.getCurrentInstance();
+ HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
+ response.setContentType("application/download");
+
+ String fileNameString = "";
+ if (fileMetadata == null || fileMetadata.getLabel() == null) {
+ // Dataset-level citation:
+ fileNameString = "attachment;filename=" + getFileNameDOI(workingVersion) + ".bib";
+ } else {
+ // Datafile-level citation:
+ fileNameString = "attachment;filename=" + getFileNameDOI(workingVersion) + "-" + fileMetadata.getLabel().replaceAll("\\.tab$", ".bib");
+ }
+ response.setHeader("Content-Disposition", fileNameString);
+
+ try {
+ ServletOutputStream out = response.getOutputStream();
+ out.write(bibFormatDowload.getBytes());
+ out.flush();
+ ctx.responseComplete();
+ } catch (Exception e) {
+
+ }
+ }
+
+
+ public void requestAccess(DataFile file, boolean sendNotification) {
+ if (!file.getFileAccessRequesters().contains((AuthenticatedUser) session.getUser())) {
+ file.getFileAccessRequesters().add((AuthenticatedUser) session.getUser());
+ datafileService.save(file);
+
+ // create notifications
+ if (sendNotification) {
+ sendRequestFileAccessNotification(file);
+
+ }
+ }
+ }
+
+ private void sendRequestFileAccessNotification(DataFile file) {
+ for (AuthenticatedUser au : permissionService.getUsersWithPermissionOn(Permission.ManageDatasetPermissions, file.getOwner())) {
+ userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.REQUESTFILEACCESS, file.getId());
+ }
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/main/java/edu/harvard/iq/dataverse/FileMetadata.java b/src/main/java/edu/harvard/iq/dataverse/FileMetadata.java
index c17433cea08..f4bf3c03964 100644
--- a/src/main/java/edu/harvard/iq/dataverse/FileMetadata.java
+++ b/src/main/java/edu/harvard/iq/dataverse/FileMetadata.java
@@ -1,9 +1,12 @@
package edu.harvard.iq.dataverse;
import java.io.Serializable;
+import java.sql.Timestamp;
+import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
+import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
@@ -35,7 +38,7 @@
@Entity
public class FileMetadata implements Serializable {
private static final long serialVersionUID = 1L;
-
+ private static final DateFormat displayDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
private static final Logger logger = Logger.getLogger(FileMetadata.class.getCanonicalName());
@Pattern(regexp="^[^:<>;#/\"\\*\\|\\?\\\\]*$",
@@ -236,8 +239,49 @@ public void addCategoryByName(String newCategoryName) {
}
}
-
-
+ public String getFileDateToDisplay() {
+ Date fileDate = null;
+ DataFile datafile = this.getDataFile();
+ if (datafile != null) {
+ boolean fileHasBeenReleased = datafile.isReleased();
+ if (fileHasBeenReleased) {
+ Timestamp filePublicationTimestamp = datafile.getPublicationDate();
+ if (filePublicationTimestamp != null) {
+ fileDate = filePublicationTimestamp;
+ }
+ } else {
+ Timestamp fileCreateTimestamp = datafile.getCreateDate();
+ if (fileCreateTimestamp != null) {
+ fileDate = fileCreateTimestamp;
+ }
+ }
+ }
+ if (fileDate != null) {
+ return displayDateFormat.format(fileDate);
+ }
+ return "";
+ }
+
+ public String getFileCitation(){
+ return getFileCitation(false);
+ }
+
+
+
+
+ public String getFileCitation(boolean html){
+ String citation = this.getDatasetVersion().getCitation(html);
+ /*
+ ", #{FilePage.fileMetadata.label} [fileName]"
+
+ */
+ citation += "; " + this.getLabel() + " [fileName]" ;
+ if (this.dataFile.isTabularData() && this.dataFile.getUnf() != null && !this.dataFile.getUnf().isEmpty()){
+ citation += ", " + this.dataFile.getUnf() + " [fileUNF]";
+ }
+ return citation;
+ }
+
public DatasetVersion getDatasetVersion() {
return datasetVersion;
}
diff --git a/src/main/java/edu/harvard/iq/dataverse/FilePage.java b/src/main/java/edu/harvard/iq/dataverse/FilePage.java
index 9ff1cdf1389..9dfe0649d21 100644
--- a/src/main/java/edu/harvard/iq/dataverse/FilePage.java
+++ b/src/main/java/edu/harvard/iq/dataverse/FilePage.java
@@ -5,18 +5,22 @@
*/
package edu.harvard.iq.dataverse;
+import edu.harvard.iq.dataverse.DatasetVersionServiceBean.RetrieveDatasetVersionResponse;
+import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;
import edu.harvard.iq.dataverse.authorization.Permission;
-import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
+import edu.harvard.iq.dataverse.authorization.users.GuestUser;
+import edu.harvard.iq.dataverse.datasetutility.TwoRavensHelper;
+import edu.harvard.iq.dataverse.datasetutility.WorldMapPermissionHelper;
import edu.harvard.iq.dataverse.engine.command.Command;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
-import edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetCommand;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand;
+import edu.harvard.iq.dataverse.export.ExportException;
+import edu.harvard.iq.dataverse.export.ExportService;
+import edu.harvard.iq.dataverse.export.spi.Exporter;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import edu.harvard.iq.dataverse.util.JsfHelper;
import static edu.harvard.iq.dataverse.util.JsfHelper.JH;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
+import edu.harvard.iq.dataverse.util.SystemConfig;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -43,16 +47,32 @@ public class FilePage implements java.io.Serializable {
private FileMetadata fileMetadata;
private Long fileId;
- private Long datasetVersionId;
- private DataFile file;
-
+ private String version;
+ private DataFile file;
+ private GuestbookResponse guestbookResponse;
+ private int selectedTabIndex;
private Dataset editDataset;
@EJB
DataFileServiceBean datafileService;
+
+ @EJB
+ DatasetVersionServiceBean datasetVersionService;
@EJB
PermissionServiceBean permissionService;
+ @EJB
+ SettingsServiceBean settingsService;
+ @EJB
+ FileDownloadServiceBean fileDownloadService;
+ @EJB
+ GuestbookResponseServiceBean guestbookResponseService;
+ @EJB
+ AuthenticationServiceBean authService;
+
+ @EJB
+ SystemConfig systemConfig;
+
@Inject
DataverseSession session;
@@ -63,9 +83,14 @@ public class FilePage implements java.io.Serializable {
DataverseRequestServiceBean dvRequestService;
@Inject
PermissionsWrapper permissionsWrapper;
+ @Inject
+ FileDownloadHelper fileDownloadHelper;
+ @Inject
+ TwoRavensHelper twoRavensHelper;
+ @Inject WorldMapPermissionHelper worldMapPermissionHelper;
public String init() {
-
+
if ( fileId != null ) {
@@ -82,24 +107,32 @@ public String init() {
if (file == null){
return permissionsWrapper.notFound();
}
-
- fileMetadata = datafileService.findFileMetadataByDatasetVersionIdAndDataFileId(datasetVersionId, fileId);
+ RetrieveDatasetVersionResponse retrieveDatasetVersionResponse;
+ retrieveDatasetVersionResponse = datasetVersionService.selectRequestedVersion(file.getOwner().getVersions(), version);
+ Long getDatasetVersionID = retrieveDatasetVersionResponse.getDatasetVersion().getId();
+ fileMetadata = datafileService.findFileMetadataByDatasetVersionIdAndDataFileId(getDatasetVersionID, fileId);
+
+
if (fileMetadata == null){
return permissionsWrapper.notFound();
}
-
-
// If this DatasetVersion is unpublished and permission is doesn't have permissions:
// > Go to the Login page
//
-
- if ( !permissionService.on(file).has(Permission.DownloadFile)) {
- return permissionsWrapper.notAuthorized();
- }
-
+ // Check permisisons
+
+ Boolean authorized = (fileMetadata.getDatasetVersion().isReleased()) ||
+ (!fileMetadata.getDatasetVersion().isReleased() && this.canViewUnpublishedDataset())
+ || fileMetadata.getDatasetVersion().isDeaccessioned();
+
+ if (!authorized ) {
+ return permissionsWrapper.notAuthorized();
+ }
+
+ this.guestbookResponse = this.guestbookResponseService.initGuestbookResponseForFragment(fileMetadata, session);
} else {
return permissionsWrapper.notFound();
@@ -107,11 +140,24 @@ public String init() {
return null;
}
-
+
+ private boolean canViewUnpublishedDataset() {
+ return permissionsWrapper.canViewUnpublishedDataset( dvRequestService.getDataverseRequest(), fileMetadata.getDatasetVersion().getDataset());
+ }
+
public FileMetadata getFileMetadata() {
return fileMetadata;
}
+
+
+ public boolean isDownloadPopupRequired() {
+ if(fileMetadata.getId() == null || fileMetadata.getDatasetVersion().getId() == null ){
+ return false;
+ }
+ return fileDownloadService.isDownloadPopupRequired(fileMetadata.getDatasetVersion());
+ }
+
public void setFileMetadata(FileMetadata fileMetadata) {
this.fileMetadata = fileMetadata;
@@ -132,17 +178,42 @@ public Long getFileId() {
public void setFileId(Long fileId) {
this.fileId = fileId;
}
-
- public Long getDatasetVersionId() {
- return datasetVersionId;
+
+ public String getVersion() {
+ return version;
}
- public void setDatasetVersionId(Long datasetVersionId) {
- this.datasetVersionId = datasetVersionId;
+ public void setVersion(String version) {
+ this.version = version;
}
+ public List< String[]> getExporters(){
+ List retList = new ArrayList();
+ String myHostURL = systemConfig.getDataverseSiteUrl();
+ for (String [] provider : ExportService.getInstance().getExportersLabels() ){
+ String formatName = provider[1];
+ String formatDisplayName = provider[0];
+
+ Exporter exporter = null;
+ try {
+ exporter = ExportService.getInstance().getExporter(formatName);
+ } catch (ExportException ex) {
+ exporter = null;
+ }
+ if (exporter != null && exporter.isAvailableToUsers()) {
+ // Not all metadata exports should be presented to the web users!
+ // Some are only for harvesting clients.
+
+ String[] temp = new String[2];
+ temp[0] = formatDisplayName;
+ temp[1] = myHostURL + "/api/datasets/export?exporter=" + formatName + "&persistentId=" + fileMetadata.getDatasetVersion().getDataset().getGlobalId();
+ retList.add(temp);
+ }
+ }
+ return retList;
+ }
+
public String restrictFile(boolean restricted){
-
String fileNames = null;
editDataset = this.file.getOwner();
@@ -151,6 +222,7 @@ public String restrictFile(boolean restricted){
for (FileMetadata fmw: editDataset.getEditVersion().getFileMetadatas()){
if (fmw.getDataFile().equals(this.fileMetadata.getDataFile())){
+ fileNames += fmw.getLabel();
fmw.setRestricted(restricted);
}
}
@@ -161,6 +233,7 @@ public String restrictFile(boolean restricted){
JsfHelper.addFlashMessage(successMessage);
}
save();
+ init();
return returnToDraftVersion();
}
@@ -225,9 +298,8 @@ public String save() {
Command cmd;
try {
- System.out.print(filesToBeDeleted.size());
cmd = new UpdateDatasetCommand(editDataset, dvRequestService.getDataverseRequest(), filesToBeDeleted);
- commandEngine.submit(cmd);
+ commandEngine.submit(cmd);
} catch (EJBException ex) {
@@ -249,20 +321,72 @@ public String save() {
}
- JsfHelper.addSuccessMessage(JH.localize("dataset.message.filesSuccess"));
-
- setDatasetVersionId(editDataset.getEditVersion().getId());
+ JsfHelper.addSuccessMessage(JH.localize("dataset.message.filesSuccess"));
+ setVersion("DRAFT");
return "";
}
+ public boolean isThumbnailAvailable(FileMetadata fileMetadata) {
+ // new and optimized logic:
+ // - check download permission here (should be cached - so it's free!)
+ // - only then ask the file service if the thumbnail is available/exists.
+ // the service itself no longer checks download permissions.
+
+ if (!fileDownloadHelper.canDownloadFile(fileMetadata)) {
+ return false;
+ }
+
+ return datafileService.isThumbnailAvailable(fileMetadata.getDataFile());
+ }
+
private String returnToDatasetOnly(){
return "/dataset.xhtml?persistentId=" + editDataset.getGlobalId() + "&version=DRAFT" + "&faces-redirect=true";
}
private String returnToDraftVersion(){
+
+ return "/file.xhtml?fileId=" + fileId + "&version=DRAFT&faces-redirect=true";
+ }
+
+ public FileDownloadServiceBean getFileDownloadService() {
+ return fileDownloadService;
+ }
- return "/file.xhtml?fileId=" + fileId + "&datasetVersionId=" + editDataset.getEditVersion().getId() + "&faces-redirect=true";
+ public void setFileDownloadService(FileDownloadServiceBean fileDownloadService) {
+ this.fileDownloadService = fileDownloadService;
}
+
+ public GuestbookResponseServiceBean getGuestbookResponseService() {
+ return guestbookResponseService;
+ }
+
+ public void setGuestbookResponseService(GuestbookResponseServiceBean guestbookResponseService) {
+ this.guestbookResponseService = guestbookResponseService;
+ }
+
+
+ public GuestbookResponse getGuestbookResponse() {
+ return guestbookResponse;
+ }
+
+ public void setGuestbookResponse(GuestbookResponse guestbookResponse) {
+ this.guestbookResponse = guestbookResponse;
+ }
+
+
+ public boolean canUpdateDataset() {
+ return permissionsWrapper.canUpdateDataset(dvRequestService.getDataverseRequest(), this.file.getOwner());
+ }
+
+ public int getSelectedTabIndex() {
+ return selectedTabIndex;
+ }
+
+ public void setSelectedTabIndex(int selectedTabIndex) {
+ this.selectedTabIndex = selectedTabIndex;
+ }
+
+
}
diff --git a/src/main/java/edu/harvard/iq/dataverse/GuestbookPage.java b/src/main/java/edu/harvard/iq/dataverse/GuestbookPage.java
index a07678472ea..a4d9067e584 100644
--- a/src/main/java/edu/harvard/iq/dataverse/GuestbookPage.java
+++ b/src/main/java/edu/harvard/iq/dataverse/GuestbookPage.java
@@ -15,6 +15,7 @@
import java.util.Date;
import java.util.Iterator;
import java.util.List;
+import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
@@ -32,6 +33,8 @@
@Named("GuestbookPage")
public class GuestbookPage implements java.io.Serializable {
+ private static final Logger logger = Logger.getLogger(GuestbookPage.class.getCanonicalName());
+
@EJB
GuestbookServiceBean guestbookService;
@@ -309,13 +312,12 @@ public String save() {
}
//
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Guestbook Save Failed", " - " + error.toString()));
- System.out.print("dataverse " + dataverse.getName());
- System.out.print("Ejb exception");
- System.out.print(error.toString());
+ logger.info("Guestbook Page EJB Exception. Dataverse: " + dataverse.getName());
+ logger.info(error.toString());
return null;
} catch (CommandException ex) {
- System.out.print("command exception");
- System.out.print(ex.toString());
+ logger.info("Guestbook Page Command Exception. Dataverse: " + dataverse.getName());
+ logger.info(ex.toString());
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Guestbook Save Failed", " - " + ex.toString()));
//logger.severe(ex.getMessage());
}
diff --git a/src/main/java/edu/harvard/iq/dataverse/GuestbookResponse.java b/src/main/java/edu/harvard/iq/dataverse/GuestbookResponse.java
index 53d7876ff11..a3790fd32ce 100644
--- a/src/main/java/edu/harvard/iq/dataverse/GuestbookResponse.java
+++ b/src/main/java/edu/harvard/iq/dataverse/GuestbookResponse.java
@@ -7,7 +7,6 @@
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import java.io.Serializable;
-import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@@ -61,9 +60,51 @@ public class GuestbookResponse implements Serializable {
private String position;
private String downloadtype;
private String sessionId;
-
+
@Temporal(value = TemporalType.TIMESTAMP)
private Date responseTime;
+
+ /*
+ Transient Values carry non-written information
+ that will assist in the download process
+ - selected file ids is a comma delimited list that contains the file ids for multiple download
+ - fileFormat tells the download api which format a subsettable file should be downloaded as
+ - writeResponse is set to false when dataset version is draft.
+ */
+
+ @Transient
+ private String selectedFileIds;
+
+ @Transient
+ private String fileFormat;
+
+ @Transient
+ private boolean writeResponse = true;
+
+ public boolean isWriteResponse() {
+ return writeResponse;
+ }
+
+ public void setWriteResponse(boolean writeResponse) {
+ this.writeResponse = writeResponse;
+ }
+
+ public String getSelectedFileIds() {
+ return selectedFileIds;
+ }
+
+ public void setSelectedFileIds(String selectedFileIds) {
+ this.selectedFileIds = selectedFileIds;
+ }
+
+
+ public String getFileFormat() {
+ return fileFormat;
+ }
+
+ public void setFileFormat(String downloadFormat) {
+ this.fileFormat = downloadFormat;
+ }
public GuestbookResponse(){
diff --git a/src/main/java/edu/harvard/iq/dataverse/GuestbookResponseServiceBean.java b/src/main/java/edu/harvard/iq/dataverse/GuestbookResponseServiceBean.java
index 23a33b0cbf6..fa3e8a67d9e 100644
--- a/src/main/java/edu/harvard/iq/dataverse/GuestbookResponseServiceBean.java
+++ b/src/main/java/edu/harvard/iq/dataverse/GuestbookResponseServiceBean.java
@@ -8,24 +8,26 @@
import edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.authorization.users.User;
+import static edu.harvard.iq.dataverse.util.JsfHelper.JH;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIComponent;
+import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
+import javax.faces.model.SelectItem;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletResponse;
/**
*
@@ -432,17 +434,126 @@ public AuthenticatedUser getAuthenticatedUser(User user) {
}
return null;
}
+
+
+ public GuestbookResponse initGuestbookResponseForFragment(Dataset dataset, FileMetadata fileMetadata, DataverseSession session){
+
+ DatasetVersion workingVersion = null;
+ if (fileMetadata != null){
+ workingVersion = fileMetadata.getDatasetVersion();
+ } else {
+ workingVersion = dataset.getLatestVersion();
+ }
- public GuestbookResponse initDefaultGuestbookResponse(Dataset dataset, DataFile dataFile, User user, DataverseSession session) {
+
GuestbookResponse guestbookResponse = new GuestbookResponse();
- guestbookResponse.setGuestbook(findDefaultGuestbook());
- if (dataFile != null){
- guestbookResponse.setDataFile(dataFile);
- }
+
+ if(workingVersion != null && workingVersion.isDraft()){
+ guestbookResponse.setWriteResponse(false);
+ }
+
+ if (fileMetadata != null){
+ guestbookResponse.setDataFile(fileMetadata.getDataFile());
+ }
+
+ if (dataset.getGuestbook() != null) {
+ guestbookResponse.setGuestbook(workingVersion.getDataset().getGuestbook());
+ setUserDefaultResponses(guestbookResponse, session);
+ if (fileMetadata != null){
+ guestbookResponse.setDataFile(fileMetadata.getDataFile());
+ }
+ } else {
+ if (fileMetadata != null){
+ guestbookResponse = initDefaultGuestbookResponse(dataset, fileMetadata.getDataFile(), session);
+ } else {
+ guestbookResponse = initDefaultGuestbookResponse(dataset, null, session);
+ }
+ }
+ if (dataset.getGuestbook() != null && !dataset.getGuestbook().getCustomQuestions().isEmpty()) {
+ initCustomQuestions(guestbookResponse, dataset);
+ }
+ guestbookResponse.setDownloadtype("Download");
+
guestbookResponse.setDataset(dataset);
- guestbookResponse.setResponseTime(new Date());
- guestbookResponse.setSessionId(session.toString());
+
+ return guestbookResponse;
+ }
+
+ public GuestbookResponse initGuestbookResponseForFragment(FileMetadata fileMetadata, DataverseSession session){
+ return initGuestbookResponseForFragment(fileMetadata.getDatasetVersion().getDataset(), fileMetadata, session);
+ }
+
+ public void initGuestbookResponse(FileMetadata fileMetadata, String downloadType, DataverseSession session){
+ initGuestbookResponse(fileMetadata, downloadType, null, session);
+ }
+
+ public GuestbookResponse initGuestbookResponse(FileMetadata fileMetadata, String downloadFormat, String selectedFileIds, DataverseSession session) {
+ Dataset dataset;
+ DatasetVersion workingVersion = null;
+ if (fileMetadata != null){
+ workingVersion = fileMetadata.getDatasetVersion();
+ }
+
+
+
+ GuestbookResponse guestbookResponse = new GuestbookResponse();
+
+ if(workingVersion != null && workingVersion.isDraft()){
+ guestbookResponse.setWriteResponse(false);
+ }
+
+ dataset = workingVersion.getDataset();
+
+ if (fileMetadata != null){
+ guestbookResponse.setDataFile(fileMetadata.getDataFile());
+ }
+
+ if (dataset.getGuestbook() != null) {
+ guestbookResponse.setGuestbook(workingVersion.getDataset().getGuestbook());
+ setUserDefaultResponses(guestbookResponse, session);
+ if (fileMetadata != null){
+ guestbookResponse.setDataFile(fileMetadata.getDataFile());
+ }
+ } else {
+ if (fileMetadata != null){
+ guestbookResponse = initDefaultGuestbookResponse(dataset, fileMetadata.getDataFile(), session);
+ } else {
+ guestbookResponse = initDefaultGuestbookResponse(dataset, null, session);
+ }
+ }
+ if (dataset.getGuestbook() != null && !dataset.getGuestbook().getCustomQuestions().isEmpty()) {
+ initCustomQuestions(guestbookResponse, dataset);
+ }
+ guestbookResponse.setDownloadtype("Download");
+ if(downloadFormat.toLowerCase().equals("subset")){
+ guestbookResponse.setDownloadtype("Subset");
+ }
+ if(downloadFormat.toLowerCase().equals("explore")){
+ guestbookResponse.setDownloadtype("Explore");
+ }
+ guestbookResponse.setDataset(dataset);
+
+ return guestbookResponse;
+ }
+
+ private void initCustomQuestions(GuestbookResponse guestbookResponse, Dataset dataset) {
+ guestbookResponse.setCustomQuestionResponses(new ArrayList());
+ for (CustomQuestion cq : dataset.getGuestbook().getCustomQuestions()) {
+ CustomQuestionResponse cqr = new CustomQuestionResponse();
+ cqr.setGuestbookResponse(guestbookResponse);
+ cqr.setCustomQuestion(cq);
+ cqr.setResponse("");
+ if (cq.getQuestionType().equals("options")) {
+ //response select Items
+ cqr.setResponseSelectItems(setResponseUISelectItems(cq));
+ }
+ guestbookResponse.getCustomQuestionResponses().add(cqr);
+ }
+ }
+
+ private void setUserDefaultResponses(GuestbookResponse guestbookResponse, DataverseSession session) {
+ User user = session.getUser();
if (user != null) {
guestbookResponse.setEmail(getUserEMail(user));
guestbookResponse.setName(getUserName(user));
@@ -456,8 +567,125 @@ public GuestbookResponse initDefaultGuestbookResponse(Dataset dataset, DataFile
guestbookResponse.setPosition("");
guestbookResponse.setAuthenticatedUser(null);
}
+ guestbookResponse.setSessionId(session.toString());
+ }
+
+ public GuestbookResponse initDefaultGuestbookResponse(Dataset dataset, DataFile dataFile, DataverseSession session) {
+ GuestbookResponse guestbookResponse = new GuestbookResponse();
+ guestbookResponse.setGuestbook(findDefaultGuestbook());
+ if(dataset.getLatestVersion() != null && dataset.getLatestVersion().isDraft()){
+ guestbookResponse.setWriteResponse(false);
+ }
+ if (dataFile != null){
+ guestbookResponse.setDataFile(dataFile);
+ }
+ guestbookResponse.setDataset(dataset);
+ guestbookResponse.setResponseTime(new Date());
+ guestbookResponse.setSessionId(session.toString());
+ guestbookResponse.setDownloadtype("Download");
+ setUserDefaultResponses(guestbookResponse, session);
return guestbookResponse;
}
+
+ public void guestbookResponseValidator(FacesContext context, UIComponent toValidate, Object value) {
+ String response = (String) value;
+
+ if (response != null && response.length() > 255) {
+ ((UIInput) toValidate).setValid(false);
+ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, JH.localize("dataset.guestbookResponse.guestbook.responseTooLong"), null);
+ context.addMessage(toValidate.getClientId(context), message);
+ }
+ }
+
+ public GuestbookResponse modifyDatafile(GuestbookResponse in, FileMetadata fm) {
+ if (in != null && fm.getDataFile() != null) {
+ in.setDataFile(fm.getDataFile());
+ }
+ if (in != null && fm.getDatasetVersion() != null && fm.getDatasetVersion().isDraft() ) {
+ in.setWriteResponse(false);
+ }
+ return in;
+ }
+
+ public GuestbookResponse modifySelectedFileIds(GuestbookResponse in, String fileIds) {
+ if (in != null && fileIds != null) {
+ in.setSelectedFileIds(fileIds);
+ }
+ return in;
+ }
+
+ public GuestbookResponse modifyDatafileAndFormat(GuestbookResponse in, FileMetadata fm, String format) {
+ if (in != null && fm.getDataFile() != null) {
+ in.setFileFormat(format);
+ in.setDataFile(fm.getDataFile());
+ }
+ if (in != null && fm.getDatasetVersion() != null && fm.getDatasetVersion().isDraft() ) {
+ in.setWriteResponse(false);
+ }
+
+ return in;
+ }
+
+ public Boolean validateGuestbookResponse(GuestbookResponse guestbookResponse, String type) {
+ boolean valid = true;
+ Dataset dataset = guestbookResponse.getDataset();
+ if (dataset.getGuestbook() != null) {
+ if (dataset.getGuestbook().isNameRequired()) {
+ if (guestbookResponse.getName() == null) {
+ valid = false;
+ } else {
+ valid &= !guestbookResponse.getName().isEmpty();
+ }
+ }
+ if (dataset.getGuestbook().isEmailRequired()) {
+ if (guestbookResponse.getEmail() == null) {
+ valid = false;
+ } else {
+ valid &= !guestbookResponse.getEmail().isEmpty();
+ }
+ }
+ if (dataset.getGuestbook().isInstitutionRequired()) {
+ if (guestbookResponse.getInstitution() == null) {
+ valid = false;
+ } else {
+ valid &= !guestbookResponse.getInstitution().isEmpty();
+ }
+ }
+ if (dataset.getGuestbook().isPositionRequired()) {
+ if (guestbookResponse.getPosition() == null) {
+ valid = false;
+ } else {
+ valid &= !guestbookResponse.getPosition().isEmpty();
+ }
+ }
+ }
+
+ if (dataset.getGuestbook() != null && !dataset.getGuestbook().getCustomQuestions().isEmpty()) {
+ for (CustomQuestion cq : dataset.getGuestbook().getCustomQuestions()) {
+ if (cq.isRequired()) {
+ for (CustomQuestionResponse cqr : guestbookResponse.getCustomQuestionResponses()) {
+ if (cqr.getCustomQuestion().equals(cq)) {
+ valid &= (cqr.getResponse() != null && !cqr.getResponse().isEmpty());
+ }
+ }
+ }
+ }
+ }
+
+ return valid;
+ }
+
+ private List setResponseUISelectItems(CustomQuestion cq) {
+ List retList = new ArrayList();
+ for (CustomQuestionValue cqv : cq.getCustomQuestionValues()) {
+ SelectItem si = new SelectItem(cqv.getValueString(), cqv.getValueString());
+ retList.add(si);
+ }
+ return retList;
+ }
+
+
+
public GuestbookResponse findById(Long id) {
return em.find(GuestbookResponse.class, id);
diff --git a/src/main/java/edu/harvard/iq/dataverse/NavigationWrapper.java b/src/main/java/edu/harvard/iq/dataverse/NavigationWrapper.java
index 989b69d10b0..beee1a81173 100644
--- a/src/main/java/edu/harvard/iq/dataverse/NavigationWrapper.java
+++ b/src/main/java/edu/harvard/iq/dataverse/NavigationWrapper.java
@@ -51,7 +51,7 @@ public String getPageFromContext() {
// that we don't want, so we filter through a list of paramters we do allow
// @todo verify what needs to be in this list of available parameters (for example do we want to repeat searches when you login?
List acceptableParameters = new ArrayList();
- acceptableParameters.addAll(Arrays.asList("id", "alias", "version", "q", "ownerId", "persistentId", "versionId", "datasetId", "selectedFileIds", "mode", "dataverseId"));
+ acceptableParameters.addAll(Arrays.asList("id", "alias", "version", "q", "ownerId", "persistentId", "versionId", "datasetId", "selectedFileIds", "mode", "dataverseId", "fileId", "datasetVersionId"));
if (req.getParameterMap() != null) {
StringBuilder queryString = new StringBuilder();
diff --git a/src/main/java/edu/harvard/iq/dataverse/api/Access.java b/src/main/java/edu/harvard/iq/dataverse/api/Access.java
index 11746a19c04..2377c459992 100644
--- a/src/main/java/edu/harvard/iq/dataverse/api/Access.java
+++ b/src/main/java/edu/harvard/iq/dataverse/api/Access.java
@@ -18,6 +18,8 @@
import edu.harvard.iq.dataverse.DataverseServiceBean;
import edu.harvard.iq.dataverse.DataverseSession;
import edu.harvard.iq.dataverse.DataverseTheme;
+import edu.harvard.iq.dataverse.GuestbookResponse;
+import edu.harvard.iq.dataverse.GuestbookResponseServiceBean;
import edu.harvard.iq.dataverse.PermissionServiceBean;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
@@ -113,6 +115,8 @@ public class Access extends AbstractApiBean {
WorldMapTokenServiceBean worldMapTokenServiceBean;
@Inject
DataverseRequestServiceBean dvRequestService;
+ @EJB
+ GuestbookResponseServiceBean guestbookResponseService;
private static final String API_KEY_HEADER = "X-Dataverse-key";
@@ -174,10 +178,16 @@ public BundleDownloadInstance datafileBundle(@PathParam("fileId") Long fileId, @
@Path("datafile/{fileId}")
@GET
@Produces({ "application/xml" })
- public DownloadInstance datafile(@PathParam("fileId") Long fileId, @QueryParam("key") String apiToken, @Context UriInfo uriInfo, @Context HttpHeaders headers, @Context HttpServletResponse response) /*throws NotFoundException, ServiceUnavailableException, PermissionDeniedException, AuthorizationRequiredException*/ {
-
+ public DownloadInstance datafile(@PathParam("fileId") Long fileId, @QueryParam("gbrecs") Boolean gbrecs, @QueryParam("key") String apiToken, @Context UriInfo uriInfo, @Context HttpHeaders headers, @Context HttpServletResponse response) /*throws NotFoundException, ServiceUnavailableException, PermissionDeniedException, AuthorizationRequiredException*/ {
DataFile df = dataFileService.find(fileId);
+ GuestbookResponse gbr = null;
+ /*
+ if (gbrecs == null && df.isReleased()){
+ //commenting out for 4.6 SEK
+ // gbr = guestbookResponseService.initDefaultGuestbookResponse(df.getOwner(), df, session);
+ }
+ */
if (df == null) {
logger.warning("Access: datafile service could not locate a DataFile object for id "+fileId+"!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
@@ -206,7 +216,11 @@ public DownloadInstance datafile(@PathParam("fileId") Long fileId, @QueryParam("
dInfo.addServiceAvailable(new OptionalAccessService("subset", "text/tab-separated-values", "variables=<LIST>", "Column-wise Subsetting"));
}
DownloadInstance downloadInstance = new DownloadInstance(dInfo);
-
+ if (gbr != null){
+ downloadInstance.setGbr(gbr);
+ downloadInstance.setDataverseRequestService(dvRequestService);
+ downloadInstance.setCommand(engineSvc);
+ }
for (String key : uriInfo.getQueryParameters().keySet()) {
String value = uriInfo.getQueryParameters().getFirst(key);
diff --git a/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstance.java b/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstance.java
index b84896739e9..94d7af1ba77 100644
--- a/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstance.java
+++ b/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstance.java
@@ -6,6 +6,9 @@
package edu.harvard.iq.dataverse.api;
//import java.io.ByteArrayOutputStream;
+import edu.harvard.iq.dataverse.DataverseRequestServiceBean;
+import edu.harvard.iq.dataverse.EjbDataverseEngine;
+import edu.harvard.iq.dataverse.GuestbookResponse;
import java.util.List;
import edu.harvard.iq.dataverse.dataaccess.OptionalAccessService;
@@ -40,6 +43,13 @@ public void setExtraArguments(List extraArguments) {
private DownloadInfo downloadInfo = null;
private String conversionParam = null;
private String conversionParamValue = null;
+
+ private EjbDataverseEngine command;
+
+ private DataverseRequestServiceBean dataverseRequestService;
+
+ private GuestbookResponse gbr;
+
public DownloadInstance() {
@@ -142,4 +152,31 @@ public String getServiceFormatType(String serviceArg, String serviceArgValue) {
}
return null;
}
+
+
+ public EjbDataverseEngine getCommand() {
+ return command;
+ }
+
+ public void setCommand(EjbDataverseEngine command) {
+ this.command = command;
+ }
+
+ public GuestbookResponse getGbr() {
+ return gbr;
+ }
+
+ public void setGbr(GuestbookResponse gbr) {
+ this.gbr = gbr;
+ }
+
+
+ public DataverseRequestServiceBean getDataverseRequestService() {
+ return dataverseRequestService;
+ }
+
+ public void setDataverseRequestService(DataverseRequestServiceBean dataverseRequestService) {
+ this.dataverseRequestService = dataverseRequestService;
+ }
+
}
diff --git a/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstanceWriter.java b/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstanceWriter.java
index 76a5d035a13..7b0c6c414dd 100644
--- a/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstanceWriter.java
+++ b/src/main/java/edu/harvard/iq/dataverse/api/DownloadInstanceWriter.java
@@ -22,8 +22,13 @@
import javax.ws.rs.ext.Provider;
import edu.harvard.iq.dataverse.DataFile;
+import edu.harvard.iq.dataverse.DataverseRequestServiceBean;
import edu.harvard.iq.dataverse.dataaccess.*;
import edu.harvard.iq.dataverse.datavariable.DataVariable;
+import edu.harvard.iq.dataverse.engine.command.Command;
+import edu.harvard.iq.dataverse.engine.command.DataverseRequest;
+import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
+import edu.harvard.iq.dataverse.engine.command.impl.CreateGuestbookResponseCommand;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
@@ -245,6 +250,26 @@ public void writeTo(DownloadInstance di, Class> clazz, Type type, Annotation[]
outstream.write(chunkClosing.getBytes());
}
+
+ logger.fine("di conversion param: "+di.getConversionParam()+", value: "+di.getConversionParamValue());
+
+ // Downloads of thumbnail images (scaled down, low-res versions of graphic image files) and
+ // "preprocessed metadata" records for tabular data files are NOT considered "real" downloads,
+ // so these should not produce guestbook entries:
+
+ if (di.getGbr() != null && !(isThumbnailDownload(di) || isPreprocessedMetadataDownload(di))) {
+ try {
+ logger.fine("writing guestbook response.");
+ Command cmd = new CreateGuestbookResponseCommand(di.getDataverseRequestService().getDataverseRequest(), di.getGbr(), di.getGbr().getDataFile().getOwner());
+ di.getCommand().submit(cmd);
+ } catch (CommandException e) {
+ //if an error occurs here then download won't happen no need for response recs...
+ }
+ } else {
+ logger.fine("not writing guestbook response");
+ }
+
+
instream.close();
outstream.close();
return;
@@ -256,6 +281,24 @@ public void writeTo(DownloadInstance di, Class> clazz, Type type, Annotation[]
}
+ private boolean isThumbnailDownload(DownloadInstance downloadInstance) {
+ if (downloadInstance == null) return false;
+
+ if (downloadInstance.getConversionParam() == null) return false;
+
+ return downloadInstance.getConversionParam().equals("imageThumb");
+ }
+
+ private boolean isPreprocessedMetadataDownload(DownloadInstance downloadInstance) {
+ if (downloadInstance == null) return false;
+
+ if (downloadInstance.getConversionParam() == null) return false;
+
+ if (downloadInstance.getConversionParamValue() == null) return false;
+
+ return downloadInstance.getConversionParam().equals("format") && downloadInstance.getConversionParamValue().equals("prep");
+ }
+
private long getContentSize(DataFileIO accessObject) {
long contentSize = 0;
diff --git a/src/main/java/edu/harvard/iq/dataverse/datasetutility/TwoRavensHelper.java b/src/main/java/edu/harvard/iq/dataverse/datasetutility/TwoRavensHelper.java
new file mode 100644
index 00000000000..e352a2995fc
--- /dev/null
+++ b/src/main/java/edu/harvard/iq/dataverse/datasetutility/TwoRavensHelper.java
@@ -0,0 +1,322 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package edu.harvard.iq.dataverse.datasetutility;
+
+import edu.harvard.iq.dataverse.Dataset;
+import edu.harvard.iq.dataverse.DataverseSession;
+import edu.harvard.iq.dataverse.DvObject;
+import edu.harvard.iq.dataverse.FileMetadata;
+import edu.harvard.iq.dataverse.PermissionServiceBean;
+import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;
+import edu.harvard.iq.dataverse.authorization.Permission;
+import edu.harvard.iq.dataverse.authorization.users.ApiToken;
+import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
+import edu.harvard.iq.dataverse.authorization.users.GuestUser;
+import edu.harvard.iq.dataverse.authorization.users.User;
+import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
+import java.util.HashMap;
+import java.util.Map;
+import javax.faces.view.ViewScoped;
+import javax.inject.Inject;
+import javax.inject.Named;
+
+/**
+ *
+ * @author rmp553
+
+ */
+@ViewScoped
+@Named
+public class TwoRavensHelper implements java.io.Serializable {
+
+ @Inject SettingsServiceBean settingsService;
+ @Inject PermissionServiceBean permissionService;
+ @Inject AuthenticationServiceBean authService;
+
+ @Inject
+ DataverseSession session;
+
+ private final Map fileMetadataTwoRavensExploreMap = new HashMap<>(); // { FileMetadata.id : Boolean }
+
+ public TwoRavensHelper(){
+
+ }
+
+
+ /**
+ * Call this from a Dataset or File page
+ * - calls private method canSeeTwoRavensExploreButton
+ *
+ * WARNING: Before calling this, make sure the user has download
+ * permission for the file!! (See DatasetPage.canDownloadFile())
+ *
+ * @param fm
+ * @return
+ */
+ public boolean canSeeTwoRavensExploreButtonFromAPI(FileMetadata fm, User user){
+
+ if (fm == null){
+ return false;
+ }
+
+ if (user == null){
+ return false;
+ }
+
+ if (!this.permissionService.userOn(user, fm.getDataFile()).has(Permission.DownloadFile)){
+ return false;
+ }
+
+ return this.canSeeTwoRavensExploreButton(fm, true);
+ }
+
+ /**
+ * Call this from a Dataset or File page
+ * - calls private method canSeeTwoRavensExploreButton
+ *
+ * WARNING: Before calling this, make sure the user has download
+ * permission for the file!! (See DatasetPage.canDownloadFile())
+ *
+ * @param fm
+ * @return
+ */
+ public boolean canSeeTwoRavensExploreButtonFromPage(FileMetadata fm){
+
+ if (fm == null){
+ return false;
+ }
+
+ return this.canSeeTwoRavensExploreButton(fm, true);
+ }
+
+ /**
+ * Used to check whether a tabular file
+ * may be viewed via TwoRavens
+ *
+ * @param fm
+ * @return
+ */
+ public boolean canSeeTwoRavensExploreButton(FileMetadata fm, boolean permissionsChecked){
+ if (fm == null){
+ return false;
+ }
+
+ // This is only here as a reminder to the public method users
+ if (!permissionsChecked){
+ return false;
+ }
+
+ if (!fm.getDataFile().isTabularData()){
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
+ return false;
+ }
+
+ // Has this already been checked?
+ if (this.fileMetadataTwoRavensExploreMap.containsKey(fm.getId())){
+ // Yes, return previous answer
+ //logger.info("using cached result for candownloadfile on filemetadata "+fid);
+ return this.fileMetadataTwoRavensExploreMap.get(fm.getId());
+ }
+
+
+ // (1) Is TwoRavens active via the "setting" table?
+ // Nope: get out
+ //
+ if (!settingsService.isTrueForKey(SettingsServiceBean.Key.TwoRavensTabularView, false)){
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
+ return false;
+ }
+
+ //----------------------------------------------------------------------
+ //(1a) Before we do any testing - if version is deaccessioned and user
+ // does not have edit dataset permission then may download
+ //---
+
+ // (2) Is the DataFile object there and persisted?
+ // Nope: scat
+ //
+ if ((fm.getDataFile() == null)||(fm.getDataFile().getId()==null)){
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
+ return false;
+ }
+
+ if (fm.getDatasetVersion().isDeaccessioned()) {
+ if (this.doesSessionUserHavePermission( Permission.EditDataset, fm)) {
+ // Yes, save answer and return true
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), true);
+ return true;
+ } else {
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
+ return false;
+ }
+ }
+
+
+
+
+ //Check for restrictions
+
+ boolean isRestrictedFile = fm.isRestricted();
+
+
+ // --------------------------------------------------------------------
+ // Conditions (2) through (4) are for Restricted files
+ // --------------------------------------------------------------------
+
+
+ if (isRestrictedFile && session.getUser() instanceof GuestUser){
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
+ return false;
+ }
+
+
+ // --------------------------------------------------------------------
+ // (3) Does the User have DownloadFile Permission at the **Dataset** level
+ // --------------------------------------------------------------------
+
+
+ if (isRestrictedFile && !this.doesSessionUserHavePermission(Permission.DownloadFile, fm)){
+ // Yes, save answer and return true
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
+ return false;
+ }
+
+ // (3) Is there tabular data or is the ingest in progress?
+ // Yes: great
+ //
+ if ((fm.getDataFile().isTabularData())||(fm.getDataFile().isIngestInProgress())){
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), true);
+ return true;
+ }
+
+ // Nope
+ this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
+ return false;
+
+ // (empty fileMetadata.dataFile.id) and (fileMetadata.dataFile.tabularData or fileMetadata.dataFile.ingestInProgress)
+ // and DatasetPage.canDownloadFile(fileMetadata)
+ }
+
+
+ /**
+ * Copied over from the dataset page - 9/21/2016
+ *
+ * @return
+ */
+ public String getDataExploreURL() {
+ String TwoRavensUrl = settingsService.getValueForKey(SettingsServiceBean.Key.TwoRavensUrl);
+
+ if (TwoRavensUrl != null && !TwoRavensUrl.equals("")) {
+ return TwoRavensUrl;
+ }
+
+ return "";
+ }
+
+
+ /**
+ * Copied over from the dataset page - 9/21/2016
+ *
+ * @param fileid
+ * @param apiTokenKey
+ * @return
+ */
+ public String getDataExploreURLComplete(Long fileid) {
+ if (fileid == null){
+ throw new NullPointerException("fileid cannot be null");
+ }
+
+
+ String TwoRavensUrl = settingsService.getValueForKey(SettingsServiceBean.Key.TwoRavensUrl);
+ String TwoRavensDefaultLocal = "/dataexplore/gui.html?dfId=";
+
+ if (TwoRavensUrl != null && !TwoRavensUrl.equals("")) {
+ // If we have TwoRavensUrl set up as, as an optional
+ // configuration service, it must mean that TwoRavens is sitting
+ // on some remote server. And that in turn means that we must use
+ // full URLs to pass data and metadata to it.
+ // update: actually, no we don't want to use this "dataurl" notation.
+ // switching back to the dfId=:
+ // -- L.A. 4.1
+ /*
+ String tabularDataURL = getTabularDataFileURL(fileid);
+ String tabularMetaURL = getVariableMetadataURL(fileid);
+ return TwoRavensUrl + "?ddiurl=" + tabularMetaURL + "&dataurl=" + tabularDataURL + "&" + getApiTokenKey();
+ */
+ System.out.print("TwoRavensUrl Set up " + TwoRavensUrl + "?dfId=" + fileid + "&" + getApiTokenKey());
+
+ return TwoRavensUrl + "?dfId=" + fileid + "&" + getApiTokenKey();
+ }
+
+ // For a local TwoRavens setup it's enough to call it with just
+ // the file id:
+ return TwoRavensDefaultLocal + fileid + "&" + getApiTokenKey();
+ }
+
+ private String getApiTokenKey() {
+ ApiToken apiToken;
+ if (session.getUser() == null) {
+ return null;
+ }
+ if (isSessionUserAuthenticated()) {
+ AuthenticatedUser au = (AuthenticatedUser) session.getUser();
+ apiToken = authService.findApiTokenByUser(au);
+ if (apiToken != null) {
+ return "key=" + apiToken.getTokenString();
+ }
+ // Generate if not available?
+ // Or should it just be generated inside the authService
+ // automatically?
+ apiToken = authService.generateApiTokenForUser(au);
+ if (apiToken != null) {
+ return "key=" + apiToken.getTokenString();
+ }
+ }
+ return "";
+
+ }
+
+ public boolean isSessionUserAuthenticated() {
+
+ if (session == null) {
+ return false;
+ }
+
+ if (session.getUser() == null) {
+ return false;
+ }
+
+ return session.getUser().isAuthenticated();
+
+ }
+
+ public boolean doesSessionUserHavePermission(Permission permissionToCheck, FileMetadata fileMetadata){
+ if (permissionToCheck == null){
+ return false;
+ }
+
+ DvObject objectToCheck = null;
+
+ if (permissionToCheck.equals(Permission.EditDataset)){
+ objectToCheck = fileMetadata.getDatasetVersion().getDataset();
+ } else if (permissionToCheck.equals(Permission.DownloadFile)){
+ objectToCheck = fileMetadata.getDataFile();
+ }
+
+ if (objectToCheck == null){
+ return false;
+ }
+
+
+ // Check the permission
+ //
+ boolean hasPermission = this.permissionService.userOn(this.session.getUser(), objectToCheck).has(permissionToCheck);
+
+
+ // return true/false
+ return hasPermission;
+ }
+}
diff --git a/src/main/java/edu/harvard/iq/dataverse/datasetutility/WorldMapPermissionHelper.java b/src/main/java/edu/harvard/iq/dataverse/datasetutility/WorldMapPermissionHelper.java
new file mode 100644
index 00000000000..2bf79b7cfb9
--- /dev/null
+++ b/src/main/java/edu/harvard/iq/dataverse/datasetutility/WorldMapPermissionHelper.java
@@ -0,0 +1,629 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package edu.harvard.iq.dataverse.datasetutility;
+
+import edu.harvard.iq.dataverse.DataFile;
+import edu.harvard.iq.dataverse.Dataset;
+import edu.harvard.iq.dataverse.DataverseSession;
+import edu.harvard.iq.dataverse.DvObject;
+import edu.harvard.iq.dataverse.FileMetadata;
+import edu.harvard.iq.dataverse.MapLayerMetadata;
+import edu.harvard.iq.dataverse.MapLayerMetadataServiceBean;
+import edu.harvard.iq.dataverse.PermissionServiceBean;
+import edu.harvard.iq.dataverse.authorization.Permission;
+import edu.harvard.iq.dataverse.authorization.users.GuestUser;
+import edu.harvard.iq.dataverse.authorization.users.User;
+import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.faces.view.ViewScoped;
+import javax.inject.Inject;
+import javax.inject.Named;
+
+/**
+ * This class originally encapsulated display logic for the DatasetPage
+ *
+ * It allows the following checks without redundantly querying the db to
+ * check permissions or if MapLayerMetadata exists
+ *
+ * - canUserSeeMapDataButton (private)
+ * - canUserSeeMapDataButtonFromPage (public)
+ * - canUserSeeMapDataButtonFromAPI (public)
+ *
+ * - canSeeMapButtonReminderToPublish (private)
+ * - canSeeMapButtonReminderToPublishFromPage (public)
+ * - canSeeMapButtonReminderToPublishFromAPI (public)
+ *
+ * - canUserSeeExploreWorldMapButton (private)
+ * - canUserSeeExploreWorldMapButtonFromPage (public)
+ * - canUserSeeExploreWorldMapButtonFromAPI (public)
+ *
+ * @author rmp553
+ */
+@ViewScoped
+@Named
+public class WorldMapPermissionHelper implements java.io.Serializable {
+
+ @Inject SettingsServiceBean settingsService;
+ @Inject MapLayerMetadataServiceBean mapLayerMetadataService;
+ @Inject PermissionServiceBean permissionService;
+ @Inject DataverseSession session;
+
+
+ private final Map fileMetadataWorldMapExplore = new HashMap<>(); // { FileMetadata.id : Boolean }
+ private Map mapLayerMetadataLookup = null;
+ private final Map datasetPermissionMap = new HashMap<>(); // { Permission human_name : Boolean }
+
+
+ public WorldMapPermissionHelper( ){
+
+ }
+
+
+ /**
+ * Using a DataFile id, retrieve an associated MapLayerMetadata object
+ *
+ * The MapLayerMetadata objects have been fetched at page inception by
+ * "loadMapLayerMetadataLookup()"
+ */
+ public MapLayerMetadata getMapLayerMetadata(DataFile df) {
+ if (df == null) {
+ return null;
+ }
+ if (mapLayerMetadataLookup == null){
+ loadMapLayerMetadataLookup(df.getOwner());
+ }
+ return this.mapLayerMetadataLookup.get(df.getId());
+ }
+
+
+ /*
+ * Call this when using the API
+ * - calls private method canUserSeeExploreWorldMapButton
+ */
+ public boolean canUserSeeExploreWorldMapButtonFromAPI(FileMetadata fm, User user){
+
+ if (fm == null){
+ return false;
+ }
+ if (user==null){
+ return false;
+ }
+ if (!this.permissionService.userOn(user, fm.getDataFile()).has(Permission.DownloadFile)){
+ return false;
+ }
+
+ return this.canUserSeeExploreWorldMapButton(fm, true);
+ }
+
+ /**
+ * Call this from a Dataset or File page
+ * - calls private method canUserSeeExploreWorldMapButton
+ *
+ * WARNING: Before calling this, make sure the user has download
+ * permission for the file!! (See DatasetPage.canDownloadFile())
+ *
+ * @param FileMetadata fm
+ * @return boolean
+ */
+ public boolean canUserSeeExploreWorldMapButtonFromPage(FileMetadata fm){
+
+ if (fm==null){
+ return false;
+ }
+ return this.canUserSeeExploreWorldMapButton(fm, true);
+ }
+
+ /**
+ * WARNING: Before calling this, make sure the user has download
+ * permission for the file!! (See DatasetPage.canDownloadFile())
+ *
+ * Should there be a Explore WorldMap Button for this file?
+ * See table in: https://github.com/IQSS/dataverse/issues/1618
+ *
+ * (1) Does the file have MapLayerMetadata?
+ * (2) Are the proper settings in place
+ *
+ * @param fm FileMetadata
+ * @return boolean
+ */
+ private boolean canUserSeeExploreWorldMapButton(FileMetadata fm, boolean permissionsChecked){
+ if (fm==null){
+ return false;
+ }
+ // This is only here to make the public method users think...
+ if (!permissionsChecked){
+ return false;
+ }
+ if (this.fileMetadataWorldMapExplore.containsKey(fm.getId())){
+ // Yes, return previous answer
+ //logger.info("using cached result for candownloadfile on filemetadata "+fid);
+ return this.fileMetadataWorldMapExplore.get(fm.getId());
+ }
+
+ /* -----------------------------------------------------
+ Does a Map Exist?
+ ----------------------------------------------------- */
+ if (!(this.hasMapLayerMetadata(fm))) {
+ //See if it does
+ MapLayerMetadata layer_metadata = mapLayerMetadataService.findMetadataByDatafile(fm.getDataFile());
+ if (layer_metadata != null) {
+ if (mapLayerMetadataLookup == null) {
+ loadMapLayerMetadataLookup(fm.getDataFile().getOwner());
+ }
+ // yes: keep going...
+ mapLayerMetadataLookup.put(layer_metadata.getDataFile().getId(), layer_metadata);
+ } else {
+ // Nope: no button
+ this.fileMetadataWorldMapExplore.put(fm.getId(), false);
+ return false;
+ }
+ }
+
+ /*
+ Is setting for GeoconnectViewMaps true?
+ Nope? no button
+ */
+ if (!settingsService.isTrueForKey(SettingsServiceBean.Key.GeoconnectViewMaps, false)){
+ this.fileMetadataWorldMapExplore.put(fm.getId(), false);
+ return false;
+ }
+ //----------------------------------------------------------------------
+ //(0) Before we give it to you - if version is deaccessioned and user
+ // does not have edit dataset permission then may download
+ //----------------------------------------------------------------------
+
+ if (fm.getDatasetVersion().isDeaccessioned()) {
+ if (this.doesSessionUserHavePermission( Permission.EditDataset, fm)) {
+ // Yes, save answer and return true
+ this.fileMetadataWorldMapExplore.put(fm.getId(), true);
+ return true;
+ } else {
+ this.fileMetadataWorldMapExplore.put(fm.getId(), false);
+ return false;
+ }
+ }
+ //Check for restrictions
+
+ boolean isRestrictedFile = fm.isRestricted();
+
+ // --------------------------------------------------------------------
+ // Is the file Unrestricted ?
+ // --------------------------------------------------------------------
+ if (!isRestrictedFile){
+ // Yes, save answer and return true
+ this.fileMetadataWorldMapExplore.put(fm.getId(), true);
+ return true;
+ }
+
+ // --------------------------------------------------------------------
+ // Conditions (2) through (4) are for Restricted files
+ // --------------------------------------------------------------------
+
+
+ if (session.getUser() instanceof GuestUser){
+ this.fileMetadataWorldMapExplore.put(fm.getId(), false);
+ return false;
+ }
+
+
+ // --------------------------------------------------------------------
+ // (3) Does the User have DownloadFile Permission at the **Dataset** level
+ // --------------------------------------------------------------------
+
+
+ if (!this.doesSessionUserHavePermission(Permission.DownloadFile, fm)){
+ // Yes, save answer and return true
+ this.fileMetadataWorldMapExplore.put(fm.getId(), false);
+ return false;
+ }
+
+ /* -----------------------------------------------------
+ Yes: User can view button!
+ ----------------------------------------------------- */
+ this.fileMetadataWorldMapExplore.put(fm.getId(), true);
+ return true;
+ }
+
+
+ /*
+ Check if the FileMetadata.dataFile has an associated MapLayerMetadata object
+
+ The MapLayerMetadata objects have been fetched at page inception by "loadMapLayerMetadataLookup()"
+ */
+ public boolean hasMapLayerMetadata(FileMetadata fm) {
+ if (fm == null) {
+ return false;
+ }
+ if (fm.getDataFile() == null) {
+ return false;
+ }
+ if (mapLayerMetadataLookup == null) {
+ loadMapLayerMetadataLookup(fm.getDataFile().getOwner());
+ }
+ return doesDataFileHaveMapLayerMetadata(fm.getDataFile());
+ }
+
+ /**
+ * Check if a DataFile has an associated MapLayerMetadata object
+ *
+ * The MapLayerMetadata objects have been fetched at page inception by
+ * "loadMapLayerMetadataLookup()"
+ */
+ private boolean doesDataFileHaveMapLayerMetadata(DataFile df) {
+ if (df == null) {
+ return false;
+ }
+ if (df.getId() == null) {
+ return false;
+ }
+ return this.mapLayerMetadataLookup.containsKey(df.getId());
+ }
+
+
+ /**
+ * Create a hashmap consisting of { DataFile.id : MapLayerMetadata object}
+ *
+ * Very few DataFiles will have associated MapLayerMetadata objects so only
+ * use 1 query to get them
+ */
+ private void loadMapLayerMetadataLookup(Dataset dataset) {
+ mapLayerMetadataLookup = new HashMap<>();
+ if (dataset == null) {
+ }
+ if (dataset.getId() == null) {
+ return;
+ }
+ List mapLayerMetadataList = mapLayerMetadataService.getMapLayerMetadataForDataset(dataset);
+ if (mapLayerMetadataList == null) {
+ return;
+ }
+ for (MapLayerMetadata layer_metadata : mapLayerMetadataList) {
+ mapLayerMetadataLookup.put(layer_metadata.getDataFile().getId(), layer_metadata);
+ }
+
+ }// A DataFile may have a related MapLayerMetadata object
+
+
+ /**
+ * Check if this is a mappable file type.
+ *
+ * Currently (2/2016)
+ * - Shapefile (zipped shapefile)
+ * - Tabular file with Geospatial Data tag
+ *
+ * @param fm
+ * @return
+ */
+ private boolean isPotentiallyMappableFileType(FileMetadata fm){
+ if (fm==null){
+ return false;
+ }
+
+ // Yes, it's a shapefile
+ //
+ if (this.isShapefileType(fm)){
+ return true;
+ }
+
+ // Yes, it's tabular with a geospatial tag
+ //
+ if (fm.getDataFile().isTabularData()){
+ if (fm.getDataFile().hasGeospatialTag()){
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+
+ public boolean isShapefileType(FileMetadata fm) {
+ if (fm == null) {
+ return false;
+ }
+ if (fm.getDataFile() == null) {
+ return false;
+ }
+
+ return fm.getDataFile().isShapefileType();
+ }
+
+
+ /**
+ * Call this from a Dataset or File page
+ * - calls private method canSeeMapButtonReminderToPublish
+ *
+ * WARNING: Assumes user isAuthenicated AND has Permission.EditDataset
+ * - These checks should be made on the DatasetPage or FilePage which calls this method
+ *
+ *
+ * @param FileMetadata fm
+ * @return boolean
+ */
+ public boolean canSeeMapButtonReminderToPublishFromPage(FileMetadata fm){
+ if (fm == null){
+ return false;
+ }
+
+ if (mapLayerMetadataLookup == null){
+ loadMapLayerMetadataLookup(fm.getDatasetVersion().getDataset());
+ }
+
+ return this.canSeeMapButtonReminderToPublish(fm, true);
+
+ }
+
+
+ /**
+ * Call this when using the API
+ * - calls private method canSeeMapButtonReminderToPublish
+ *
+ * @param fm
+ * @param user
+ * @return
+ */
+ public boolean canSeeMapButtonReminderToPublishFromAPI(FileMetadata fm, User user){
+ if (fm == null){
+ return false;
+ }
+ if (user==null){
+ return false;
+ }
+
+ if (!this.permissionService.userOn(user, fm.getDataFile().getOwner()).has(Permission.EditDataset)){
+ return false;
+ }
+
+ return this.canSeeMapButtonReminderToPublish(fm, true);
+
+ }
+
+
+
+ /**
+ * Assumes permissions have been checked!!
+ *
+ * See table in: https://github.com/IQSS/dataverse/issues/1618
+ *
+ * Can the user see a reminder to publish button?
+ * (1) Is the view GeoconnectViewMaps
+ * (2) Is this file a Shapefile or a Tabular file tagged as Geospatial?
+ * (3) Is this DataFile released? Yes, don't need reminder
+ * (4) Does a map already exist? Yes, don't need reminder
+ */
+ private boolean canSeeMapButtonReminderToPublish(FileMetadata fm, boolean permissionsChecked){
+ if (fm==null){
+ return false;
+ }
+
+ // Is this user authenticated with EditDataset permission?
+ //
+ if (!(isUserAuthenticatedWithEditDatasetPermission(fm))){
+ return false;
+ }
+
+ // This is only here as a reminder to the public method users
+ if (!permissionsChecked){
+ return false;
+ }
+
+ // (1) Is the view GeoconnectViewMaps
+ if (!settingsService.isTrueForKey(SettingsServiceBean.Key.GeoconnectCreateEditMaps, false)){
+ return false;
+ }
+
+
+ // (2) Is this file a Shapefile or a Tabular file tagged as Geospatial?
+ //
+ if (!(this.isPotentiallyMappableFileType(fm))){
+ return false;
+ }
+
+ // (3) Is this DataFile released? Yes, don't need reminder
+ //
+ if (fm.getDataFile().isReleased()){
+ return false;
+ }
+
+ // (4) Does a map already exist? Yes, don't need reminder
+ //
+ if (this.hasMapLayerMetadata(fm)){
+ return false;
+ }
+
+ // Looks good
+ //
+ return true;
+ }
+
+ /**
+ *
+ * WARNING: Assumes user isAuthenicated AND has Permission.EditDataset
+ * - These checks are made on the DatasetPage which calls this method
+ *
+ */
+ public boolean canUserSeeMapDataButtonFromPage(FileMetadata fm){
+
+ if (fm==null){
+ return false;
+ }
+
+ // Is this user authenticated with EditDataset permission?
+ //
+ if (!(isUserAuthenticatedWithEditDatasetPermission(fm))){
+ return false;
+ }
+ if (mapLayerMetadataLookup == null){
+ loadMapLayerMetadataLookup(fm.getDatasetVersion().getDataset());
+ }
+ if (this.hasMapLayerMetadata(fm)){
+ return false;
+ }
+ return this.canUserSeeMapDataButton(fm, true);
+ }
+
+
+
+ /**
+ * Call this when using the API
+ * - calls private method canUserSeeMapDataButton
+ *
+ * @param fm
+ * @param user
+ * @return
+ */
+ public boolean canUserSeeMapDataButtonFromAPI(FileMetadata fm, User user){
+ if (fm == null){
+ return false;
+ }
+ if (user==null){
+ return false;
+ }
+
+ if (!this.permissionService.userOn(user, fm.getDataFile().getOwner()).has(Permission.EditDataset)){
+ return false;
+ }
+
+ return this.canUserSeeMapDataButton(fm, true);
+
+ }
+
+ /**
+ *
+ * WARNING: Assumes user isAuthenicated AND has Permission.EditDataset
+ * - These checks are made on the DatasetPage which calls this method
+ *
+ * Should there be a Map Data Button for this file?
+ * see table in: https://github.com/IQSS/dataverse/issues/1618
+ * (1) Is the user logged in?
+ * (2) Is this file a Shapefile or a Tabular file tagged as Geospatial?
+ * (3) Does the logged in user have permission to edit the Dataset to which this FileMetadata belongs?
+ * (4) Is the create Edit Maps flag set to true?
+ * (5) Any of these conditions:
+ * 9a) File Published
+ * (b) Draft: File Previously published
+ * @param fm FileMetadata
+ * @return boolean
+ */
+ private boolean canUserSeeMapDataButton(FileMetadata fm, boolean permissionsChecked){
+ if (fm==null){
+ return false;
+ }
+
+ // This is only here as a reminder to the public method users
+ if (!permissionsChecked){
+
+ return false;
+ }
+
+ // (1) Is this file a Shapefile or a Tabular file tagged as Geospatial?
+ // TO DO: EXPAND FOR TABULAR FILES TAGGED AS GEOSPATIAL!
+ //
+ if (!(this.isPotentiallyMappableFileType(fm))){
+
+ return false;
+ }
+
+
+ // (2) Is the view GeoconnectViewMaps
+ if (!settingsService.isTrueForKey(SettingsServiceBean.Key.GeoconnectCreateEditMaps, false)){
+
+ return false;
+ }
+
+ // (3) Is File released?
+ //
+ if (fm.getDataFile().isReleased()){
+
+ return true;
+ }
+
+ // Nope
+ return false;
+ }
+
+ private boolean isUserAuthenticatedWithEditDatasetPermission( FileMetadata fm){
+
+ // Is the user authenticated?
+ //
+ if (!(isSessionUserAuthenticated())){
+ return false;
+ }
+
+ // If so, can the logged in user edit the Dataset to which this FileMetadata belongs?
+ //
+ if (!this.doesSessionUserHavePermission(Permission.EditDataset, fm)){
+ return false;
+ }
+
+ return true;
+ }
+
+ public boolean isSessionUserAuthenticated() {
+
+
+ if (session == null) {
+ return false;
+ }
+
+ if (session.getUser() == null) {
+ return false;
+ }
+
+ return session.getUser().isAuthenticated();
+
+ }
+
+ private boolean doesSessionUserHavePermission(Permission permissionToCheck, FileMetadata fileMetadata){
+ if (permissionToCheck == null){
+ return false;
+ }
+
+ DvObject objectToCheck = null;
+
+ if (permissionToCheck.equals(Permission.EditDataset)){
+ objectToCheck = fileMetadata.getDatasetVersion().getDataset();
+ } else if (permissionToCheck.equals(Permission.DownloadFile)){
+ objectToCheck = fileMetadata.getDataFile();
+ }
+
+ if (objectToCheck == null){
+ return false;
+ }
+
+ if (this.session.getUser() == null){
+ return false;
+ }
+
+ if (this.permissionService == null){
+ return false;
+ }
+
+ String permName = permissionToCheck.getHumanName();
+
+ // Has this check already been done?
+ //
+ if (this.datasetPermissionMap.containsKey(permName)){
+ // Yes, return previous answer
+ return this.datasetPermissionMap.get(permName);
+ }
+
+ // Check the permission
+ //
+
+ boolean hasPermission = this.permissionService.userOn(this.session.getUser(), objectToCheck).has(permissionToCheck);
+
+ // Save the permission
+ this.datasetPermissionMap.put(permName, hasPermission);
+
+ // return true/false
+ return hasPermission;
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/main/webapp/dataset-citation.xhtml b/src/main/webapp/dataset-citation.xhtml
index ea59da57c3d..1df6b7ee929 100644
--- a/src/main/webapp/dataset-citation.xhtml
+++ b/src/main/webapp/dataset-citation.xhtml
@@ -11,9 +11,9 @@
-
+
-
+
@@ -25,17 +25,17 @@