Search in sources :

Example 26 with CommandException

use of edu.harvard.iq.dataverse.engine.command.exception.CommandException in project dataverse by IQSS.

the class EjbDataverseEngine method submit.

public <R> R submit(Command<R> aCommand) throws CommandException {
    final ActionLogRecord logRec = new ActionLogRecord(ActionLogRecord.ActionType.Command, aCommand.getClass().getCanonicalName());
    try {
        logRec.setUserIdentifier(aCommand.getRequest().getUser().getIdentifier());
        // Check permissions - or throw an exception
        Map<String, ? extends Set<Permission>> requiredMap = aCommand.getRequiredPermissions();
        if (requiredMap == null) {
            throw new RuntimeException("Command " + aCommand + " does not define required permissions.");
        }
        DataverseRequest dvReq = aCommand.getRequest();
        Map<String, DvObject> affectedDvObjects = aCommand.getAffectedDvObjects();
        logRec.setInfo(aCommand.describe());
        for (Map.Entry<String, ? extends Set<Permission>> pair : requiredMap.entrySet()) {
            String dvName = pair.getKey();
            if (!affectedDvObjects.containsKey(dvName)) {
                throw new RuntimeException("Command instance " + aCommand + " does not have a DvObject named '" + dvName + "'");
            }
            DvObject dvo = affectedDvObjects.get(dvName);
            Set<Permission> granted = (dvo != null) ? permissionService.permissionsFor(dvReq, dvo) : EnumSet.allOf(Permission.class);
            Set<Permission> required = requiredMap.get(dvName);
            if (!granted.containsAll(required)) {
                required.removeAll(granted);
                logRec.setActionResult(ActionLogRecord.Result.PermissionError);
                /**
                 * @todo Is there any harm in showing the "granted" set
                 * since we already show "required"? It would help people
                 * reason about the mismatch.
                 */
                throw new PermissionException("Can't execute command " + aCommand + ", because request " + aCommand.getRequest() + " is missing permissions " + required + " on Object " + dvo.accept(DvObject.NamePrinter), aCommand, required, dvo);
            }
        }
        try {
            return aCommand.execute(getContext());
        } catch (EJBException ejbe) {
            logRec.setActionResult(ActionLogRecord.Result.InternalError);
            throw new CommandException("Command " + aCommand.toString() + " failed: " + ejbe.getMessage(), ejbe.getCausedByException(), aCommand);
        }
    } catch (RuntimeException re) {
        logRec.setActionResult(ActionLogRecord.Result.InternalError);
        logRec.setInfo(re.getMessage());
        Throwable cause = re;
        while (cause != null) {
            if (cause instanceof ConstraintViolationException) {
                StringBuilder sb = new StringBuilder();
                sb.append("Unexpected bean validation constraint exception:");
                ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
                for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) {
                    sb.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
                }
                logger.log(Level.SEVERE, sb.toString());
                // set this more detailed info in action log
                logRec.setInfo(sb.toString());
            }
            cause = cause.getCause();
        }
        throw re;
    } finally {
        if (logRec.getActionResult() == null) {
            logRec.setActionResult(ActionLogRecord.Result.OK);
        }
        logRec.setEndTime(new java.util.Date());
        logSvc.log(logRec);
    }
}
Also used : PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) ActionLogRecord(edu.harvard.iq.dataverse.actionlogging.ActionLogRecord) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) ConstraintViolation(javax.validation.ConstraintViolation) Permission(edu.harvard.iq.dataverse.authorization.Permission) ConstraintViolationException(javax.validation.ConstraintViolationException) EJBException(javax.ejb.EJBException) Map(java.util.Map)

Example 27 with CommandException

use of edu.harvard.iq.dataverse.engine.command.exception.CommandException in project dataverse by IQSS.

the class DataversePage method saveSavedSearch.

public String saveSavedSearch() {
    if (linkingDataverseId == null) {
        JsfHelper.addErrorMessage("You must select a linking dataverse.");
        return "";
    }
    linkingDataverse = dataverseService.find(linkingDataverseId);
    AuthenticatedUser savedSearchCreator = getAuthenticatedUser();
    if (savedSearchCreator == null) {
        String msg = "Only authenticated users can save a search.";
        logger.severe(msg);
        JsfHelper.addErrorMessage(msg);
        return returnRedirect();
    }
    SavedSearch savedSearch = new SavedSearch(searchIncludeFragment.getQuery(), linkingDataverse, savedSearchCreator);
    savedSearch.setSavedSearchFilterQueries(new ArrayList<>());
    for (String filterQuery : searchIncludeFragment.getFilterQueriesDebug()) {
        /**
         * @todo Why are there null's here anyway? Turn on debug and figure
         * this out.
         */
        if (filterQuery != null && !filterQuery.isEmpty()) {
            SavedSearchFilterQuery ssfq = new SavedSearchFilterQuery(filterQuery, savedSearch);
            savedSearch.getSavedSearchFilterQueries().add(ssfq);
        }
    }
    CreateSavedSearchCommand cmd = new CreateSavedSearchCommand(dvRequestService.getDataverseRequest(), linkingDataverse, savedSearch);
    try {
        commandEngine.submit(cmd);
        List<String> arguments = new ArrayList<>();
        String linkString = "<a href=\"/dataverse/" + linkingDataverse.getAlias() + "\">" + StringEscapeUtils.escapeHtml(linkingDataverse.getDisplayName()) + "</a>";
        arguments.add(linkString);
        String successMessageString = BundleUtil.getStringFromBundle("dataverse.saved.search.success", arguments);
        JsfHelper.addSuccessMessage(successMessageString);
        return returnRedirect();
    } catch (CommandException ex) {
        String msg = "There was a problem linking this search to yours: " + ex;
        logger.severe(msg);
        JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("dataverse.saved.search.failure") + " " + ex);
        return returnRedirect();
    }
}
Also used : CreateSavedSearchCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateSavedSearchCommand) SavedSearch(edu.harvard.iq.dataverse.search.savedsearch.SavedSearch) SavedSearchFilterQuery(edu.harvard.iq.dataverse.search.savedsearch.SavedSearchFilterQuery) ArrayList(java.util.ArrayList) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 28 with CommandException

use of edu.harvard.iq.dataverse.engine.command.exception.CommandException in project dataverse by IQSS.

the class DataversePage method saveLinkedDataverse.

public String saveLinkedDataverse() {
    if (linkingDataverseId == null) {
        JsfHelper.addSuccessMessage("You must select a linking dataverse.");
        return "";
    }
    AuthenticatedUser savedSearchCreator = getAuthenticatedUser();
    if (savedSearchCreator == null) {
        String msg = "Only authenticated users can link a dataverse.";
        logger.severe(msg);
        JsfHelper.addErrorMessage(msg);
        return returnRedirect();
    }
    linkingDataverse = dataverseService.find(linkingDataverseId);
    LinkDataverseCommand cmd = new LinkDataverseCommand(dvRequestService.getDataverseRequest(), linkingDataverse, dataverse);
    // LinkDvObjectCommand cmd = new LinkDvObjectCommand (session.getUser(), linkingDataverse, dataverse);
    try {
        commandEngine.submit(cmd);
    } catch (CommandException ex) {
        String msg = "Unable to link " + dataverse.getDisplayName() + " to " + linkingDataverse.getDisplayName() + ". An internal error occurred.";
        logger.log(Level.SEVERE, "{0} {1}", new Object[] { msg, ex });
        JsfHelper.addErrorMessage(msg);
        return returnRedirect();
    }
    SavedSearch savedSearchOfChildren = createSavedSearchForChildren(savedSearchCreator);
    boolean createLinksAndIndexRightNow = false;
    if (createLinksAndIndexRightNow) {
        try {
            // create links (does indexing) right now (might be expensive)
            boolean debug = false;
            DataverseRequest dataverseRequest = new DataverseRequest(savedSearchCreator, SavedSearchServiceBean.getHttpServletRequest());
            savedSearchService.makeLinksForSingleSavedSearch(dataverseRequest, savedSearchOfChildren, debug);
            JsfHelper.addSuccessMessage(BundleUtil.getStringFromBundle("dataverse.linked.success", getSuccessMessageArguments()));
            return returnRedirect();
        } catch (SearchException | CommandException ex) {
            // error: solr is down, etc. can't link children right now
            JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("dataverse.linked.internalerror", getSuccessMessageArguments()));
            String msg = dataverse.getDisplayName() + " has been successfully linked to " + linkingDataverse.getDisplayName() + " but contents will not appear until an internal error has been fixed.";
            logger.log(Level.SEVERE, "{0} {1}", new Object[] { msg, ex });
            // JsfHelper.addErrorMessage(msg);
            return returnRedirect();
        }
    } else {
        // defer: please wait for the next timer/cron job
        // JsfHelper.addSuccessMessage(dataverse.getDisplayName() + " has been successfully linked to " + linkingDataverse.getDisplayName() + ". Please wait for its contents to appear.");
        JsfHelper.addSuccessMessage(BundleUtil.getStringFromBundle("dataverse.linked.success.wait", getSuccessMessageArguments()));
        return returnRedirect();
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) SavedSearch(edu.harvard.iq.dataverse.search.savedsearch.SavedSearch) SearchException(edu.harvard.iq.dataverse.search.SearchException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) LinkDataverseCommand(edu.harvard.iq.dataverse.engine.command.impl.LinkDataverseCommand)

Example 29 with CommandException

use of edu.harvard.iq.dataverse.engine.command.exception.CommandException in project dataverse by IQSS.

the class ManageGuestbooksPage method saveDataverse.

private void saveDataverse(String successMessage, String failureMessage) {
    if (successMessage.isEmpty()) {
        successMessage = "dataset.manageGuestbooks.message.editSuccess";
    }
    if (failureMessage.isEmpty()) {
        failureMessage = "dataset.manageGuestbooks.message.editFailure";
    }
    try {
        engineService.submit(new UpdateDataverseCommand(getDataverse(), null, null, dvRequestService.getDataverseRequest(), null));
        JsfHelper.addSuccessMessage(JH.localize(successMessage));
    } catch (CommandException ex) {
        JH.addMessage(FacesMessage.SEVERITY_FATAL, JH.localize(failureMessage));
    }
}
Also used : UpdateDataverseCommand(edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseCommand) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException)

Example 30 with CommandException

use of edu.harvard.iq.dataverse.engine.command.exception.CommandException in project dataverse by IQSS.

the class ManagePermissionsPage method assignRole.

private void assignRole(RoleAssignee ra, DataverseRole r) {
    try {
        String privateUrlToken = null;
        commandEngine.submit(new AssignRoleCommand(ra, r, dvObject, dvRequestService.getDataverseRequest(), privateUrlToken));
        JsfHelper.addSuccessMessage(r.getName() + " role assigned to " + ra.getDisplayInfo().getTitle() + " for " + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()) + ".");
        // don't notify if role = file downloader and object is not released
        if (!(r.getAlias().equals(DataverseRole.FILE_DOWNLOADER) && !dvObject.isReleased())) {
            notifyRoleChange(ra, UserNotification.Type.ASSIGNROLE);
        }
    } catch (PermissionException ex) {
        JH.addMessage(FacesMessage.SEVERITY_ERROR, "The role was not able to be assigned.", "Permissions " + ex.getRequiredPermissions().toString() + " missing.");
    } catch (CommandException ex) {
        String message = r.getName() + " role could NOT be assigned to " + ra.getDisplayInfo().getTitle() + " for " + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()) + ".";
        JsfHelper.addErrorMessage(message);
        // JH.addMessage(FacesMessage.SEVERITY_FATAL, "The role was not able to be assigned.");
        logger.log(Level.SEVERE, "Error assiging role: " + ex.getMessage(), ex);
    }
    showAssignmentMessages();
}
Also used : PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AssignRoleCommand(edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand)

Aggregations

CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)86 Dataset (edu.harvard.iq.dataverse.Dataset)21 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)20 IllegalCommandException (edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException)19 Test (org.junit.Test)16 PermissionException (edu.harvard.iq.dataverse.engine.command.exception.PermissionException)15 EJBException (javax.ejb.EJBException)13 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)12 DataFile (edu.harvard.iq.dataverse.DataFile)11 Dataverse (edu.harvard.iq.dataverse.Dataverse)9 UpdateDatasetCommand (edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand)9 ConstraintViolation (javax.validation.ConstraintViolation)9 DatasetThumbnail (edu.harvard.iq.dataverse.dataset.DatasetThumbnail)8 IOException (java.io.IOException)8 Timestamp (java.sql.Timestamp)8 ArrayList (java.util.ArrayList)8 Date (java.util.Date)8 FacesMessage (javax.faces.application.FacesMessage)7 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)6 SwordError (org.swordapp.server.SwordError)6