Search in sources :

Example 1 with ScriptRequestResponse

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;
}
Also used : ScriptRequestResponse(edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse) PrivateUrlUser(edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser) GetPrivateUrlCommand(edu.harvard.iq.dataverse.engine.command.impl.GetPrivateUrlCommand) IOException(java.io.IOException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) RequestRsyncScriptCommand(edu.harvard.iq.dataverse.engine.command.impl.RequestRsyncScriptCommand)

Example 2 with ScriptRequestResponse

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());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) ScriptRequestResponse(edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse) Dataset(edu.harvard.iq.dataverse.Dataset) Test(org.junit.Test)

Example 3 with ScriptRequestResponse

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;
}
Also used : PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) ScriptRequestResponse(edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) UploadRequestResponse(edu.harvard.iq.dataverse.datacapturemodule.UploadRequestResponse) DataCaptureModuleException(edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 4 with 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));
    }
}
Also used : ScriptRequestResponse(edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse) Dataset(edu.harvard.iq.dataverse.Dataset) EJBException(javax.ejb.EJBException) RequestRsyncScriptCommand(edu.harvard.iq.dataverse.engine.command.impl.RequestRsyncScriptCommand) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 5 with ScriptRequestResponse

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();
        }
    });
}
Also used : ScriptRequestResponse(edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse) TestCommandContext(edu.harvard.iq.dataverse.engine.TestCommandContext) UploadRequestResponse(edu.harvard.iq.dataverse.datacapturemodule.UploadRequestResponse) DataCaptureModuleServiceBean(edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleServiceBean) TestDataverseEngine(edu.harvard.iq.dataverse.engine.TestDataverseEngine) Before(org.junit.Before)

Aggregations

ScriptRequestResponse (edu.harvard.iq.dataverse.datacapturemodule.ScriptRequestResponse)6 Dataset (edu.harvard.iq.dataverse.Dataset)2 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)2 UploadRequestResponse (edu.harvard.iq.dataverse.datacapturemodule.UploadRequestResponse)2 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)2 IllegalCommandException (edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException)2 RequestRsyncScriptCommand (edu.harvard.iq.dataverse.engine.command.impl.RequestRsyncScriptCommand)2 IOException (java.io.IOException)2 PrivateUrlUser (edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser)1 User (edu.harvard.iq.dataverse.authorization.users.User)1 DataCaptureModuleException (edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleException)1 DataCaptureModuleServiceBean (edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleServiceBean)1 TestCommandContext (edu.harvard.iq.dataverse.engine.TestCommandContext)1 TestDataverseEngine (edu.harvard.iq.dataverse.engine.TestDataverseEngine)1 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)1 PermissionException (edu.harvard.iq.dataverse.engine.command.exception.PermissionException)1 GetPrivateUrlCommand (edu.harvard.iq.dataverse.engine.command.impl.GetPrivateUrlCommand)1 Timestamp (java.sql.Timestamp)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1