Search in sources :

Example 1 with DatasetLock

use of edu.harvard.iq.dataverse.DatasetLock 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);
    }
}
Also used : IRI(org.apache.abdera.i18n.iri.IRI) ResourcePart(org.swordapp.server.ResourcePart) SwordError(org.swordapp.server.SwordError) AtomStatement(org.swordapp.server.AtomStatement) HashMap(java.util.HashMap) Dataset(edu.harvard.iq.dataverse.Dataset) AtomStatement(org.swordapp.server.AtomStatement) Statement(org.swordapp.server.Statement) FileMetadata(edu.harvard.iq.dataverse.FileMetadata) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) Date(java.util.Date) AtomDate(org.apache.abdera.model.AtomDate) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) DataFile(edu.harvard.iq.dataverse.DataFile) AtomDate(org.apache.abdera.model.AtomDate) GetDraftDatasetVersionCommand(edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand) DatasetLock(edu.harvard.iq.dataverse.DatasetLock) IRISyntaxException(org.apache.abdera.i18n.iri.IRISyntaxException)

Example 2 with DatasetLock

use of edu.harvard.iq.dataverse.DatasetLock in project dataverse by IQSS.

the class SubmitDatasetForReviewCommand method execute.

@Override
public Dataset execute(CommandContext ctxt) throws CommandException {
    if (theDataset == null) {
        throw new IllegalCommandException(BundleUtil.getStringFromBundle("dataset.submit.failure.null"), this);
    }
    if (theDataset.getLatestVersion().isReleased()) {
        throw new IllegalCommandException(BundleUtil.getStringFromBundle("dataset.submit.failure.isReleased"), this);
    }
    if (theDataset.getLatestVersion().isInReview()) {
        throw new IllegalCommandException(BundleUtil.getStringFromBundle("dataset.submit.failure.inReview"), this);
    }
    // SEK 9-1 Add Lock before saving dataset
    DatasetLock inReviewLock = new DatasetLock(DatasetLock.Reason.InReview, getRequest().getAuthenticatedUser());
    ctxt.engine().submit(new AddLockCommand(getRequest(), theDataset, inReviewLock));
    Dataset updatedDataset = save(ctxt);
    return updatedDataset;
}
Also used : Dataset(edu.harvard.iq.dataverse.Dataset) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) DatasetLock(edu.harvard.iq.dataverse.DatasetLock)

Example 3 with DatasetLock

use of edu.harvard.iq.dataverse.DatasetLock in project dataverse by IQSS.

the class ReturnDatasetToAuthorCommand method save.

public Dataset save(CommandContext ctxt) throws CommandException {
    Timestamp updateTime = new Timestamp(new Date().getTime());
    theDataset.getEditVersion().setLastUpdateTime(updateTime);
    // We set "in review" to false because now the ball is back in the author's court.
    theDataset.setModificationTime(updateTime);
    // TODO: ctxt.datasets().removeDatasetLocks() doesn't work. Try RemoveLockCommand?
    AuthenticatedUser authenticatedUser = null;
    for (DatasetLock lock : theDataset.getLocks()) {
        if (DatasetLock.Reason.InReview.equals(lock.getReason())) {
            theDataset.removeLock(lock);
            // TODO: Are we supposed to remove the dataset lock from the user? What's going on here?
            authenticatedUser = lock.getUser();
        }
    }
    Dataset savedDataset = ctxt.em().merge(theDataset);
    ctxt.em().flush();
    DatasetVersionUser ddu = ctxt.datasets().getDatasetVersionUser(theDataset.getLatestVersion(), this.getUser());
    WorkflowComment workflowComment = new WorkflowComment(theDataset.getEditVersion(), WorkflowComment.Type.RETURN_TO_AUTHOR, comment, (AuthenticatedUser) this.getUser());
    ctxt.datasets().addWorkflowComment(workflowComment);
    if (ddu != null) {
        ddu.setLastUpdateDate(updateTime);
        ctxt.em().merge(ddu);
    } else {
        // TODO: This logic to update the DatasetVersionUser was copied from UpdateDatasetCommand and also appears in CreateDatasetCommand, PublishDatasetCommand UpdateDatasetCommand, and SubmitDatasetForReviewCommand. Consider consolidating.
        DatasetVersionUser datasetDataverseUser = new DatasetVersionUser();
        datasetDataverseUser.setDatasetVersion(savedDataset.getLatestVersion());
        datasetDataverseUser.setLastUpdateDate(updateTime);
        String id = getUser().getIdentifier();
        id = id.startsWith("@") ? id.substring(1) : id;
        AuthenticatedUser au = ctxt.authentication().getAuthenticatedUser(id);
        datasetDataverseUser.setAuthenticatedUser(au);
        ctxt.em().merge(datasetDataverseUser);
    }
    /*
            So what we're doing here is sending notifications to the authors who do not have publish permissions
            First get users who can publish - or in this case review
            Then get authors.
            Then remove reviewers from the autors list
            Finally send a notification to the remaining (non-reviewing) authors - Hey! your dataset was rejected.
        */
    List<AuthenticatedUser> reviewers = ctxt.permissions().getUsersWithPermissionOn(Permission.PublishDataset, savedDataset);
    List<AuthenticatedUser> authors = ctxt.permissions().getUsersWithPermissionOn(Permission.EditDataset, savedDataset);
    for (AuthenticatedUser au : reviewers) {
        authors.remove(au);
    }
    for (AuthenticatedUser au : authors) {
        ctxt.notifications().sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.RETURNEDDS, savedDataset.getLatestVersion().getId(), comment);
    }
    // TODO: What should we do with the indexing result? Print it to the log?
    boolean doNormalSolrDocCleanUp = true;
    Future<String> indexingResult = ctxt.index().indexDataset(savedDataset, doNormalSolrDocCleanUp);
    return savedDataset;
}
Also used : DatasetVersionUser(edu.harvard.iq.dataverse.DatasetVersionUser) Dataset(edu.harvard.iq.dataverse.Dataset) WorkflowComment(edu.harvard.iq.dataverse.workflows.WorkflowComment) DatasetLock(edu.harvard.iq.dataverse.DatasetLock) Timestamp(java.sql.Timestamp) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Date(java.util.Date)

Example 4 with DatasetLock

use of edu.harvard.iq.dataverse.DatasetLock in project dataverse by IQSS.

the class ReturnDatasetToAuthorCommandTest method testAllGood.

/*
    FIXME - Empty Comments won't be allowed in future
    @Test
    public void testEmptyComments(){
               
        dataset.setIdentifier("DUMMY");
        dataset.getLatestVersion().setVersionState(DatasetVersion.VersionState.DRAFT);
        dataset.getLatestVersion().setInReview(true);
        dataset.getLatestVersion().setReturnReason(null);
        String expected = "You must enter a reason for returning a dataset to the author(s).";
        String actual = null;
        Dataset updatedDataset = null;
        try {
            
             updatedDataset = testEngine.submit(new ReturnDatasetToAuthorCommand(dataverseRequest, dataset));
        } catch (CommandException ex) {
            actual = ex.getMessage();
        }
        assertEquals(expected, actual);      
        
        
    }
     */
@Test
public void testAllGood() {
    dataset.getLatestVersion().setVersionState(DatasetVersion.VersionState.DRAFT);
    Dataset updatedDataset = null;
    try {
        testEngine.submit(new AddLockCommand(dataverseRequest, dataset, new DatasetLock(DatasetLock.Reason.InReview, dataverseRequest.getAuthenticatedUser())));
        updatedDataset = testEngine.submit(new ReturnDatasetToAuthorCommand(dataverseRequest, dataset, "Update Your Files, Dummy"));
    } catch (CommandException ex) {
        System.out.println("Error updating dataset: " + ex.getMessage());
    }
    assertNotNull(updatedDataset);
}
Also used : Dataset(edu.harvard.iq.dataverse.Dataset) DatasetLock(edu.harvard.iq.dataverse.DatasetLock) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) Test(org.junit.Test)

Example 5 with DatasetLock

use of edu.harvard.iq.dataverse.DatasetLock in project dataverse by IQSS.

the class WorkflowServiceBean method lockDataset.

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
void lockDataset(WorkflowContext ctxt) throws CommandException {
    final DatasetLock datasetLock = new DatasetLock(DatasetLock.Reason.Workflow, ctxt.getRequest().getAuthenticatedUser());
    // engine.submit(new AddLockCommand(ctxt.getRequest(), ctxt.getDataset(), datasetLock));
    datasetLock.setDataset(ctxt.getDataset());
    em.persist(datasetLock);
    em.flush();
}
Also used : DatasetLock(edu.harvard.iq.dataverse.DatasetLock) TransactionAttribute(javax.ejb.TransactionAttribute)

Aggregations

DatasetLock (edu.harvard.iq.dataverse.DatasetLock)5 Dataset (edu.harvard.iq.dataverse.Dataset)4 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)2 Date (java.util.Date)2 DataFile (edu.harvard.iq.dataverse.DataFile)1 DatasetVersionUser (edu.harvard.iq.dataverse.DatasetVersionUser)1 Dataverse (edu.harvard.iq.dataverse.Dataverse)1 FileMetadata (edu.harvard.iq.dataverse.FileMetadata)1 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)1 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)1 IllegalCommandException (edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException)1 GetDraftDatasetVersionCommand (edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand)1 WorkflowComment (edu.harvard.iq.dataverse.workflows.WorkflowComment)1 Timestamp (java.sql.Timestamp)1 HashMap (java.util.HashMap)1 TransactionAttribute (javax.ejb.TransactionAttribute)1 IRI (org.apache.abdera.i18n.iri.IRI)1 IRISyntaxException (org.apache.abdera.i18n.iri.IRISyntaxException)1 AtomDate (org.apache.abdera.model.AtomDate)1 Test (org.junit.Test)1