Search in sources :

Example 26 with DataverseRequest

use of edu.harvard.iq.dataverse.engine.command.DataverseRequest 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 DataverseRequest

use of edu.harvard.iq.dataverse.engine.command.DataverseRequest 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 28 with DataverseRequest

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

the class SavedSearchServiceBean method findHits.

private SolrQueryResponse findHits(SavedSearch savedSearch) throws SearchException {
    String sortField = SearchFields.RELEVANCE;
    String sortOrder = SortBy.DESCENDING;
    SortBy sortBy = new SortBy(sortField, sortOrder);
    int paginationStart = 0;
    boolean dataRelatedToMe = false;
    int numResultsPerPage = Integer.MAX_VALUE;
    SolrQueryResponse solrQueryResponse = searchService.search(new DataverseRequest(savedSearch.getCreator(), getHttpServletRequest()), savedSearch.getDefinitionPoint(), savedSearch.getQuery(), savedSearch.getFilterQueriesAsStrings(), sortBy.getField(), sortBy.getOrder(), paginationStart, dataRelatedToMe, numResultsPerPage);
    return solrQueryResponse;
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) SolrQueryResponse(edu.harvard.iq.dataverse.search.SolrQueryResponse) SortBy(edu.harvard.iq.dataverse.search.SortBy)

Example 29 with DataverseRequest

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

the class SavedSearchServiceBean method makeLinksForAllSavedSearches.

public JsonObjectBuilder makeLinksForAllSavedSearches(boolean debugFlag) throws SearchException, CommandException {
    JsonObjectBuilder response = Json.createObjectBuilder();
    List<SavedSearch> allSavedSearches = findAll();
    JsonArrayBuilder savedSearchArrayBuilder = Json.createArrayBuilder();
    for (SavedSearch savedSearch : allSavedSearches) {
        DataverseRequest dataverseRequest = new DataverseRequest(savedSearch.getCreator(), getHttpServletRequest());
        JsonObjectBuilder perSavedSearchResponse = makeLinksForSingleSavedSearch(dataverseRequest, savedSearch, debugFlag);
        savedSearchArrayBuilder.add(perSavedSearchResponse);
    }
    response.add("hits by saved search", savedSearchArrayBuilder);
    return response;
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder)

Example 30 with DataverseRequest

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

the class DataverseTimerServiceBean method handleTimeout.

/**
 * This method is called whenever an EJB Timer goes off.
 * Check to see if this is a Harvest Timer, and if it is
 * Run the harvest for the given (scheduled) dataverse
 * @param timer
 */
@Timeout
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void handleTimeout(javax.ejb.Timer timer) {
    if (!systemConfig.isTimerServer()) {
        // logger.info("I am not the timer server! - bailing out of handleTimeout()");
        Logger.getLogger(DataverseTimerServiceBean.class.getName()).log(Level.WARNING, null, "I am not the timer server! - but handleTimeout() got called. Please investigate!");
    }
    try {
        logger.log(Level.INFO, "Handling timeout on " + InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException ex) {
        Logger.getLogger(DataverseTimerServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (timer.getInfo() instanceof MotherTimerInfo) {
        logger.info("Behold! I am the Master Timer, king of all timers! I'm here to create all the lesser timers!");
        removeHarvestTimers();
        for (HarvestingClient client : harvestingClientService.getAllHarvestingClients()) {
            createHarvestTimer(client);
        }
    } else if (timer.getInfo() instanceof HarvestTimerInfo) {
        HarvestTimerInfo info = (HarvestTimerInfo) timer.getInfo();
        try {
            logger.log(Level.INFO, "running a harvesting client: id=" + info.getHarvestingClientId());
            // Timer batch jobs are run by the main Admin user.
            // TODO: revisit how we retrieve the superuser here.
            // Should it be configurable somewhere, which superuser
            // runs these jobs? Should there be a central mechanism for obtaining
            // the "major", builtin superuser for this Dataverse instance?
            // -- L.A. 4.5, Aug. 2016
            // getAuthenticatedUser("admin");
            AuthenticatedUser adminUser = authSvc.getAdminUser();
            if (adminUser == null) {
                logger.info("Scheduled harvest: failed to locate the admin user! Exiting.");
                throw new IOException("Scheduled harvest: failed to locate the admin user");
            }
            logger.info("found admin user " + adminUser.getName());
            DataverseRequest dataverseRequest = new DataverseRequest(adminUser, (HttpServletRequest) null);
            harvesterService.doHarvest(dataverseRequest, info.getHarvestingClientId());
        } catch (Throwable e) {
            // Harvester Service should be handling any error notifications,
            // if/when things go wrong.
            // (TODO: -- verify this logic; harvesterService may still be able
            // to throw an IOException, if it could not run the harvest at all,
            // or could not for whatever reason modify the database record...
            // in this case we should, probably, log the error and try to send
            // a mail notification. -- L.A. 4.4)
            // dataverseService.setHarvestResult(info.getHarvestingDataverseId(), harvesterService.HARVEST_RESULT_FAILED);
            // mailService.sendHarvestErrorNotification(dataverseService.find().getSystemEmail(), dataverseService.find().getName());
            logException(e, logger);
        }
    } else if (timer.getInfo() instanceof ExportTimerInfo) {
        try {
            ExportTimerInfo info = (ExportTimerInfo) timer.getInfo();
            logger.info("Timer Service: Running a scheduled export job.");
            // try to export all unexported datasets:
            datasetService.exportAll();
            // and update all oai sets:
            oaiSetService.exportAllSets();
        } catch (Throwable e) {
            logException(e, logger);
        }
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) HarvestingClient(edu.harvard.iq.dataverse.harvest.client.HarvestingClient) HarvestTimerInfo(edu.harvard.iq.dataverse.harvest.client.HarvestTimerInfo) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) TransactionAttribute(javax.ejb.TransactionAttribute) Timeout(javax.ejb.Timeout)

Aggregations

DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)57 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)22 Dataverse (edu.harvard.iq.dataverse.Dataverse)21 Test (org.junit.Test)18 Dataset (edu.harvard.iq.dataverse.Dataset)15 Path (javax.ws.rs.Path)14 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)13 SwordError (org.swordapp.server.SwordError)10 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 DataverseRole (edu.harvard.iq.dataverse.authorization.DataverseRole)6 IOException (java.io.IOException)6 POST (javax.ws.rs.POST)6 DataFile (edu.harvard.iq.dataverse.DataFile)5 User (edu.harvard.iq.dataverse.authorization.users.User)5 HarvestingClient (edu.harvard.iq.dataverse.harvest.client.HarvestingClient)5 JsonObject (javax.json.JsonObject)5 JsonObjectBuilder (javax.json.JsonObjectBuilder)5 DepositReceipt (org.swordapp.server.DepositReceipt)5 RoleAssignment (edu.harvard.iq.dataverse.RoleAssignment)4