use of edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse in project dataverse by IQSS.
the class DatasetPage method init.
private String init(boolean initFull) {
// System.out.println("_YE_OLDE_QUERY_COUNTER_"); // for debug purposes
this.maxFileUploadSizeInBytes = systemConfig.getMaxFileUploadSize();
setDataverseSiteUrl(systemConfig.getDataverseSiteUrl());
guestbookResponse = new GuestbookResponse();
String nonNullDefaultIfKeyNotFound = "";
protocol = settingsWrapper.getValueForKey(SettingsServiceBean.Key.Protocol, nonNullDefaultIfKeyNotFound);
authority = settingsWrapper.getValueForKey(SettingsServiceBean.Key.Authority, nonNullDefaultIfKeyNotFound);
separator = settingsWrapper.getValueForKey(SettingsServiceBean.Key.DoiSeparator, nonNullDefaultIfKeyNotFound);
if (dataset.getId() != null || versionId != null || persistentId != null) {
// view mode for a dataset
DatasetVersionServiceBean.RetrieveDatasetVersionResponse retrieveDatasetVersionResponse = null;
// ---------------------------------------
if (persistentId != null) {
logger.fine("initializing DatasetPage with persistent ID " + persistentId);
// Set Working Version and Dataset by PersistentID
dataset = datasetService.findByGlobalId(persistentId);
if (dataset == null) {
logger.warning("No such dataset: " + persistentId);
return permissionsWrapper.notFound();
}
logger.fine("retrieved dataset, id=" + dataset.getId());
retrieveDatasetVersionResponse = datasetVersionService.selectRequestedVersion(dataset.getVersions(), version);
// retrieveDatasetVersionResponse = datasetVersionService.retrieveDatasetVersionByPersistentId(persistentId, version);
this.workingVersion = retrieveDatasetVersionResponse.getDatasetVersion();
logger.fine("retrieved version: id: " + workingVersion.getId() + ", state: " + this.workingVersion.getVersionState());
} else if (dataset.getId() != null) {
// Set Working Version and Dataset by Datasaet Id and Version
dataset = datasetService.find(dataset.getId());
if (dataset == null) {
logger.warning("No such dataset: " + dataset);
return permissionsWrapper.notFound();
}
// retrieveDatasetVersionResponse = datasetVersionService.retrieveDatasetVersionById(dataset.getId(), version);
retrieveDatasetVersionResponse = datasetVersionService.selectRequestedVersion(dataset.getVersions(), version);
this.workingVersion = retrieveDatasetVersionResponse.getDatasetVersion();
logger.info("retreived version: id: " + workingVersion.getId() + ", state: " + this.workingVersion.getVersionState());
} else if (versionId != null) {
// TODO: 4.2.1 - this method is broken as of now!
// Set Working Version and Dataset by DatasaetVersion Id
// retrieveDatasetVersionResponse = datasetVersionService.retrieveDatasetVersionByVersionId(versionId);
}
if (retrieveDatasetVersionResponse == null) {
return permissionsWrapper.notFound();
}
//
if (workingVersion == null || this.dataset == null) {
return permissionsWrapper.notFound();
}
// Is the Dataset harvested?
if (dataset.isHarvested()) {
// if so, we'll simply forward to the remote URL for the original
// source of this harvested dataset:
String originalSourceURL = dataset.getRemoteArchiveURL();
if (originalSourceURL != null && !originalSourceURL.equals("")) {
logger.fine("redirecting to " + originalSourceURL);
try {
FacesContext.getCurrentInstance().getExternalContext().redirect(originalSourceURL);
} catch (IOException ioex) {
// must be a bad URL...
// we don't need to do anything special here - we'll redirect
// to the local 404 page, below.
logger.warning("failed to issue a redirect to " + originalSourceURL);
}
return originalSourceURL;
}
return permissionsWrapper.notFound();
}
// Check permisisons
if (!(workingVersion.isReleased() || workingVersion.isDeaccessioned()) && !this.canViewUnpublishedDataset()) {
return permissionsWrapper.notAuthorized();
}
if (!retrieveDatasetVersionResponse.wasRequestedVersionRetrieved()) {
// msg("checkit " + retrieveDatasetVersionResponse.getDifferentVersionMessage());
// JH.localize("dataset.message.metadataSuccess"));
JsfHelper.addWarningMessage(retrieveDatasetVersionResponse.getDifferentVersionMessage());
}
// init the citation
displayCitation = dataset.getCitation(true, workingVersion);
if (initFull) {
// init the list of FileMetadatas
if (workingVersion.isDraft() && canUpdateDataset()) {
readOnly = false;
} 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.getFileMetadatasSorted();
ownerId = dataset.getOwner().getId();
datasetNextMajorVersion = this.dataset.getNextMajorVersionString();
datasetNextMinorVersion = this.dataset.getNextMinorVersionString();
datasetVersionUI = datasetVersionUI.initDatasetVersionUI(workingVersion, false);
updateDatasetFieldInputLevels();
setExistReleasedVersion(resetExistRealeaseVersion());
// moving setVersionTabList to tab change event
// setVersionTabList(resetVersionTabList());
// setReleasedVersionTabList(resetReleasedVersionTabList());
// SEK - lazymodel may be needed for datascroller in future release
// lazyModel = new LazyFileMetadataDataModel(workingVersion.getId(), datafileService );
// populate MapLayerMetadata
// A DataFile may have a related MapLayerMetadata object
this.loadMapLayerMetadataLookup();
this.guestbookResponse = guestbookResponseService.initGuestbookResponseForFragment(dataset, null, session);
this.getFileDownloadHelper().setGuestbookResponse(guestbookResponse);
logger.fine("Checking if rsync support is enabled.");
if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsWrapper.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
try {
ScriptRequestResponse scriptRequestResponse = commandEngine.submit(new RequestRsyncScriptCommand(dvRequestService.getDataverseRequest(), dataset));
logger.fine("script: " + scriptRequestResponse.getScript());
if (scriptRequestResponse.getScript() != null && !scriptRequestResponse.getScript().isEmpty()) {
setHasRsyncScript(true);
setRsyncScript(scriptRequestResponse.getScript());
rsyncScriptFilename = "upload-" + workingVersion.getDataset().getIdentifier() + ".bash";
} else {
setHasRsyncScript(false);
}
} catch (RuntimeException ex) {
logger.warning("Problem getting rsync script: " + ex.getLocalizedMessage());
} catch (CommandException cex) {
logger.warning("Problem getting rsync script (Command Exception): " + cex.getLocalizedMessage());
}
}
}
} else if (ownerId != null) {
// create mode for a new child dataset
readOnly = false;
editMode = EditMode.CREATE;
dataset.setOwner(dataverseService.find(ownerId));
dataset.setProtocol(protocol);
dataset.setAuthority(authority);
dataset.setDoiSeparator(separator);
if (dataset.getOwner() == null) {
return permissionsWrapper.notFound();
} else if (!permissionService.on(dataset.getOwner()).has(Permission.AddDataset)) {
return permissionsWrapper.notAuthorized();
}
dataverseTemplates = dataverseService.find(ownerId).getTemplates();
if (!dataverseService.find(ownerId).isTemplateRoot()) {
dataverseTemplates.addAll(dataverseService.find(ownerId).getParentTemplates());
}
defaultTemplate = dataverseService.find(ownerId).getDefaultTemplate();
if (defaultTemplate != null) {
selectedTemplate = defaultTemplate;
for (Template testT : dataverseTemplates) {
if (defaultTemplate.getId().equals(testT.getId())) {
selectedTemplate = testT;
}
}
workingVersion = dataset.getEditVersion(selectedTemplate);
updateDatasetFieldInputLevels();
} else {
workingVersion = dataset.getCreateVersion();
updateDatasetFieldInputLevels();
}
if (settingsWrapper.isTrueForKey(SettingsServiceBean.Key.PublicInstall, false)) {
JH.addMessage(FacesMessage.SEVERITY_WARN, BundleUtil.getStringFromBundle("dataset.message.publicInstall"));
}
resetVersionUI();
// FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Add New Dataset", " - Enter metadata to create the dataset's citation. You can add more metadata about this dataset after it's created."));
} else {
return permissionsWrapper.notFound();
}
try {
privateUrl = commandEngine.submit(new GetPrivateUrlCommand(dvRequestService.getDataverseRequest(), dataset));
if (privateUrl != null) {
JH.addMessage(FacesMessage.SEVERITY_INFO, BundleUtil.getStringFromBundle("dataset.privateurl.infoMessageAuthor", Arrays.asList(getPrivateUrlLink(privateUrl))));
}
} catch (CommandException ex) {
// No big deal. The user simply doesn't have access to create or delete a Private URL.
}
if (session.getUser() instanceof PrivateUrlUser) {
PrivateUrlUser privateUrlUser = (PrivateUrlUser) session.getUser();
if (dataset != null && dataset.getId().equals(privateUrlUser.getDatasetId())) {
JH.addMessage(FacesMessage.SEVERITY_INFO, BundleUtil.getStringFromBundle("dataset.privateurl.infoMessageReviewer"));
}
}
// Various info messages, when the dataset is locked (for various reasons):
if (dataset.isLocked()) {
if (dataset.isLockedFor(DatasetLock.Reason.Workflow)) {
JH.addMessage(FacesMessage.SEVERITY_WARN, BundleUtil.getStringFromBundle("dataset.locked.message"), BundleUtil.getStringFromBundle("dataset.publish.workflow.inprogress"));
}
if (dataset.isLockedFor(DatasetLock.Reason.InReview)) {
JH.addMessage(FacesMessage.SEVERITY_WARN, BundleUtil.getStringFromBundle("dataset.locked.inReview.message"), BundleUtil.getStringFromBundle("dataset.inreview.infoMessage"));
}
if (dataset.isLockedFor(DatasetLock.Reason.DcmUpload)) {
JH.addMessage(FacesMessage.SEVERITY_WARN, BundleUtil.getStringFromBundle("file.rsyncUpload.inProgressMessage.summary"), BundleUtil.getStringFromBundle("file.rsyncUpload.inProgressMessage.details"));
}
}
configureTools = externalToolService.findByType(ExternalTool.Type.CONFIGURE);
exploreTools = externalToolService.findByType(ExternalTool.Type.EXPLORE);
return null;
}
use of edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse in project dataverse by IQSS.
the class RequestRsyncScriptCommandTest method testHappyPath.
@Test
public void testHappyPath() throws Exception {
dataset = new Dataset();
dataset.setIdentifier("42");
HttpServletRequest aHttpServletRequest = null;
DataverseRequest dataverseRequest = new DataverseRequest(MocksFactory.makeAuthenticatedUser("First", "Last"), aHttpServletRequest);
ScriptRequestResponse scriptRequestResponse = testEngine.submit(new RequestRsyncScriptCommand(dataverseRequest, dataset));
assertEquals("theScript", scriptRequestResponse.getScript());
}
use of edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse in project dataverse by IQSS.
the class RequestRsyncScriptCommand method execute.
@Override
public ScriptRequestResponse execute(CommandContext ctxt) throws CommandException {
if (request == null) {
throw new PermissionException("DataverseRequest cannot be null.", this, Collections.singleton(Permission.AddDataset), dataset);
}
String dcmBaseUrl = ctxt.settings().getValueForKey(DataCaptureModuleUrl);
if (dcmBaseUrl == null) {
throw new RuntimeException(DataCaptureModuleUrl + " is null!");
}
User user = request.getUser();
if (!(user instanceof AuthenticatedUser)) {
/**
* @todo get Permission.AddDataset from above somehow rather than
* duplicating it here.
*/
throw new PermissionException("This command can only be called by an AuthenticatedUser, not " + user, this, Collections.singleton(Permission.AddDataset), dataset);
}
// We need an AuthenticatedUser so we can pass its database id to the DCM.
AuthenticatedUser authenticatedUser = (AuthenticatedUser) user;
String errorPreamble = "User id " + authenticatedUser.getId() + " had a problem retrieving rsync script for dataset id " + dataset.getId() + " from Data Capture Module.";
String jsonString = DataCaptureModuleUtil.generateJsonForUploadRequest(authenticatedUser, dataset).toString();
UploadRequestResponse uploadRequestResponse = null;
try {
uploadRequestResponse = ctxt.dataCaptureModule().requestRsyncScriptCreation(jsonString, dcmBaseUrl + DataCaptureModuleServiceBean.uploadRequestPath);
} catch (DataCaptureModuleException ex) {
throw new RuntimeException("Problem making upload request to Data Capture Module: " + DataCaptureModuleUtil.getMessageFromException(ex));
}
int statusCode = uploadRequestResponse.getHttpStatusCode();
String response = uploadRequestResponse.getResponse();
if (statusCode != 200) {
throw new RuntimeException("When making the upload request, rather than 200 the status code was " + statusCode + ". The body was \'" + response + "\'. We cannot proceed. Returning.");
}
long millisecondsToSleep = DataCaptureModuleServiceBean.millisecondsToSleepBetweenUploadRequestAndScriptRequestCalls;
logger.fine("Message from Data Caputure Module upload request endpoint: " + response + ". Sleeping " + millisecondsToSleep + " milliseconds before making rsync script request.");
try {
Thread.sleep(millisecondsToSleep);
} catch (InterruptedException ex) {
throw new RuntimeException(errorPreamble + " Unable to wait " + millisecondsToSleep + " milliseconds: " + ex.getLocalizedMessage());
}
ScriptRequestResponse scriptRequestResponse = null;
try {
scriptRequestResponse = ctxt.dataCaptureModule().retreiveRequestedRsyncScript(dataset.getIdentifier(), dcmBaseUrl + DataCaptureModuleServiceBean.scriptRequestPath);
} catch (DataCaptureModuleException ex) {
throw new RuntimeException("Problem making script request to Data Capture Module: " + DataCaptureModuleUtil.getMessageFromException(ex));
}
String script = scriptRequestResponse.getScript();
if (script == null || script.isEmpty()) {
logger.warning("There was a problem getting the script. DCM returned status code: " + scriptRequestResponse.getHttpStatusCode());
}
logger.fine("script for dataset " + dataset.getId() + ": " + script);
return scriptRequestResponse;
}
use of edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse in project dataverse by IQSS.
the class Datasets method getRsync.
@GET
@Path("{identifier}/dataCaptureModule/rsync")
public Response getRsync(@PathParam("identifier") String id) {
// TODO - does it make sense to switch this to dataset identifier for consistency with the rest of the DCM APIs?
if (!DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
return error(Response.Status.METHOD_NOT_ALLOWED, SettingsServiceBean.Key.UploadMethods + " does not contain " + SystemConfig.FileUploadMethods.RSYNC + ".");
}
Dataset dataset = null;
try {
dataset = findDatasetOrDie(id);
ScriptRequestResponse scriptRequestResponse = execCommand(new RequestRsyncScriptCommand(createDataverseRequest(findUserOrDie()), dataset));
return ok(scriptRequestResponse.getScript(), MediaType.valueOf(MediaType.TEXT_PLAIN));
} catch (WrappedResponse wr) {
return wr.getResponse();
} catch (EJBException ex) {
return error(Response.Status.INTERNAL_SERVER_ERROR, "Something went wrong attempting to download rsync script: " + EjbUtil.ejbExceptionToString(ex));
}
}
use of edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse in project dataverse by IQSS.
the class RequestRsyncScriptCommandTest method setUp.
@Before
public void setUp() {
testEngine = new TestDataverseEngine(new TestCommandContext() {
@Override
public DataCaptureModuleServiceBean dataCaptureModule() {
return new DataCaptureModuleServiceBean() {
@Override
public UploadRequestResponse requestRsyncScriptCreation(String jsonString, String dcmBaseUrl) {
return new UploadRequestResponse(200, "myResponse");
}
@Override
public ScriptRequestResponse retreiveRequestedRsyncScript(String datasetIdentifier, String dcmBaseUrl) {
int httpStatusCode = 200;
long userId = 123l;
String script = "theScript";
ScriptRequestResponse scriptRequestResponse = new ScriptRequestResponse(httpStatusCode, datasetIdentifier, userId, script);
return scriptRequestResponse;
}
};
}
@Override
public SettingsServiceBean settings() {
return new MockSettingsSvc();
}
});
}
Aggregations