Search in sources :

Example 11 with Dataverse

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

the class Dataverses method createAssignment.

/**
 * This code for setting a dataverse logo via API was started when initially
 * investigating https://github.com/IQSS/dataverse/issues/3559 but it isn't
 * finished so it's commented out. See also * "No functionality should be
 * GUI-only. Make all functionality reachable via the API" at
 * https://github.com/IQSS/dataverse/issues/3440
 */
// File tempDir;
// 
// private void createTempDir(Dataverse editDv) {
// try {
// File tempRoot = java.nio.file.Files.createDirectories(Paths.get("../docroot/logos/temp")).toFile();
// tempDir = java.nio.file.Files.createTempDirectory(tempRoot.toPath(), editDv.getId().toString()).toFile();
// } catch (IOException e) {
// throw new RuntimeException("Error creating temp directory", e); // improve error handling
// }
// }
// 
// private DataverseTheme initDataverseTheme(Dataverse editDv) {
// DataverseTheme dvt = new DataverseTheme();
// dvt.setLinkColor(DEFAULT_LINK_COLOR);
// dvt.setLogoBackgroundColor(DEFAULT_LOGO_BACKGROUND_COLOR);
// dvt.setBackgroundColor(DEFAULT_BACKGROUND_COLOR);
// dvt.setTextColor(DEFAULT_TEXT_COLOR);
// dvt.setDataverse(editDv);
// return dvt;
// }
// 
// @PUT
// @Path("{identifier}/logo")
// @Consumes(MediaType.MULTIPART_FORM_DATA)
// public Response setDataverseLogo(@PathParam("identifier") String dvIdtf,
// @FormDataParam("file") InputStream fileInputStream,
// @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
// @QueryParam("key") String apiKey) {
// boolean disabled = true;
// if (disabled) {
// return error(Status.FORBIDDEN, "Setting the dataverse logo via API needs more work.");
// }
// try {
// final DataverseRequest req = createDataverseRequest(findUserOrDie());
// final Dataverse editDv = findDataverseOrDie(dvIdtf);
// 
// logger.finer("entering fileUpload");
// if (tempDir == null) {
// createTempDir(editDv);
// logger.finer("created tempDir");
// }
// File uploadedFile;
// try {
// String fileName = contentDispositionHeader.getFileName();
// 
// uploadedFile = new File(tempDir, fileName);
// if (!uploadedFile.exists()) {
// uploadedFile.createNewFile();
// }
// logger.finer("created file");
// File file = null;
// file = FileUtil.inputStreamToFile(fileInputStream);
// if (file.length() > systemConfig.getUploadLogoSizeLimit()) {
// return error(Response.Status.BAD_REQUEST, "File is larger than maximum size: " + systemConfig.getUploadLogoSizeLimit() + ".");
// }
// java.nio.file.Files.copy(fileInputStream, uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
// logger.finer("copied inputstream to file");
// editDv.setDataverseTheme(initDataverseTheme(editDv));
// editDv.getDataverseTheme().setLogo(fileName);
// 
// } catch (IOException e) {
// logger.finer("caught IOException");
// logger.throwing("ThemeWidgetFragment", "handleImageFileUpload", e);
// throw new RuntimeException("Error uploading logo file", e); // improve error handling
// }
// // If needed, set the default values for the logo
// if (editDv.getDataverseTheme().getLogoFormat() == null) {
// editDv.getDataverseTheme().setLogoFormat(DataverseTheme.ImageFormat.SQUARE);
// }
// logger.finer("end handelImageFileUpload");
// UpdateDataverseThemeCommand cmd = new UpdateDataverseThemeCommand(editDv, uploadedFile, req);
// Dataverse saved = execCommand(cmd);
// 
// /**
// * @todo delete the temp file:
// * docroot/logos/temp/1148114212463761832421/cc0.png
// */
// return ok("logo uploaded: " + saved.getDataverseTheme().getLogo());
// } catch (WrappedResponse ex) {
// return error(Status.BAD_REQUEST, "problem uploading logo: " + ex);
// }
// }
@POST
@Path("{identifier}/assignments")
public Response createAssignment(RoleAssignmentDTO ra, @PathParam("identifier") String dvIdtf, @QueryParam("key") String apiKey) {
    try {
        final DataverseRequest req = createDataverseRequest(findUserOrDie());
        final Dataverse dataverse = findDataverseOrDie(dvIdtf);
        RoleAssignee assignee = findAssignee(ra.getAssignee());
        if (assignee == null) {
            return error(Status.BAD_REQUEST, "Assignee not found");
        }
        DataverseRole theRole;
        Dataverse dv = dataverse;
        theRole = null;
        while ((theRole == null) && (dv != null)) {
            for (DataverseRole aRole : rolesSvc.availableRoles(dv.getId())) {
                if (aRole.getAlias().equals(ra.getRole())) {
                    theRole = aRole;
                    break;
                }
            }
            dv = dv.getOwner();
        }
        if (theRole == null) {
            return error(Status.BAD_REQUEST, "Can't find role named '" + ra.getRole() + "' in dataverse " + dataverse);
        }
        String privateUrlToken = null;
        return ok(json(execCommand(new AssignRoleCommand(assignee, theRole, dataverse, req, privateUrlToken))));
    } catch (WrappedResponse ex) {
        LOGGER.log(Level.WARNING, "Can''t create assignment: {0}", ex.getMessage());
        return ex.getResponse();
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) JsonString(javax.json.JsonString) AssignRoleCommand(edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand) Dataverse(edu.harvard.iq.dataverse.Dataverse) RoleAssignee(edu.harvard.iq.dataverse.authorization.RoleAssignee) DataverseRole(edu.harvard.iq.dataverse.authorization.DataverseRole) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 12 with Dataverse

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

the class Dataverses method setMetadataRoot.

@PUT
@Path("{identifier}/metadatablocks/isRoot")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.WILDCARD)
public Response setMetadataRoot(@PathParam("identifier") String dvIdtf, String body) {
    return response(req -> {
        final boolean root = parseBooleanOrDie(body);
        final Dataverse dataverse = findDataverseOrDie(dvIdtf);
        execCommand(new UpdateDataverseMetadataBlocksCommand.SetRoot(req, dataverse, root));
        return ok("Dataverse " + dataverse.getName() + " is now a metadata  " + (root ? "" : "non-") + "root");
    });
}
Also used : Dataverse(edu.harvard.iq.dataverse.Dataverse) UpdateDataverseMetadataBlocksCommand(edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseMetadataBlocksCommand) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 13 with Dataverse

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

the class HarvestingClients method createHarvestingClient.

@POST
@Path("{nickName}")
public Response createHarvestingClient(String jsonBody, @PathParam("nickName") String nickName, @QueryParam("key") String apiKey) throws IOException, JsonParseException {
    try (StringReader rdr = new StringReader(jsonBody)) {
        JsonObject json = Json.createReader(rdr).readObject();
        HarvestingClient harvestingClient = new HarvestingClient();
        // TODO: check that it doesn't exist yet...
        harvestingClient.setName(nickName);
        String dataverseAlias = jsonParser().parseHarvestingClient(json, harvestingClient);
        Dataverse ownerDataverse = dataverseService.findByAlias(dataverseAlias);
        if (ownerDataverse == null) {
            return error(Response.Status.BAD_REQUEST, "No such dataverse: " + dataverseAlias);
        }
        harvestingClient.setDataverse(ownerDataverse);
        if (ownerDataverse.getHarvestingClientConfigs() == null) {
            ownerDataverse.setHarvestingClientConfigs(new ArrayList<>());
        }
        ownerDataverse.getHarvestingClientConfigs().add(harvestingClient);
        DataverseRequest req = createDataverseRequest(findUserOrDie());
        HarvestingClient managedHarvestingClient = execCommand(new CreateHarvestingClientCommand(req, harvestingClient));
        return created("/harvest/clients/" + nickName, harvestingConfigAsJson(managedHarvestingClient));
    } catch (JsonParseException ex) {
        return error(Response.Status.BAD_REQUEST, "Error parsing harvesting client: " + ex.getMessage());
    } catch (WrappedResponse ex) {
        return ex.getResponse();
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) CreateHarvestingClientCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateHarvestingClientCommand) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) HarvestingClient(edu.harvard.iq.dataverse.harvest.client.HarvestingClient) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) Dataverse(edu.harvard.iq.dataverse.Dataverse) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 14 with Dataverse

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

the class Index method getContentInDatabaseButStaleInOrMissingFromSolr.

private JsonObjectBuilder getContentInDatabaseButStaleInOrMissingFromSolr() {
    List<Dataverse> stateOrMissingDataverses = indexService.findStaleOrMissingDataverses();
    List<Dataset> staleOrMissingDatasets = indexService.findStaleOrMissingDatasets();
    JsonArrayBuilder jsonStateOrMissingDataverses = Json.createArrayBuilder();
    for (Dataverse dataverse : stateOrMissingDataverses) {
        jsonStateOrMissingDataverses.add(dataverse.getId());
    }
    JsonArrayBuilder datasetsInDatabaseButNotSolr = Json.createArrayBuilder();
    for (Dataset dataset : staleOrMissingDatasets) {
        datasetsInDatabaseButNotSolr.add(dataset.getId());
    }
    JsonObjectBuilder contentInDatabaseButStaleInOrMissingFromSolr = Json.createObjectBuilder().add("dataverses", jsonStateOrMissingDataverses.build().size()).add("datasets", datasetsInDatabaseButNotSolr.build().size());
    return contentInDatabaseButStaleInOrMissingFromSolr;
}
Also used : Dataset(edu.harvard.iq.dataverse.Dataset) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Dataverse(edu.harvard.iq.dataverse.Dataverse)

Example 15 with Dataverse

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

the class Index method searchDebug.

/**
 * This method is for integration tests of search.
 */
@GET
@Path("test")
public Response searchDebug(@QueryParam("key") String apiToken, @QueryParam("q") String query, @QueryParam("fq") final List<String> filterQueries) {
    User user = findUserByApiToken(apiToken);
    if (user == null) {
        return error(Response.Status.UNAUTHORIZED, "Invalid apikey '" + apiToken + "'");
    }
    Dataverse subtreeScope = dataverseService.findRootDataverse();
    String sortField = SearchFields.ID;
    String sortOrder = SortBy.ASCENDING;
    int paginationStart = 0;
    boolean dataRelatedToMe = false;
    int numResultsPerPage = Integer.MAX_VALUE;
    SolrQueryResponse solrQueryResponse;
    try {
        solrQueryResponse = searchService.search(createDataverseRequest(user), subtreeScope, query, filterQueries, sortField, sortOrder, paginationStart, dataRelatedToMe, numResultsPerPage);
    } catch (SearchException ex) {
        return error(Response.Status.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage() + ": " + ex.getCause().getLocalizedMessage());
    }
    JsonArrayBuilder itemsArrayBuilder = Json.createArrayBuilder();
    List<SolrSearchResult> solrSearchResults = solrQueryResponse.getSolrSearchResults();
    for (SolrSearchResult solrSearchResult : solrSearchResults) {
        itemsArrayBuilder.add(solrSearchResult.getType() + ":" + solrSearchResult.getNameSort());
    }
    return ok(itemsArrayBuilder);
}
Also used : SolrSearchResult(edu.harvard.iq.dataverse.search.SolrSearchResult) SolrQueryResponse(edu.harvard.iq.dataverse.search.SolrQueryResponse) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) GuestUser(edu.harvard.iq.dataverse.authorization.users.GuestUser) SearchException(edu.harvard.iq.dataverse.search.SearchException) JsonArrayBuilder(javax.json.JsonArrayBuilder) Dataverse(edu.harvard.iq.dataverse.Dataverse) 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