use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class CollectionListManagerImpl method listCollectionContents.
@Override
public Feed listCollectionContents(IRI iri, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordServerException, SwordAuthException, SwordError {
AuthenticatedUser user = swordAuth.auth(authCredentials);
DataverseRequest dvReq = new DataverseRequest(user, request);
urlManager.processUrl(iri.toString());
String dvAlias = urlManager.getTargetIdentifier();
if (urlManager.getTargetType().equals("dataverse") && dvAlias != null) {
Dataverse dv = dataverseService.findByAlias(dvAlias);
if (dv != null) {
/**
* We'll say having AddDataset is enough to use this API
* endpoint, which means you are a Contributor to that
* dataverse. If we let just anyone call this endpoint, they
* will be able to see if the supplied dataverse is published or
* not.
*/
if (!permissionService.requestOn(dvReq, dv).has(Permission.AddDataset)) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to list datasets in dataverse " + dv.getAlias());
}
Abdera abdera = new Abdera();
Feed feed = abdera.newFeed();
feed.setTitle(dv.getName());
String baseUrl = urlManager.getHostnamePlusBaseUrlPath(iri.toString());
List<Dataset> datasets = datasetService.findByOwnerId(dv.getId());
for (Dataset dataset : datasets) {
/**
* @todo Will this be performant enough with production
* data, say in the root dataverse? Remove this todo if
* there are no complaints. :)
*/
if (!permissionService.isUserAllowedOn(user, new UpdateDatasetCommand(dataset, dvReq), dataset)) {
continue;
}
String editUri = baseUrl + "/edit/study/" + dataset.getGlobalId();
String editMediaUri = baseUrl + "/edit-media/study/" + dataset.getGlobalId();
Entry entry = feed.addEntry();
entry.setId(editUri);
entry.setTitle(datasetService.getTitleFromLatestVersion(dataset.getId()));
entry.setBaseUri(new IRI(editUri));
entry.addLink(editMediaUri, "edit-media");
feed.addEntry(entry);
}
Boolean dvHasBeenReleased = dv.isReleased();
feed.addSimpleExtension(new QName(UriRegistry.SWORD_STATE, "dataverseHasBeenReleased"), dvHasBeenReleased.toString());
return feed;
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataverse: " + dvAlias);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't determine target type or identifer from URL: " + iri);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class MediaResourceManagerImpl method replaceOrAddFiles.
DepositReceipt replaceOrAddFiles(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration, boolean shouldReplace) throws SwordError, SwordAuthException, SwordServerException {
AuthenticatedUser user = swordAuth.auth(authCredentials);
DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
urlManager.processUrl(uri);
String globalId = urlManager.getTargetIdentifier();
if (urlManager.getTargetType().equals("study") && globalId != null) {
logger.fine("looking up dataset with globalId " + globalId);
Dataset dataset = datasetService.findByGlobalId(globalId);
if (dataset == null) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset with global ID of " + globalId);
}
UpdateDatasetCommand updateDatasetCommand = new UpdateDatasetCommand(dataset, dvReq);
if (!permissionService.isUserAllowedOn(user, updateDatasetCommand, dataset)) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to modify dataset with global ID " + dataset.getGlobalId());
}
// -------------------------------------
if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, SettingsServiceBean.Key.UploadMethods + " contains " + SystemConfig.FileUploadMethods.RSYNC + ". Please use rsync file upload.");
}
/**
* @todo decide if we want non zip files to work. Technically, now
* that we're letting ingestService.createDataFiles unpack the zip
* for us, the following *does* work:
*
* curl--data-binary @path/to/trees.png -H "Content-Disposition:
* filename=trees.png" -H "Content-Type: image/png" -H "Packaging:
* http://purl.org/net/sword/package/SimpleZip"
*
* We *might* want to continue to force API users to only upload zip
* files so that some day we can support a including a file or files
* that contain the metadata (i.e. description) for each file in the
* zip: https://github.com/IQSS/dataverse/issues/723
*/
if (!deposit.getPackaging().equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) {
throw new SwordError(UriRegistry.ERROR_CONTENT, 415, "Package format " + UriRegistry.PACKAGE_SIMPLE_ZIP + " is required but format specified in 'Packaging' HTTP header was " + deposit.getPackaging());
}
String uploadedZipFilename = deposit.getFilename();
DatasetVersion editVersion = dataset.getEditVersion();
if (deposit.getInputStream() == null) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Deposit input stream was null.");
}
int bytesAvailableInInputStream = 0;
try {
bytesAvailableInInputStream = deposit.getInputStream().available();
} catch (IOException ex) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine number of bytes available in input stream: " + ex);
}
if (bytesAvailableInInputStream == 0) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Bytes available in input stream was " + bytesAvailableInInputStream + ". Please check the file you are attempting to deposit.");
}
/**
* @todo Think about if we should instead pass in "application/zip"
* rather than letting ingestService.createDataFiles() guess the
* contentType by passing it "null". See also the note above about
* SimpleZip vs. other contentTypes.
*/
String guessContentTypeForMe = null;
List<DataFile> dataFiles = new ArrayList<>();
try {
try {
dataFiles = FileUtil.createDataFiles(editVersion, deposit.getInputStream(), uploadedZipFilename, guessContentTypeForMe, systemConfig);
} catch (EJBException ex) {
Throwable cause = ex.getCause();
if (cause != null) {
if (cause instanceof IllegalArgumentException) {
/**
* @todo should be safe to remove this catch of
* EJBException and IllegalArgumentException once
* this ticket is resolved:
*
* IllegalArgumentException: MALFORMED when
* uploading certain zip files
* https://github.com/IQSS/dataverse/issues/1021
*/
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles. Problem with zip file, perhaps: " + cause);
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles: " + cause);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles. No cause: " + ex.getMessage());
}
}
/*TODO: L.A. 4.6! catch (FileExceedsMaxSizeException ex) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles: " + ex.getMessage());
//Logger.getLogger(MediaResourceManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
}*/
} catch (IOException ex) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to dataset: " + ex.getMessage());
}
if (!dataFiles.isEmpty()) {
Set<ConstraintViolation> constraintViolations = editVersion.validate();
if (constraintViolations.size() > 0) {
ConstraintViolation violation = constraintViolations.iterator().next();
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to dataset: " + violation.getMessage() + " The invalid value was \"" + violation.getInvalidValue() + "\".");
} else {
ingestService.addFiles(editVersion, dataFiles);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No files to add to dataset. Perhaps the zip file was empty.");
}
try {
dataset = commandEngine.submit(updateDatasetCommand);
} catch (CommandException ex) {
throw returnEarly("Couldn't update dataset " + ex);
} catch (EJBException ex) {
/**
* @todo stop bothering to catch an EJBException once this has
* been implemented:
*
* Have commands catch ConstraintViolationException and turn
* them into something that inherits from CommandException ยท
* https://github.com/IQSS/dataverse/issues/1009
*/
Throwable cause = ex;
StringBuilder sb = new StringBuilder();
sb.append(ex.getLocalizedMessage());
while (cause.getCause() != null) {
cause = cause.getCause();
sb.append(cause + " ");
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) {
sb.append(" Invalid value \"").append(violation.getInvalidValue()).append("\" for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
}
}
}
throw returnEarly("EJBException: " + sb.toString());
}
ingestService.startIngestJobs(dataset, user);
ReceiptGenerator receiptGenerator = new ReceiptGenerator();
String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri);
DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, dataset);
return depositReceipt;
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to determine target type or identifier from URL: " + uri);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class MediaResourceManagerImpl method deleteMediaResource.
@Override
public void deleteMediaResource(String uri, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
AuthenticatedUser user = swordAuth.auth(authCredentials);
DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
urlManager.processUrl(uri);
String targetType = urlManager.getTargetType();
String fileId = urlManager.getTargetIdentifier();
if (targetType != null && fileId != null) {
if ("file".equals(targetType)) {
String fileIdString = urlManager.getTargetIdentifier();
if (fileIdString != null) {
Long fileIdLong;
try {
fileIdLong = Long.valueOf(fileIdString);
} catch (NumberFormatException ex) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "File id must be a number, not '" + fileIdString + "'. URL was: " + uri);
}
if (fileIdLong != null) {
logger.fine("preparing to delete file id " + fileIdLong);
DataFile fileToDelete = dataFileService.find(fileIdLong);
if (fileToDelete != null) {
Dataset dataset = fileToDelete.getOwner();
Dataset datasetThatOwnsFile = fileToDelete.getOwner();
Dataverse dataverseThatOwnsFile = datasetThatOwnsFile.getOwner();
/**
* @todo it would be nice to have this check higher
* up. Do we really need the file ID? Should the
* last argument to isUserAllowedOn be changed from
* "dataset" to "fileToDelete"?
*/
UpdateDatasetCommand updateDatasetCommand = new UpdateDatasetCommand(dataset, dvReq, fileToDelete);
if (!permissionService.isUserAllowedOn(user, updateDatasetCommand, dataset)) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to modify " + dataverseThatOwnsFile.getAlias());
}
try {
commandEngine.submit(updateDatasetCommand);
} catch (CommandException ex) {
throw SwordUtil.throwSpecialSwordErrorWithoutStackTrace(UriRegistry.ERROR_BAD_REQUEST, "Could not delete file: " + ex);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to find file id " + fileIdLong + " from URL: " + uri);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to find file id in URL: " + uri);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not file file to delete in URL: " + uri);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unsupported file type found in URL: " + uri);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Target or identifer not specified in URL: " + uri);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class MediaResourceManagerImpl method getMediaResourceRepresentation.
@Override
public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> map, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
AuthenticatedUser user = swordAuth.auth(authCredentials);
DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
urlManager.processUrl(uri);
String globalId = urlManager.getTargetIdentifier();
if (urlManager.getTargetType().equals("study") && globalId != null) {
logger.fine("looking up dataset with globalId " + globalId);
Dataset dataset = datasetService.findByGlobalId(globalId);
if (dataset != null) {
/**
* @todo: support downloading of files (SWORD 2.0 Profile 6.4. -
* Retrieving the content)
* http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_retrievingcontent
*
* This ticket is mostly about terms of use:
* https://github.com/IQSS/dataverse/issues/183
*/
boolean getMediaResourceRepresentationSupported = false;
if (getMediaResourceRepresentationSupported) {
Dataverse dvThatOwnsDataset = dataset.getOwner();
/**
* @todo Add Dataverse 4 style permission check here. Is
* there a Command we use for downloading files as zip?
*/
boolean authorized = false;
if (authorized) {
/**
* @todo Zip file download is being implemented in
* https://github.com/IQSS/dataverse/issues/338
*/
InputStream fixmeInputStream = new ByteArrayInputStream("FIXME: replace with zip of all dataset files".getBytes());
String contentType = "application/zip";
String packaging = UriRegistry.PACKAGE_SIMPLE_ZIP;
boolean isPackaged = true;
MediaResource mediaResource = new MediaResource(fixmeInputStream, contentType, packaging, isPackaged);
return mediaResource;
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to get a media resource representation of the dataset with global ID " + dataset.getGlobalId());
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Downloading files via the SWORD-based Dataverse Data Deposit API is not (yet) supported: https://github.com/IQSS/dataverse/issues/183");
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't find dataset with global ID of " + globalId);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't dermine target type or identifier from URL: " + uri);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class StatementManagerImpl method getStatement.
@Override
public Statement getStatement(String editUri, Map<String, String> map, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordServerException, SwordError, SwordAuthException {
AuthenticatedUser user = swordAuth.auth(authCredentials);
DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
urlManager.processUrl(editUri);
String globalId = urlManager.getTargetIdentifier();
if (urlManager.getTargetType().equals("study") && globalId != null) {
logger.fine("request for sword statement by user " + user.getDisplayInfo().getTitle());
Dataset dataset = datasetService.findByGlobalId(globalId);
if (dataset == null) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "couldn't find dataset with global ID of " + globalId);
}
Dataverse dvThatOwnsDataset = dataset.getOwner();
if (!permissionService.isUserAllowedOn(user, new GetDraftDatasetVersionCommand(dvReq, dataset), dataset)) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to view dataset with global ID " + globalId);
}
String feedUri = urlManager.getHostnamePlusBaseUrlPath(editUri) + "/edit/study/" + dataset.getGlobalId();
String author = dataset.getLatestVersion().getAuthorsStr();
String title = dataset.getLatestVersion().getTitle();
// in the statement, the element is called "updated"
Date lastUpdatedFinal = new Date();
Date lastUpdateTime = dataset.getLatestVersion().getLastUpdateTime();
if (lastUpdateTime != null) {
lastUpdatedFinal = lastUpdateTime;
} else {
logger.info("lastUpdateTime was null, trying createtime");
Date createtime = dataset.getLatestVersion().getCreateTime();
if (createtime != null) {
lastUpdatedFinal = createtime;
} else {
logger.info("creatime was null, using \"now\"");
lastUpdatedFinal = new Date();
}
}
AtomDate atomDate = new AtomDate(lastUpdatedFinal);
String datedUpdated = atomDate.toString();
Statement statement = new AtomStatement(feedUri, author, title, datedUpdated);
Map<String, String> states = new HashMap<>();
states.put("latestVersionState", dataset.getLatestVersion().getVersionState().toString());
Boolean isMinorUpdate = dataset.getLatestVersion().isMinorUpdate();
states.put("isMinorUpdate", isMinorUpdate.toString());
if (dataset.isLocked()) {
states.put("locked", "true");
states.put("lockedDetail", dataset.getLocks().stream().map(l -> l.getInfo()).collect(joining(",")));
Optional<DatasetLock> earliestLock = dataset.getLocks().stream().min((l1, l2) -> (int) Math.signum(l1.getStartTime().getTime() - l2.getStartTime().getTime()));
states.put("lockedStartTime", earliestLock.get().getStartTime().toString());
} else {
states.put("locked", "false");
}
statement.setStates(states);
List<FileMetadata> fileMetadatas = dataset.getLatestVersion().getFileMetadatas();
for (FileMetadata fileMetadata : fileMetadatas) {
DataFile dataFile = fileMetadata.getDataFile();
// We are exposing the filename for informational purposes. The file id is what you
// actually operate on to delete a file, etc.
//
// Replace spaces to avoid IRISyntaxException
String fileNameFinal = fileMetadata.getLabel().replace(' ', '_');
String fileUrlString = urlManager.getHostnamePlusBaseUrlPath(editUri) + "/edit-media/file/" + dataFile.getId() + "/" + fileNameFinal;
IRI fileUrl;
try {
fileUrl = new IRI(fileUrlString);
} catch (IRISyntaxException ex) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Invalid URL for file ( " + fileUrlString + " ) resulted in " + ex.getMessage());
}
ResourcePart resourcePart = new ResourcePart(fileUrl.toString());
// default to something that doesn't throw a org.apache.abdera.util.MimeTypeParseException
String finalFileFormat = "application/octet-stream";
String contentType = dataFile.getContentType();
if (contentType != null) {
finalFileFormat = contentType;
}
resourcePart.setMediaType(finalFileFormat);
/**
* @todo: Why are properties set on a ResourcePart not exposed
* when you GET a Statement? Asked about this at
* http://www.mail-archive.com/sword-app-tech@lists.sourceforge.net/msg00394.html
*/
// Map<String, String> properties = new HashMap<String, String>();
// properties.put("filename", studyFile.getFileName());
// properties.put("category", studyFile.getLatestCategory());
// properties.put("originalFileType", studyFile.getOriginalFileType());
// properties.put("id", studyFile.getId().toString());
// properties.put("UNF", studyFile.getUnf());
// resourcePart.setProperties(properties);
statement.addResource(resourcePart);
/**
* @todo it's been noted at
* https://github.com/IQSS/dataverse/issues/892#issuecomment-54159284
* that at the file level the "updated" date is always "now",
* which seems to be set here:
* https://github.com/swordapp/JavaServer2.0/blob/sword2-server-1.0/src/main/java/org/swordapp/server/AtomStatement.java#L70
*/
}
return statement;
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine target type or identifier from URL: " + editUri);
}
}
Aggregations