use of edu.harvard.iq.dataverse.Dataset in project dataverse by IQSS.
the class Index method filesearch.
@GET
@Path("filesearch")
public Response filesearch(@QueryParam("persistentId") String persistentId, @QueryParam("semanticVersion") String semanticVersion, @QueryParam("q") String userSuppliedQuery) {
Dataset dataset = datasetService.findByGlobalId(persistentId);
if (dataset == null) {
return error(Status.BAD_REQUEST, "Could not find dataset with persistent id " + persistentId);
}
User user = GuestUser.get();
try {
AuthenticatedUser authenticatedUser = findAuthenticatedUserOrDie();
if (authenticatedUser != null) {
user = authenticatedUser;
}
} catch (WrappedResponse ex) {
}
RetrieveDatasetVersionResponse datasetVersionResponse = datasetVersionService.retrieveDatasetVersionByPersistentId(persistentId, semanticVersion);
if (datasetVersionResponse == null) {
return error(Status.BAD_REQUEST, "Problem searching for files. Could not find dataset version based on " + persistentId + " and " + semanticVersion);
}
DatasetVersion datasetVersion = datasetVersionResponse.getDatasetVersion();
FileView fileView = searchFilesService.getFileView(datasetVersion, user, userSuppliedQuery);
if (fileView == null) {
return error(Status.BAD_REQUEST, "Problem searching for files. Null returned from getFileView.");
}
JsonArrayBuilder filesFound = Json.createArrayBuilder();
JsonArrayBuilder cards = Json.createArrayBuilder();
JsonArrayBuilder fileIds = Json.createArrayBuilder();
for (SolrSearchResult result : fileView.getSolrSearchResults()) {
cards.add(result.getNameSort());
fileIds.add(result.getEntityId());
JsonObjectBuilder fileFound = Json.createObjectBuilder();
fileFound.add("name", result.getNameSort());
fileFound.add("entityId", result.getEntityId().toString());
fileFound.add("datasetVersionId", result.getDatasetVersionId());
fileFound.add("datasetId", result.getParent().get(SearchFields.ID));
filesFound.add(fileFound);
}
JsonArrayBuilder facets = Json.createArrayBuilder();
for (FacetCategory facetCategory : fileView.getFacetCategoryList()) {
facets.add(facetCategory.getFriendlyName());
}
JsonArrayBuilder filterQueries = Json.createArrayBuilder();
for (String filterQuery : fileView.getFilterQueries()) {
filterQueries.add(filterQuery);
}
JsonArrayBuilder allDatasetVersionIds = Json.createArrayBuilder();
for (DatasetVersion dsVersion : dataset.getVersions()) {
allDatasetVersionIds.add(dsVersion.getId());
}
JsonObjectBuilder data = Json.createObjectBuilder();
data.add("filesFound", filesFound);
data.add("cards", cards);
data.add("fileIds", fileIds);
data.add("facets", facets);
data.add("user", user.getIdentifier());
data.add("persistentID", persistentId);
data.add("query", fileView.getQuery());
data.add("filterQueries", filterQueries);
data.add("allDataverVersionIds", allDatasetVersionIds);
data.add("semanticVersion", datasetVersion.getSemanticVersion());
return ok(data);
}
use of edu.harvard.iq.dataverse.Dataset in project dataverse by IQSS.
the class Datasets method receiveChecksumValidationResults.
@POST
@Path("{identifier}/dataCaptureModule/checksumValidation")
public Response receiveChecksumValidationResults(@PathParam("identifier") String id, JsonObject jsonFromDcm) {
logger.log(Level.FINE, "jsonFromDcm: {0}", jsonFromDcm);
AuthenticatedUser authenticatedUser = null;
try {
authenticatedUser = findAuthenticatedUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.BAD_REQUEST, "Authentication is required.");
}
if (!authenticatedUser.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
String statusMessageFromDcm = jsonFromDcm.getString("status");
try {
Dataset dataset = findDatasetOrDie(id);
if ("validation passed".equals(statusMessageFromDcm)) {
String uploadFolder = jsonFromDcm.getString("uploadFolder");
int totalSize = jsonFromDcm.getInt("totalSize");
ImportMode importMode = ImportMode.MERGE;
try {
JsonObject jsonFromImportJobKickoff = execCommand(new ImportFromFileSystemCommand(createDataverseRequest(findUserOrDie()), dataset, uploadFolder, new Long(totalSize), importMode));
long jobId = jsonFromImportJobKickoff.getInt("executionId");
String message = jsonFromImportJobKickoff.getString("message");
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("jobId", jobId);
job.add("message", message);
return ok(job);
} catch (WrappedResponse wr) {
String message = wr.getMessage();
return error(Response.Status.INTERNAL_SERVER_ERROR, "Uploaded files have passed checksum validation but something went wrong while attempting to put the files into Dataverse. Message was '" + message + "'.");
}
} else if ("validation failed".equals(statusMessageFromDcm)) {
Map<String, AuthenticatedUser> distinctAuthors = permissionService.getDistinctUsersWithPermissionOn(Permission.EditDataset, dataset);
distinctAuthors.values().forEach((value) -> {
userNotificationService.sendNotification((AuthenticatedUser) value, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
List<AuthenticatedUser> superUsers = authenticationServiceBean.findSuperUsers();
if (superUsers != null && !superUsers.isEmpty()) {
superUsers.forEach((au) -> {
userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
}
return ok("User notified about checksum validation failure.");
} else {
return error(Response.Status.BAD_REQUEST, "Unexpected status cannot be processed: " + statusMessageFromDcm);
}
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
use of edu.harvard.iq.dataverse.Dataset in project dataverse by IQSS.
the class Datasets method getLinks.
@GET
@Path("{id}/links")
public Response getLinks(@PathParam("id") String idSupplied) {
try {
User u = findUserOrDie();
if (!u.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Not a superuser");
}
Dataset dataset = findDatasetOrDie(idSupplied);
long datasetId = dataset.getId();
List<Dataverse> dvsThatLinkToThisDatasetId = dataverseSvc.findDataversesThatLinkToThisDatasetId(datasetId);
JsonArrayBuilder dataversesThatLinkToThisDatasetIdBuilder = Json.createArrayBuilder();
for (Dataverse dataverse : dvsThatLinkToThisDatasetId) {
dataversesThatLinkToThisDatasetIdBuilder.add(dataverse.getAlias() + " (id " + dataverse.getId() + ")");
}
JsonObjectBuilder response = Json.createObjectBuilder();
response.add("dataverses that link to dataset id " + datasetId, dataversesThatLinkToThisDatasetIdBuilder);
return ok(response);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
use of edu.harvard.iq.dataverse.Dataset in project dataverse by IQSS.
the class Datasets method addFileToDataset.
/**
* Add a File to an existing Dataset
*
* @param idSupplied
* @param jsonData
* @param fileInputStream
* @param contentDispositionHeader
* @param formDataBodyPart
* @return
*/
@POST
@Path("{id}/add")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response addFileToDataset(@PathParam("id") String idSupplied, @FormDataParam("jsonData") String jsonData, @FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition contentDispositionHeader, @FormDataParam("file") final FormDataBodyPart formDataBodyPart) {
// -------------------------------------
// (1) Get the user from the API key
// -------------------------------------
User authUser;
try {
authUser = findUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, ResourceBundle.getBundle("Bundle").getString("file.addreplace.error.auth"));
}
if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
return error(Response.Status.METHOD_NOT_ALLOWED, SettingsServiceBean.Key.UploadMethods + " contains " + SystemConfig.FileUploadMethods.RSYNC + ". Please use rsync file upload.");
}
// -------------------------------------
// (2) Get the Dataset Id
//
// -------------------------------------
Dataset dataset;
Long datasetId;
try {
dataset = findDatasetOrDie(idSupplied);
} catch (WrappedResponse wr) {
return wr.getResponse();
}
// -------------------------------------
// (3) Get the file name and content type
// -------------------------------------
String newFilename = contentDispositionHeader.getFileName();
String newFileContentType = formDataBodyPart.getMediaType().toString();
// (2a) Load up optional params via JSON
// ---------------------------------------
OptionalFileParams optionalFileParams = null;
msgt("(api) jsonData: " + jsonData);
try {
optionalFileParams = new OptionalFileParams(jsonData);
} catch (DataFileTagException ex) {
return error(Response.Status.BAD_REQUEST, ex.getMessage());
}
// -------------------
// (3) Create the AddReplaceFileHelper object
// -------------------
msg("ADD!");
DataverseRequest dvRequest2 = createDataverseRequest(authUser);
AddReplaceFileHelper addFileHelper = new AddReplaceFileHelper(dvRequest2, ingestService, datasetService, fileService, permissionSvc, commandEngine, systemConfig);
// -------------------
// (4) Run "runAddFileByDatasetId"
// -------------------
addFileHelper.runAddFileByDataset(dataset, newFilename, newFileContentType, fileInputStream, optionalFileParams);
if (addFileHelper.hasError()) {
return error(addFileHelper.getHttpErrorCode(), addFileHelper.getErrorMessagesAsString("\n"));
} else {
String successMsg = ResourceBundle.getBundle("Bundle").getString("file.addreplace.success.add");
try {
// msgt("as String: " + addFileHelper.getSuccessResult());
/**
* @todo We need a consistent, sane way to communicate a human
* readable message to an API client suitable for human
* consumption. Imagine if the UI were built in Angular or React
* and we want to return a message from the API as-is to the
* user. Human readable.
*/
logger.fine("successMsg: " + successMsg);
return ok(addFileHelper.getSuccessResultAsJsonObjectBuilder());
// "Look at that! You added a file! (hey hey, it may have worked)");
} catch (NoFilesException ex) {
Logger.getLogger(Files.class.getName()).log(Level.SEVERE, null, ex);
return error(Response.Status.BAD_REQUEST, "NoFileException! Serious Error! See administrator!");
}
}
}
use of edu.harvard.iq.dataverse.Dataset in project dataverse by IQSS.
the class Datasets method deletePrivateUrl.
@DELETE
@Path("{id}/privateUrl")
public Response deletePrivateUrl(@PathParam("id") String idSupplied) {
return response(req -> {
Dataset dataset = findDatasetOrDie(idSupplied);
PrivateUrl privateUrl = execCommand(new GetPrivateUrlCommand(req, dataset));
if (privateUrl != null) {
execCommand(new DeletePrivateUrlCommand(req, dataset));
return ok("Private URL deleted.");
} else {
return notFound("No Private URL to delete.");
}
});
}
Aggregations