use of edu.harvard.iq.dataverse.engine.command.DataverseRequest in project dataverse by IQSS.
the class DataRetrieverAPI method retrieveMyDataAsJsonString.
/**
* @todo This should support the "X-Dataverse-key" header like the other
* APIs.
*/
@Path(retrieveDataPartialAPIPath)
@GET
@Produces({ "application/json" })
public String retrieveMyDataAsJsonString(@QueryParam("dvobject_types") List<String> dvobject_types, @QueryParam("published_states") List<String> published_states, @QueryParam("selected_page") Integer selectedPage, @QueryParam("mydata_search_term") String searchTerm, @QueryParam("role_ids") List<Long> roleIds, @QueryParam("userIdentifier") String userIdentifier, @QueryParam("key") String apiToken) {
// String myDataParams) {
// System.out.println("_YE_OLDE_QUERY_COUNTER_");
// msgt("_YE_OLDE_QUERY_COUNTER_"); // for debug purposes
boolean DEBUG_MODE = false;
boolean OTHER_USER = false;
// For, superusers, the searchUser may differ from the authUser
//
AuthenticatedUser searchUser = null;
if (DEBUG_MODE == true) {
// DEBUG: use userIdentifier
authUser = getUserFromIdentifier(userIdentifier);
if (authUser == null) {
return this.getJSONErrorString("Requires authentication", "retrieveMyDataAsJsonString. User not found! Shouldn't be using this anyway");
}
} else if ((session.getUser() != null) && (session.getUser().isAuthenticated())) {
authUser = (AuthenticatedUser) session.getUser();
// and use that instead
if ((authUser.isSuperuser()) && (userIdentifier != null) && (!userIdentifier.isEmpty())) {
searchUser = getUserFromIdentifier(userIdentifier);
if (searchUser != null) {
authUser = searchUser;
OTHER_USER = true;
} else {
return this.getJSONErrorString("No user found for: \"" + userIdentifier + "\"", null);
}
}
} else if (apiToken != null) {
// Is this being accessed by an API Token?
authUser = findUserByApiToken(apiToken);
if (authUser == null) {
return this.getJSONErrorString("Requires authentication. Please login.", "retrieveMyDataAsJsonString. User not found! Shouldn't be using this anyway");
} else {
// and use that instead
if ((authUser.isSuperuser()) && (userIdentifier != null) && (!userIdentifier.isEmpty())) {
searchUser = getUserFromIdentifier(userIdentifier);
if (searchUser != null) {
authUser = searchUser;
OTHER_USER = true;
} else {
return this.getJSONErrorString("No user found for: \"" + userIdentifier + "\"", null);
}
}
}
} else {
return this.getJSONErrorString("Requires authentication. Please login.", "retrieveMyDataAsJsonString. User not found! Shouldn't be using this anyway");
}
roleList = dataverseRoleService.findAll();
rolePermissionHelper = new DataverseRolePermissionHelper(roleList);
List<String> dtypes;
if (dvobject_types != null) {
dtypes = dvobject_types;
} else {
dtypes = MyDataFilterParams.defaultDvObjectTypes;
}
List<String> pub_states = null;
if (published_states != null) {
pub_states = published_states;
}
// ---------------------------------
// (1) Initialize filterParams and check for Errors
// ---------------------------------
DataverseRequest dataverseRequest = createDataverseRequest(authUser);
MyDataFilterParams filterParams = new MyDataFilterParams(dataverseRequest, dtypes, pub_states, roleIds, searchTerm);
if (filterParams.hasError()) {
return this.getJSONErrorString(filterParams.getErrorMessage(), filterParams.getErrorMessage());
}
// ---------------------------------
// (2) Initialize MyDataFinder and check for Errors
// ---------------------------------
myDataFinder = new MyDataFinder(rolePermissionHelper, roleAssigneeService, dvObjectServiceBean, groupService);
this.myDataFinder.runFindDataSteps(filterParams);
if (myDataFinder.hasError()) {
return this.getJSONErrorString(myDataFinder.getErrorMessage(), myDataFinder.getErrorMessage());
}
// ---------------------------------
// (3) Make Solr Query
// ---------------------------------
int paginationStart = 1;
if (selectedPage != null) {
paginationStart = selectedPage;
}
int solrCardStart = (paginationStart - 1) * SearchConstants.NUM_SOLR_DOCS_TO_RETRIEVE;
//
if (searchUser == null) {
searchUser = authUser;
}
// msg("search with user: " + searchUser.getIdentifier());
List<String> filterQueries = this.myDataFinder.getSolrFilterQueries();
if (filterQueries == null) {
logger.fine("No ids found for this search");
return this.getJSONErrorString(DataRetrieverAPI.MSG_NO_RESULTS_FOUND, null);
}
try {
solrQueryResponse = searchService.search(dataverseRequest, // subtree, default it to Dataverse for now
null, // "*", //
filterParams.getSearchTerm(), // filterQueries,
filterQueries, // SearchFields.NAME_SORT, SortBy.ASCENDING,
SearchFields.RELEASE_OR_CREATE_DATE, SortBy.DESCENDING, // paginationStart,
solrCardStart, // dataRelatedToMe
true, // 10 // SearchFields.NUM_SOLR_DOCS_TO_RETRIEVE
SearchConstants.NUM_SOLR_DOCS_TO_RETRIEVE);
// msgt("getSolrSearchResults: " + this.solrQueryResponse.getSolrSearchResults().toString());
if (this.solrQueryResponse.getNumResultsFound() == 0) {
return this.getJSONErrorString(DataRetrieverAPI.MSG_NO_RESULTS_FOUND, null);
}
} catch (SearchException ex) {
solrQueryResponse = null;
this.logger.severe("Solr SearchException: " + ex.getMessage());
}
if (solrQueryResponse == null) {
return this.getJSONErrorString("Sorry! There was an error with the search service.", "Sorry! There was a SOLR Error");
}
// ---------------------------------
// (4) Build JSON document including:
// - Pager
// - Formatted solr docs
// - Num results found
// - Search term
// - DvObject counts
// ---------------------------------
// Initialize JSON response
JsonObjectBuilder jsonData = Json.createObjectBuilder();
Pager pager = new Pager(solrQueryResponse.getNumResultsFound().intValue(), SearchConstants.NUM_SOLR_DOCS_TO_RETRIEVE, paginationStart);
RoleTagRetriever roleTagRetriever = new RoleTagRetriever(this.rolePermissionHelper, this.roleAssigneeSvc, this.dvObjectServiceBean);
roleTagRetriever.loadRoles(dataverseRequest, solrQueryResponse);
jsonData.add(DataRetrieverAPI.JSON_SUCCESS_FIELD_NAME, true).add(DataRetrieverAPI.JSON_DATA_FIELD_NAME, Json.createObjectBuilder().add("pagination", pager.asJsonObjectBuilderUsingCardTerms()).add(SearchConstants.SEARCH_API_ITEMS, this.formatSolrDocs(solrQueryResponse, roleTagRetriever)).add(SearchConstants.SEARCH_API_TOTAL_COUNT, solrQueryResponse.getNumResultsFound()).add(SearchConstants.SEARCH_API_START, solrQueryResponse.getResultsStart()).add("search_term", filterParams.getSearchTerm()).add("dvobject_counts", this.getDvObjectTypeCounts(solrQueryResponse)).add("pubstatus_counts", this.getPublicationStatusCounts(solrQueryResponse)).add("selected_filters", this.myDataFinder.getSelectedFilterParamsAsJSON()));
if (OTHER_USER == true) {
jsonData.add("other_user", searchUser.getIdentifier());
}
return jsonData.build().toString();
}
use of edu.harvard.iq.dataverse.engine.command.DataverseRequest in project dataverse by IQSS.
the class Dataverses method createAssignment.
/**
* This code for setting a dataverse logo via API was started when initially
* investigating https://github.com/IQSS/dataverse/issues/3559 but it isn't
* finished so it's commented out. See also * "No functionality should be
* GUI-only. Make all functionality reachable via the API" at
* https://github.com/IQSS/dataverse/issues/3440
*/
// File tempDir;
//
// private void createTempDir(Dataverse editDv) {
// try {
// File tempRoot = java.nio.file.Files.createDirectories(Paths.get("../docroot/logos/temp")).toFile();
// tempDir = java.nio.file.Files.createTempDirectory(tempRoot.toPath(), editDv.getId().toString()).toFile();
// } catch (IOException e) {
// throw new RuntimeException("Error creating temp directory", e); // improve error handling
// }
// }
//
// private DataverseTheme initDataverseTheme(Dataverse editDv) {
// DataverseTheme dvt = new DataverseTheme();
// dvt.setLinkColor(DEFAULT_LINK_COLOR);
// dvt.setLogoBackgroundColor(DEFAULT_LOGO_BACKGROUND_COLOR);
// dvt.setBackgroundColor(DEFAULT_BACKGROUND_COLOR);
// dvt.setTextColor(DEFAULT_TEXT_COLOR);
// dvt.setDataverse(editDv);
// return dvt;
// }
//
// @PUT
// @Path("{identifier}/logo")
// @Consumes(MediaType.MULTIPART_FORM_DATA)
// public Response setDataverseLogo(@PathParam("identifier") String dvIdtf,
// @FormDataParam("file") InputStream fileInputStream,
// @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
// @QueryParam("key") String apiKey) {
// boolean disabled = true;
// if (disabled) {
// return error(Status.FORBIDDEN, "Setting the dataverse logo via API needs more work.");
// }
// try {
// final DataverseRequest req = createDataverseRequest(findUserOrDie());
// final Dataverse editDv = findDataverseOrDie(dvIdtf);
//
// logger.finer("entering fileUpload");
// if (tempDir == null) {
// createTempDir(editDv);
// logger.finer("created tempDir");
// }
// File uploadedFile;
// try {
// String fileName = contentDispositionHeader.getFileName();
//
// uploadedFile = new File(tempDir, fileName);
// if (!uploadedFile.exists()) {
// uploadedFile.createNewFile();
// }
// logger.finer("created file");
// File file = null;
// file = FileUtil.inputStreamToFile(fileInputStream);
// if (file.length() > systemConfig.getUploadLogoSizeLimit()) {
// return error(Response.Status.BAD_REQUEST, "File is larger than maximum size: " + systemConfig.getUploadLogoSizeLimit() + ".");
// }
// java.nio.file.Files.copy(fileInputStream, uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
// logger.finer("copied inputstream to file");
// editDv.setDataverseTheme(initDataverseTheme(editDv));
// editDv.getDataverseTheme().setLogo(fileName);
//
// } catch (IOException e) {
// logger.finer("caught IOException");
// logger.throwing("ThemeWidgetFragment", "handleImageFileUpload", e);
// throw new RuntimeException("Error uploading logo file", e); // improve error handling
// }
// // If needed, set the default values for the logo
// if (editDv.getDataverseTheme().getLogoFormat() == null) {
// editDv.getDataverseTheme().setLogoFormat(DataverseTheme.ImageFormat.SQUARE);
// }
// logger.finer("end handelImageFileUpload");
// UpdateDataverseThemeCommand cmd = new UpdateDataverseThemeCommand(editDv, uploadedFile, req);
// Dataverse saved = execCommand(cmd);
//
// /**
// * @todo delete the temp file:
// * docroot/logos/temp/1148114212463761832421/cc0.png
// */
// return ok("logo uploaded: " + saved.getDataverseTheme().getLogo());
// } catch (WrappedResponse ex) {
// return error(Status.BAD_REQUEST, "problem uploading logo: " + ex);
// }
// }
@POST
@Path("{identifier}/assignments")
public Response createAssignment(RoleAssignmentDTO ra, @PathParam("identifier") String dvIdtf, @QueryParam("key") String apiKey) {
try {
final DataverseRequest req = createDataverseRequest(findUserOrDie());
final Dataverse dataverse = findDataverseOrDie(dvIdtf);
RoleAssignee assignee = findAssignee(ra.getAssignee());
if (assignee == null) {
return error(Status.BAD_REQUEST, "Assignee not found");
}
DataverseRole theRole;
Dataverse dv = dataverse;
theRole = null;
while ((theRole == null) && (dv != null)) {
for (DataverseRole aRole : rolesSvc.availableRoles(dv.getId())) {
if (aRole.getAlias().equals(ra.getRole())) {
theRole = aRole;
break;
}
}
dv = dv.getOwner();
}
if (theRole == null) {
return error(Status.BAD_REQUEST, "Can't find role named '" + ra.getRole() + "' in dataverse " + dataverse);
}
String privateUrlToken = null;
return ok(json(execCommand(new AssignRoleCommand(assignee, theRole, dataverse, req, privateUrlToken))));
} catch (WrappedResponse ex) {
LOGGER.log(Level.WARNING, "Can''t create assignment: {0}", ex.getMessage());
return ex.getResponse();
}
}
use of edu.harvard.iq.dataverse.engine.command.DataverseRequest in project dataverse by IQSS.
the class HarvestingClients method createHarvestingClient.
@POST
@Path("{nickName}")
public Response createHarvestingClient(String jsonBody, @PathParam("nickName") String nickName, @QueryParam("key") String apiKey) throws IOException, JsonParseException {
try (StringReader rdr = new StringReader(jsonBody)) {
JsonObject json = Json.createReader(rdr).readObject();
HarvestingClient harvestingClient = new HarvestingClient();
// TODO: check that it doesn't exist yet...
harvestingClient.setName(nickName);
String dataverseAlias = jsonParser().parseHarvestingClient(json, harvestingClient);
Dataverse ownerDataverse = dataverseService.findByAlias(dataverseAlias);
if (ownerDataverse == null) {
return error(Response.Status.BAD_REQUEST, "No such dataverse: " + dataverseAlias);
}
harvestingClient.setDataverse(ownerDataverse);
if (ownerDataverse.getHarvestingClientConfigs() == null) {
ownerDataverse.setHarvestingClientConfigs(new ArrayList<>());
}
ownerDataverse.getHarvestingClientConfigs().add(harvestingClient);
DataverseRequest req = createDataverseRequest(findUserOrDie());
HarvestingClient managedHarvestingClient = execCommand(new CreateHarvestingClientCommand(req, harvestingClient));
return created("/harvest/clients/" + nickName, harvestingConfigAsJson(managedHarvestingClient));
} catch (JsonParseException ex) {
return error(Response.Status.BAD_REQUEST, "Error parsing harvesting client: " + ex.getMessage());
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
use of edu.harvard.iq.dataverse.engine.command.DataverseRequest 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.engine.command.DataverseRequest in project dataverse by IQSS.
the class Files method replaceFileInDataset.
/**
* Replace an Existing File
*
* @param datasetId
* @param testFileInputStream
* @param contentDispositionHeader
* @param formDataBodyPart
* @return
*/
@POST
@Path("{id}/replace")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response replaceFileInDataset(@PathParam("id") Long fileToReplaceId, @FormDataParam("jsonData") String jsonData, @FormDataParam("file") InputStream testFileInputStream, @FormDataParam("file") FormDataContentDisposition contentDispositionHeader, @FormDataParam("file") final FormDataBodyPart formDataBodyPart) {
// -------------------------------------
// (1) Get the user from the API key
// -------------------------------------
User authUser;
try {
authUser = this.findUserOrDie();
} catch (AbstractApiBean.WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, ResourceBundle.getBundle("Bundle").getString("file.addreplace.error.auth"));
}
// -------------------------------------
// (2) Check/Parse the JSON (if uploaded)
// -------------------------------------
Boolean forceReplace = false;
OptionalFileParams optionalFileParams = null;
if (jsonData != null) {
JsonObject jsonObj = null;
try {
jsonObj = new Gson().fromJson(jsonData, JsonObject.class);
// -------------------------------------
if ((jsonObj.has("forceReplace")) && (!jsonObj.get("forceReplace").isJsonNull())) {
forceReplace = jsonObj.get("forceReplace").getAsBoolean();
if (forceReplace == null) {
forceReplace = false;
}
}
try {
// (2b) Load up optional params via JSON
// - Will skip extra attributes which includes fileToReplaceId and forceReplace
// ---------------------------------------
optionalFileParams = new OptionalFileParams(jsonData);
} catch (DataFileTagException ex) {
return error(Response.Status.BAD_REQUEST, ex.getMessage());
}
} catch (ClassCastException ex) {
logger.info("Exception parsing string '" + jsonData + "': " + ex);
}
}
// -------------------------------------
// (3) Get the file name and content type
// -------------------------------------
String newFilename = contentDispositionHeader.getFileName();
String newFileContentType = formDataBodyPart.getMediaType().toString();
// -------------------
// (4) Create the AddReplaceFileHelper object
// -------------------
msg("REPLACE!");
DataverseRequest dvRequest2 = createDataverseRequest(authUser);
AddReplaceFileHelper addFileHelper = new AddReplaceFileHelper(dvRequest2, this.ingestService, this.datasetService, this.fileService, this.permissionSvc, this.commandEngine, this.systemConfig);
if (forceReplace) {
addFileHelper.runForceReplaceFile(fileToReplaceId, newFilename, newFileContentType, testFileInputStream, optionalFileParams);
} else {
addFileHelper.runReplaceFile(fileToReplaceId, newFilename, newFileContentType, testFileInputStream, optionalFileParams);
}
msg("we're back.....");
if (addFileHelper.hasError()) {
msg("yes, has error");
return error(addFileHelper.getHttpErrorCode(), addFileHelper.getErrorMessagesAsString("\n"));
} else {
msg("no error");
String successMsg = ResourceBundle.getBundle("Bundle").getString("file.addreplace.success.replace");
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());
// return okResponseGsonObject(successMsg,
// addFileHelper.getSuccessResultAsGsonObject());
// "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!");
}
}
}
Aggregations