Search in sources :

Example 76 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class DataFileServiceBean method retrieveFileAccessRequesters.

private List<AuthenticatedUser> retrieveFileAccessRequesters(DataFile fileIn) {
    List<AuthenticatedUser> retList = new ArrayList<>();
    List<Object> requesters = em.createNativeQuery("select authenticated_user_id from fileaccessrequests where datafile_id = " + fileIn.getId()).getResultList();
    for (Object userIdObj : requesters) {
        Long userId = (Long) userIdObj;
        AuthenticatedUser user = userService.find(userId);
        if (user != null) {
            retList.add(user);
        }
    }
    return retList;
}
Also used : ArrayList(java.util.ArrayList) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 77 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class ConfigureFragmentBean method getConfigurePopupToolHandler.

public ExternalToolHandler getConfigurePopupToolHandler() {
    if (fileId == null) {
        // on first UI load, method is called before fileId is set. There may be a better way to handle this
        return null;
    }
    if (toolHandler != null) {
        return toolHandler;
    }
    datafileService.find(fileId);
    ApiToken apiToken = new ApiToken();
    User user = session.getUser();
    if (user instanceof AuthenticatedUser) {
        apiToken = authService.findApiTokenByUser((AuthenticatedUser) user);
    }
    toolHandler = new ExternalToolHandler(tool, datafileService.find(fileId), apiToken);
    return toolHandler;
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) ExternalToolHandler(edu.harvard.iq.dataverse.externaltools.ExternalToolHandler) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 78 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class UpdateDatasetCommand method execute.

@Override
public Dataset execute(CommandContext ctxt) throws CommandException {
    ctxt.permissions().checkEditDatasetLock(theDataset, getRequest(), this);
    // first validate
    // @todo for now we run through an initFields method that creates empty fields for anything without a value
    // that way they can be checked for required
    theDataset.getEditVersion().setDatasetFields(theDataset.getEditVersion().initDatasetFields());
    Set<ConstraintViolation> constraintViolations = theDataset.getEditVersion().validate();
    if (!constraintViolations.isEmpty()) {
        if (validateLenient) {
            // for example, saving files, shouldn't validate metadata
            for (ConstraintViolation v : constraintViolations) {
                DatasetField f = ((DatasetField) v.getRootBean());
                f.setSingleValue(DatasetField.NA_VALUE);
            }
        } else {
            String validationFailedString = "Validation failed:";
            for (ConstraintViolation constraintViolation : constraintViolations) {
                validationFailedString += " " + constraintViolation.getMessage();
            }
            throw new IllegalCommandException(validationFailedString, this);
        }
    }
    if (!(getUser() instanceof AuthenticatedUser)) {
        throw new IllegalCommandException("Only authenticated users can update datasets", this);
    }
    return save(ctxt);
}
Also used : ConstraintViolation(javax.validation.ConstraintViolation) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 79 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser 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 80 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class HarvestingServer method createOaiSet.

/**
 * create an OAI set from spec in path and other parameters from POST body
 * (as JSON). {"name":$set_name,
 * "description":$optional_set_description,"definition":$set_search_query_string}.
 */
@POST
@Path("{specname}")
public Response createOaiSet(String jsonBody, @PathParam("specname") String spec, @QueryParam("key") String apiKey) throws IOException, JsonParseException {
    /*
	     * authorization modeled after the UI (aka HarvestingSetsPage)
         */
    AuthenticatedUser dvUser;
    try {
        dvUser = findAuthenticatedUserOrDie();
    } catch (WrappedResponse wr) {
        return wr.getResponse();
    }
    if (!dvUser.isSuperuser()) {
        return badRequest(ResourceBundle.getBundle("Bundle").getString("harvestserver.newSetDialog.setspec.superUser.required"));
    }
    StringReader rdr = new StringReader(jsonBody);
    try (JsonReader jrdr = Json.createReader(rdr)) {
        JsonObject json = jrdr.readObject();
        OAISet set = new OAISet();
        // Validating spec
        if (!StringUtils.isEmpty(spec)) {
            if (spec.length() > 30) {
                return badRequest(ResourceBundle.getBundle("Bundle").getString("harvestserver.newSetDialog.setspec.sizelimit"));
            }
            if (!Pattern.matches("^[a-zA-Z0-9\\_\\-]+$", spec)) {
                return badRequest(ResourceBundle.getBundle("Bundle").getString("harvestserver.newSetDialog.setspec.invalid"));
            // If it passes the regex test, check
            }
            if (oaiSetService.findBySpec(spec) != null) {
                return badRequest(ResourceBundle.getBundle("Bundle").getString("harvestserver.newSetDialog.setspec.alreadyused"));
            }
        } else {
            return badRequest(ResourceBundle.getBundle("Bundle").getString("harvestserver.newSetDialog.setspec.required"));
        }
        set.setSpec(spec);
        String name, desc, defn;
        try {
            name = json.getString("name");
        } catch (NullPointerException npe_name) {
            return badRequest(ResourceBundle.getBundle("Bundle").getString("harvestserver.newSetDialog.setspec.required"));
        }
        try {
            defn = json.getString("definition");
        } catch (NullPointerException npe_defn) {
            throw new JsonParseException("definition unspecified");
        }
        try {
            desc = json.getString("description");
        } catch (NullPointerException npe_desc) {
            // treating description as optional
            desc = "";
        }
        set.setName(name);
        set.setDescription(desc);
        set.setDefinition(defn);
        oaiSetService.save(set);
        return created("/harvest/server/oaisets" + spec, oaiSetAsJson(set));
    }
}
Also used : StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) OAISet(edu.harvard.iq.dataverse.harvest.server.OAISet) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Aggregations

AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)125 Dataverse (edu.harvard.iq.dataverse.Dataverse)24 Timestamp (java.sql.Timestamp)24 Date (java.util.Date)24 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)23 Dataset (edu.harvard.iq.dataverse.Dataset)22 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)21 Path (javax.ws.rs.Path)19 EJBException (javax.ejb.EJBException)16 ArrayList (java.util.ArrayList)14 User (edu.harvard.iq.dataverse.authorization.users.User)13 DataFile (edu.harvard.iq.dataverse.DataFile)11 IOException (java.io.IOException)11 JsonObjectBuilder (javax.json.JsonObjectBuilder)11 POST (javax.ws.rs.POST)11 Test (org.junit.Test)11 BuiltinUser (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)10 SwordError (org.swordapp.server.SwordError)10 DataverseRole (edu.harvard.iq.dataverse.authorization.DataverseRole)8 PermissionException (edu.harvard.iq.dataverse.engine.command.exception.PermissionException)8