Search in sources :

Example 61 with Dataverse

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

the class Dataverses method setFacets.

@POST
@Path("{identifier}/facets")
@Produces(MediaType.APPLICATION_JSON)
public /**
 * (not publicly documented) API endpoint for assigning facets to a dataverse.
 * `curl -X POST -H "X-Dataverse-key: $ADMIN_KEY" http://localhost:8088/api/dataverses/$dv/facets --upload-file foo.json`; where foo.json contains a list of datasetField names,
 * works as expected (judging by the UI).
 * This triggers a 500 when '-d @foo.json' is used.
 */
Response setFacets(@PathParam("identifier") String dvIdtf, String facetIds) {
    List<DatasetFieldType> facets = new LinkedList<>();
    for (JsonString facetId : Util.asJsonArray(facetIds).getValuesAs(JsonString.class)) {
        DatasetFieldType dsfType = findDatasetFieldType(facetId.getString());
        if (dsfType == null) {
            return error(Response.Status.BAD_REQUEST, "Can't find dataset field type '" + facetId + "'");
        } else if (!dsfType.isFacetable()) {
            return error(Response.Status.BAD_REQUEST, "Dataset field type '" + facetId + "' is not facetable");
        }
        facets.add(dsfType);
    }
    try {
        Dataverse dataverse = findDataverseOrDie(dvIdtf);
        // by passing null for Featured Dataverses and DataverseFieldTypeInputLevel, those are not changed
        execCommand(new UpdateDataverseCommand(dataverse, facets, null, createDataverseRequest(findUserOrDie()), null));
        return ok("Facets of dataverse " + dvIdtf + " updated.");
    } catch (WrappedResponse ex) {
        return ex.getResponse();
    }
}
Also used : UpdateDataverseCommand(edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseCommand) JsonString(javax.json.JsonString) DatasetFieldType(edu.harvard.iq.dataverse.DatasetFieldType) Dataverse(edu.harvard.iq.dataverse.Dataverse) LinkedList(java.util.LinkedList) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 62 with Dataverse

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

the class Dataverses method listFacets.

@GET
@Path("{identifier}/facets/")
public /**
 * return list of facets for the dataverse with alias `dvIdtf`
 */
Response listFacets(@PathParam("identifier") String dvIdtf) {
    try {
        User u = findUserOrDie();
        DataverseRequest r = createDataverseRequest(u);
        Dataverse dataverse = findDataverseOrDie(dvIdtf);
        JsonArrayBuilder fs = Json.createArrayBuilder();
        for (DataverseFacet f : execCommand(new ListFacetsCommand(r, dataverse))) {
            fs.add(f.getDatasetFieldType().getName());
        }
        return allowCors(ok(fs));
    } catch (WrappedResponse e) {
        return e.getResponse();
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) ListFacetsCommand(edu.harvard.iq.dataverse.engine.command.impl.ListFacetsCommand) JsonArrayBuilder(javax.json.JsonArrayBuilder) Dataverse(edu.harvard.iq.dataverse.Dataverse) DataverseFacet(edu.harvard.iq.dataverse.DataverseFacet) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 63 with Dataverse

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

the class Dataverses method listLinks.

@GET
@Path("{identifier}/links")
public Response listLinks(@PathParam("identifier") String dvIdtf) {
    try {
        User u = findUserOrDie();
        Dataverse dv = findDataverseOrDie(dvIdtf);
        if (!u.isSuperuser()) {
            return error(Status.FORBIDDEN, "Not a superuser");
        }
        List<Dataverse> dvsThisDvHasLinkedToList = dataverseSvc.findDataversesThisIdHasLinkedTo(dv.getId());
        JsonArrayBuilder dvsThisDvHasLinkedToBuilder = Json.createArrayBuilder();
        for (Dataverse dataverse : dvsThisDvHasLinkedToList) {
            dvsThisDvHasLinkedToBuilder.add(dataverse.getAlias());
        }
        List<Dataverse> dvsThatLinkToThisDvList = dataverseSvc.findDataversesThatLinkToThisDvId(dv.getId());
        JsonArrayBuilder dvsThatLinkToThisDvBuilder = Json.createArrayBuilder();
        for (Dataverse dataverse : dvsThatLinkToThisDvList) {
            dvsThatLinkToThisDvBuilder.add(dataverse.getAlias());
        }
        List<Dataset> datasetsThisDvHasLinkedToList = dataverseSvc.findDatasetsThisIdHasLinkedTo(dv.getId());
        JsonArrayBuilder datasetsThisDvHasLinkedToBuilder = Json.createArrayBuilder();
        for (Dataset dataset : datasetsThisDvHasLinkedToList) {
            datasetsThisDvHasLinkedToBuilder.add(dataset.getLatestVersion().getTitle());
        }
        JsonObjectBuilder response = Json.createObjectBuilder();
        response.add("dataverses that the " + dv.getAlias() + " dataverse has linked to", dvsThisDvHasLinkedToBuilder);
        response.add("dataverses that link to the " + dv.getAlias(), dvsThatLinkToThisDvBuilder);
        response.add("datasets that the " + dv.getAlias() + " has linked to", datasetsThisDvHasLinkedToBuilder);
        return ok(response);
    } catch (WrappedResponse wr) {
        return wr.getResponse();
    }
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) Dataset(edu.harvard.iq.dataverse.Dataset) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Dataverse(edu.harvard.iq.dataverse.Dataverse) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 64 with Dataverse

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

the class Dataverses method addDataverse.

@POST
@Path("{identifier}")
public Response addDataverse(String body, @PathParam("identifier") String parentIdtf) {
    Dataverse d;
    JsonObject dvJson;
    try (StringReader rdr = new StringReader(body)) {
        dvJson = Json.createReader(rdr).readObject();
        d = jsonParser().parseDataverse(dvJson);
    } catch (JsonParsingException jpe) {
        LOGGER.log(Level.SEVERE, "Json: {0}", body);
        return error(Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    } catch (JsonParseException ex) {
        Logger.getLogger(Dataverses.class.getName()).log(Level.SEVERE, "Error parsing dataverse from json: " + ex.getMessage(), ex);
        return error(Response.Status.BAD_REQUEST, "Error parsing the POSTed json into a dataverse: " + ex.getMessage());
    }
    try {
        if (!parentIdtf.isEmpty()) {
            Dataverse owner = findDataverseOrDie(parentIdtf);
            d.setOwner(owner);
        }
        // set the dataverse - contact relationship in the contacts
        for (DataverseContact dc : d.getDataverseContacts()) {
            dc.setDataverse(d);
        }
        AuthenticatedUser u = findAuthenticatedUserOrDie();
        d = execCommand(new CreateDataverseCommand(d, createDataverseRequest(u), null, null));
        return created("/dataverses/" + d.getAlias(), json(d));
    } catch (WrappedResponse ww) {
        Throwable cause = ww.getCause();
        StringBuilder sb = new StringBuilder();
        if (cause == null) {
            return ww.refineResponse("cause was null!");
        }
        while (cause.getCause() != null) {
            cause = cause.getCause();
            if (cause instanceof ConstraintViolationException) {
                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());
                }
            }
        }
        String error = sb.toString();
        if (!error.isEmpty()) {
            LOGGER.log(Level.INFO, error);
            return ww.refineResponse(error);
        }
        return ww.getResponse();
    } catch (EJBException ex) {
        Throwable cause = ex;
        StringBuilder sb = new StringBuilder();
        sb.append("Error creating dataverse.");
        while (cause.getCause() != null) {
            cause = cause.getCause();
            if (cause instanceof ConstraintViolationException) {
                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());
        return error(Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + sb.toString());
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Error creating dataverse", ex);
        return error(Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + ex.getMessage());
    }
}
Also used : JsonObject(javax.json.JsonObject) DataverseContact(edu.harvard.iq.dataverse.DataverseContact) JsonString(javax.json.JsonString) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) CreateDataverseCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateDataverseCommand) Dataverse(edu.harvard.iq.dataverse.Dataverse) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) EJBException(javax.ejb.EJBException) JsonParsingException(javax.json.stream.JsonParsingException) ConstraintViolationException(javax.validation.ConstraintViolationException) ConstraintViolation(javax.validation.ConstraintViolation) StringReader(java.io.StringReader) ConstraintViolationException(javax.validation.ConstraintViolationException) EJBException(javax.ejb.EJBException) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 65 with Dataverse

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

the class Index method indexTypeById.

@GET
@Path("{type}/{id}")
public Response indexTypeById(@PathParam("type") String type, @PathParam("id") Long id) {
    try {
        if (type.equals("dataverses")) {
            Dataverse dataverse = dataverseService.find(id);
            if (dataverse != null) {
                /**
                 * @todo Can we display the result of indexing to the user?
                 */
                Future<String> indexDataverseFuture = indexService.indexDataverse(dataverse);
                return ok("starting reindex of dataverse " + id);
            } else {
                String response = indexService.removeSolrDocFromIndex(IndexServiceBean.solrDocIdentifierDataverse + id);
                return notFound("Could not find dataverse with id of " + id + ". Result from deletion attempt: " + response);
            }
        } else if (type.equals("datasets")) {
            Dataset dataset = datasetService.find(id);
            if (dataset != null) {
                boolean doNormalSolrDocCleanUp = true;
                Future<String> indexDatasetFuture = indexService.indexDataset(dataset, doNormalSolrDocCleanUp);
                return ok("starting reindex of dataset " + id);
            } else {
                /**
                 * @todo what about published, deaccessioned, etc.? Need
                 * method to target those, not just drafts!
                 */
                String response = indexService.removeSolrDocFromIndex(IndexServiceBean.solrDocIdentifierDataset + id + IndexServiceBean.draftSuffix);
                return notFound("Could not find dataset with id of " + id + ". Result from deletion attempt: " + response);
            }
        } else if (type.equals("files")) {
            DataFile dataFile = dataFileService.find(id);
            Dataset datasetThatOwnsTheFile = datasetService.find(dataFile.getOwner().getId());
            /**
             * @todo How can we display the result to the user?
             */
            boolean doNormalSolrDocCleanUp = true;
            Future<String> indexDatasetFuture = indexService.indexDataset(datasetThatOwnsTheFile, doNormalSolrDocCleanUp);
            return ok("started reindexing " + type + "/" + id);
        } else {
            return error(Status.BAD_REQUEST, "illegal type: " + type);
        }
    } catch (EJBException ex) {
        Throwable cause = ex;
        StringBuilder sb = new StringBuilder();
        sb.append("Problem indexing ").append(type).append("/").append(id).append(": ");
        sb.append(ex).append(" ");
        while (cause.getCause() != null) {
            cause = cause.getCause();
            sb.append(cause.getClass().getCanonicalName()).append(" ");
            sb.append(cause.getMessage()).append(" ");
            if (cause instanceof ConstraintViolationException) {
                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()).append(")");
                }
            } else if (cause instanceof NullPointerException) {
                for (int i = 0; i < 2; i++) {
                    StackTraceElement stacktrace = cause.getStackTrace()[i];
                    if (stacktrace != null) {
                        String classCanonicalName = stacktrace.getClass().getCanonicalName();
                        String methodName = stacktrace.getMethodName();
                        int lineNumber = stacktrace.getLineNumber();
                        String error = "at " + stacktrace.getClassName() + "." + stacktrace.getMethodName() + "(" + stacktrace.getFileName() + ":" + lineNumber + ") ";
                        sb.append(error);
                    }
                }
            }
        }
        return error(Status.INTERNAL_SERVER_ERROR, sb.toString());
    }
}
Also used : Dataset(edu.harvard.iq.dataverse.Dataset) Dataverse(edu.harvard.iq.dataverse.Dataverse) DataFile(edu.harvard.iq.dataverse.DataFile) ConstraintViolation(javax.validation.ConstraintViolation) Future(java.util.concurrent.Future) ConstraintViolationException(javax.validation.ConstraintViolationException) EJBException(javax.ejb.EJBException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

Dataverse (edu.harvard.iq.dataverse.Dataverse)94 Dataset (edu.harvard.iq.dataverse.Dataset)34 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)31 Test (org.junit.Test)27 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)22 DataFile (edu.harvard.iq.dataverse.DataFile)18 IOException (java.io.IOException)18 Path (javax.ws.rs.Path)16 JsonObject (javax.json.JsonObject)15 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)11 ArrayList (java.util.ArrayList)11 EJBException (javax.ejb.EJBException)11 JsonObjectBuilder (javax.json.JsonObjectBuilder)11 InputStream (java.io.InputStream)10 Date (java.util.Date)10 JsonArrayBuilder (javax.json.JsonArrayBuilder)10 POST (javax.ws.rs.POST)10 DataverseRole (edu.harvard.iq.dataverse.authorization.DataverseRole)9 User (edu.harvard.iq.dataverse.authorization.users.User)9 SwordError (org.swordapp.server.SwordError)9