Search in sources :

Example 56 with Dataverse

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

the class ContainerManagerImpl method deleteContainer.

@Override
public void deleteContainer(String uri, AuthCredentials authCredentials, SwordConfiguration sc) throws SwordError, SwordServerException, SwordAuthException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvRequest = new DataverseRequest(user, httpRequest);
    logger.fine("deleteContainer called with url: " + uri);
    urlManager.processUrl(uri);
    logger.fine("original url: " + urlManager.getOriginalUrl());
    if (!"edit".equals(urlManager.getServlet())) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "edit servlet expected, not " + urlManager.getServlet());
    }
    String targetType = urlManager.getTargetType();
    if (!targetType.isEmpty()) {
        logger.fine("operating on target type: " + urlManager.getTargetType());
        if ("dataverse".equals(targetType)) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Dataverses can not be deleted via the Data Deposit API but other Dataverse APIs may support this operation.");
        } else if ("study".equals(targetType)) {
            String globalId = urlManager.getTargetIdentifier();
            logger.fine("globalId: " + globalId);
            if (globalId != null) {
                Dataset dataset = dataset = datasetService.findByGlobalId(globalId);
                if (dataset != null) {
                    Dataverse dvThatOwnsDataset = dataset.getOwner();
                    /**
                     * We are checking if DeleteDatasetVersionCommand can be
                     * called even though DeleteDatasetCommand can be called
                     * when a dataset hasn't been published. They should be
                     * equivalent in terms of a permission check.
                     */
                    DeleteDatasetVersionCommand deleteDatasetVersionCommand = new DeleteDatasetVersionCommand(dvRequest, dataset);
                    if (!permissionService.isUserAllowedOn(user, deleteDatasetVersionCommand, dataset)) {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to modify " + dvThatOwnsDataset.getAlias());
                    }
                    DatasetVersion.VersionState datasetVersionState = dataset.getLatestVersion().getVersionState();
                    if (dataset.isReleased()) {
                        if (datasetVersionState.equals(DatasetVersion.VersionState.DRAFT)) {
                            logger.info("destroying working copy version of dataset " + dataset.getGlobalId());
                            try {
                                engineSvc.submit(deleteDatasetVersionCommand);
                            } catch (CommandException ex) {
                                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Can't delete dataset version for " + dataset.getGlobalId() + ": " + ex);
                            }
                            logger.info("dataset version deleted for dataset id " + dataset.getId());
                        } else if (datasetVersionState.equals(DatasetVersion.VersionState.RELEASED)) {
                            throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "Deaccessioning a dataset is no longer supported as of Data Deposit API version in URL (" + swordConfiguration.getBaseUrlPathV1() + ") Equivalent functionality is being developed at https://github.com/IQSS/dataverse/issues/778");
                        } else if (datasetVersionState.equals(DatasetVersion.VersionState.DEACCESSIONED)) {
                            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Lastest version of dataset " + dataset.getGlobalId() + " has already been deaccessioned.");
                        } else if (datasetVersionState.equals(DatasetVersion.VersionState.ARCHIVED)) {
                            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Lastest version of dataset " + dataset.getGlobalId() + " has been archived and can not be deleted or deaccessioned.");
                        } else {
                            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Operation not valid for dataset " + dataset.getGlobalId() + " in state " + datasetVersionState);
                        }
                    /**
                     * @todo Reformat else below properly so you can
                     * just reformat the whole file in Netbeans or
                     * similar.
                     */
                    } else {
                        // dataset has never been published, this is just a sanity check (should always be draft)
                        if (datasetVersionState.equals(DatasetVersion.VersionState.DRAFT)) {
                            try {
                                engineSvc.submit(new DeleteDatasetCommand(dvRequest, dataset));
                                logger.fine("dataset deleted");
                            } catch (CommandExecutionException ex) {
                                // internal error
                                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Can't delete dataset: " + ex.getMessage());
                            } catch (CommandException ex) {
                                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Can't delete dataset: " + ex.getMessage());
                            }
                        } else {
                            // we should never get here. throw an error explaining why
                            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "dataset is in illegal state (not published yet not in draft)");
                        }
                    }
                } else {
                    throw new SwordError(404);
                }
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset to delete from URL: " + uri);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unsupported delete target in URL:" + uri);
        }
    } else {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No target for deletion specified");
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) SwordError(org.swordapp.server.SwordError) Dataset(edu.harvard.iq.dataverse.Dataset) DeleteDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetCommand) CommandExecutionException(edu.harvard.iq.dataverse.engine.command.exception.CommandExecutionException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) DeleteDatasetVersionCommand(edu.harvard.iq.dataverse.engine.command.impl.DeleteDatasetVersionCommand) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse)

Example 57 with Dataverse

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

the class ContainerManagerImpl method useHeaders.

@Override
public DepositReceipt useHeaders(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
    logger.fine("uri was " + uri);
    logger.fine("isInProgress:" + deposit.isInProgress());
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvRequest = new DataverseRequest(user, httpRequest);
    urlManager.processUrl(uri);
    String targetType = urlManager.getTargetType();
    if (!targetType.isEmpty()) {
        logger.fine("operating on target type: " + urlManager.getTargetType());
        if ("study".equals(targetType)) {
            String globalId = urlManager.getTargetIdentifier();
            if (globalId != null) {
                Dataset dataset = null;
                try {
                    dataset = datasetService.findByGlobalId(globalId);
                } catch (EJBException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset based on global id (" + globalId + ") in URL: " + uri);
                }
                if (dataset != null) {
                    Dataverse dvThatOwnsDataset = dataset.getOwner();
                    boolean doMinorVersionBump = false;
                    // if dataset is unreleased, major version; if released, then check if can be minor
                    if (dataset.isReleased() && dataset.getLatestVersion().isMinorUpdate()) {
                        doMinorVersionBump = true;
                    }
                    PublishDatasetCommand publishDatasetCommand = new PublishDatasetCommand(dataset, dvRequest, doMinorVersionBump);
                    if (!permissionService.isUserAllowedOn(user, publishDatasetCommand, dataset)) {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to modify dataverse " + dvThatOwnsDataset.getAlias());
                    }
                    if (!deposit.isInProgress()) {
                        /**
                         * We are considering a draft version of a study to
                         * be incomplete and are saying that sending
                         * isInProgress=false means the study version is
                         * complete and can be released.
                         *
                         * 9.2. Deposit Incomplete
                         *
                         * "If In-Progress is true, the server SHOULD expect
                         * the client to provide further updates to the item
                         * some undetermined time in the future. Details of
                         * how this is implemented is dependent on the
                         * server's purpose. For example, a repository
                         * system may hold items which are marked
                         * In-Progress in a workspace until such time as a
                         * client request indicates that the deposit is
                         * complete." --
                         * http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#continueddeposit_incomplete
                         */
                        if (!dataset.getLatestVersion().getVersionState().equals(DatasetVersion.VersionState.RELEASED)) {
                            try {
                                dataset = engineSvc.submit(publishDatasetCommand).getDataset();
                            } catch (CommandException ex) {
                                String msg = "Unable to publish dataset: " + ex;
                                logger.severe(msg + ": " + ex.getMessage());
                                throw SwordUtil.throwRegularSwordErrorWithoutStackTrace(msg);
                            }
                            ReceiptGenerator receiptGenerator = new ReceiptGenerator();
                            String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri);
                            DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, dataset);
                            return depositReceipt;
                        } else {
                            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Latest version of dataset " + globalId + " has already been published.");
                        }
                    } else {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Pass 'In-Progress: false' header to publish a dataset.");
                    }
                } else {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset using globalId " + globalId);
                }
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to find globalId for dataset in URL:" + uri);
            }
        } else if ("dataverse".equals(targetType)) {
            String dvAlias = urlManager.getTargetIdentifier();
            if (dvAlias != null) {
                Dataverse dvToRelease = dataverseService.findByAlias(dvAlias);
                if (dvToRelease != null) {
                    PublishDataverseCommand publishDataverseCommand = new PublishDataverseCommand(dvRequest, dvToRelease);
                    if (!permissionService.isUserAllowedOn(user, publishDataverseCommand, dvToRelease)) {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to modify dataverse " + dvAlias);
                    }
                    if (deposit.isInProgress()) {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unpublishing a dataverse is not supported.");
                    }
                    try {
                        engineSvc.submit(publishDataverseCommand);
                        ReceiptGenerator receiptGenerator = new ReceiptGenerator();
                        String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri);
                        DepositReceipt depositReceipt = receiptGenerator.createDataverseReceipt(baseUrl, dvToRelease);
                        return depositReceipt;
                    } catch (CommandException ex) {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't publish dataverse " + dvAlias + ": " + ex);
                    }
                } else {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataverse based on alias in URL: " + uri);
                }
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to find dataverse alias in URL: " + uri);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "unsupported target type (" + targetType + ") in URL:" + uri);
        }
    } else {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Target type missing from URL: " + uri);
    }
}
Also used : SwordError(org.swordapp.server.SwordError) PublishDataverseCommand(edu.harvard.iq.dataverse.engine.command.impl.PublishDataverseCommand) Dataset(edu.harvard.iq.dataverse.Dataset) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) DepositReceipt(org.swordapp.server.DepositReceipt) PublishDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.PublishDatasetCommand) EJBException(javax.ejb.EJBException)

Example 58 with Dataverse

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

the class ServiceDocumentManagerImpl method getServiceDocument.

@Override
public ServiceDocument getServiceDocument(String sdUri, AuthCredentials authCredentials, SwordConfiguration config) throws SwordError, SwordServerException, SwordAuthException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    String warning = urlManager.processUrl(sdUri);
    ServiceDocument service = new ServiceDocument();
    SwordWorkspace swordWorkspace = new SwordWorkspace();
    Dataverse rootDataverse = dataverseService.findRootDataverse();
    if (rootDataverse != null) {
        String name = rootDataverse.getName();
        if (name != null) {
            swordWorkspace.setTitle(name);
        }
    }
    if (warning != null) {
        swordWorkspace.getWrappedWorkspace().setAttributeValue("warning", warning);
    }
    service.setMaxUploadSize(config.getMaxUploadSize());
    String hostnamePlusBaseUrl = urlManager.getHostnamePlusBaseUrlPath(sdUri);
    if (hostnamePlusBaseUrl == null) {
        ServiceDocument serviceDocument = new ServiceDocument();
        return serviceDocument;
    }
    /**
     * We don't expect this to support Shibboleth groups because even though
     * a Shibboleth user can have an API token the transient
     * shibIdentityProvider String on AuthenticatedUser is only set when a
     * SAML assertion is made at runtime via the browser.
     */
    List<Dataverse> dataverses = permissionService.getDataversesUserHasPermissionOn(user, Permission.AddDataset);
    for (Dataverse dataverse : dataverses) {
        String dvAlias = dataverse.getAlias();
        if (dvAlias != null && !dvAlias.isEmpty()) {
            SwordCollection swordCollection = new SwordCollection();
            swordCollection.setTitle(dataverse.getName());
            swordCollection.setHref(hostnamePlusBaseUrl + "/collection/dataverse/" + dvAlias);
            swordCollection.addAcceptPackaging(UriRegistry.PACKAGE_SIMPLE_ZIP);
            swordCollection.setCollectionPolicy(systemConfig.getApiTermsOfUse());
            swordWorkspace.addCollection(swordCollection);
        }
    }
    service.addWorkspace(swordWorkspace);
    return service;
}
Also used : SwordWorkspace(org.swordapp.server.SwordWorkspace) ServiceDocument(org.swordapp.server.ServiceDocument) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) SwordCollection(org.swordapp.server.SwordCollection)

Example 59 with Dataverse

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

the class SavedSearches method toJson.

private JsonObjectBuilder toJson(SavedSearch savedSearch) {
    JsonObjectBuilder savedSearchJson = Json.createObjectBuilder();
    long savedSearchId = savedSearch.getId();
    Dataverse definitionPoint = savedSearch.getDefinitionPoint();
    JsonArrayBuilder fqBuilder = Json.createArrayBuilder();
    for (SavedSearchFilterQuery fq : savedSearch.getSavedSearchFilterQueries()) {
        fqBuilder.add(fq.getFilterQuery());
    }
    savedSearchJson.add("query", savedSearch.getQuery());
    savedSearchJson.add("filterQueries", fqBuilder);
    savedSearchJson.add("id", savedSearchId);
    savedSearchJson.add("definitionPointId", definitionPoint.getId());
    savedSearchJson.add("definitionPointAlias", definitionPoint.getAlias());
    savedSearchJson.add("creatorId", savedSearch.getCreator().getId());
    return savedSearchJson;
}
Also used : SavedSearchFilterQuery(edu.harvard.iq.dataverse.search.savedsearch.SavedSearchFilterQuery) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Dataverse(edu.harvard.iq.dataverse.Dataverse)

Example 60 with Dataverse

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

the class Dataverses method createDataset.

@POST
@Path("{identifier}/datasets")
public Response createDataset(String jsonBody, @PathParam("identifier") String parentIdtf) {
    try {
        User u = findUserOrDie();
        Dataverse owner = findDataverseOrDie(parentIdtf);
        JsonObject json;
        try (StringReader rdr = new StringReader(jsonBody)) {
            json = Json.createReader(rdr).readObject();
        } catch (JsonParsingException jpe) {
            LOGGER.log(Level.SEVERE, "Json: {0}", jsonBody);
            return error(Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
        }
        Dataset ds = new Dataset();
        ds.setOwner(owner);
        JsonObject jsonVersion = json.getJsonObject("datasetVersion");
        if (jsonVersion == null) {
            return error(Status.BAD_REQUEST, "Json POST data are missing datasetVersion object.");
        }
        try {
            try {
                DatasetVersion version = new DatasetVersion();
                version.setDataset(ds);
                // Use the two argument version so that the version knows which dataset it's associated with.
                version = jsonParser().parseDatasetVersion(jsonVersion, version);
                // force "initial version" properties
                version.setMinorVersionNumber(null);
                version.setVersionNumber(null);
                version.setVersionState(DatasetVersion.VersionState.DRAFT);
                LinkedList<DatasetVersion> versions = new LinkedList<>();
                versions.add(version);
                version.setDataset(ds);
                ds.setVersions(versions);
            } catch (javax.ejb.TransactionRolledbackLocalException rbe) {
                throw rbe.getCausedByException();
            }
        } catch (JsonParseException ex) {
            LOGGER.log(Level.INFO, "Error parsing dataset version from Json", ex);
            return error(Status.BAD_REQUEST, "Error parsing datasetVersion: " + ex.getMessage());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Error parsing dataset version from Json", e);
            return error(Status.INTERNAL_SERVER_ERROR, "Error parsing datasetVersion: " + e.getMessage());
        }
        Dataset managedDs = execCommand(new CreateDatasetCommand(ds, createDataverseRequest(u)));
        return created("/datasets/" + managedDs.getId(), Json.createObjectBuilder().add("id", managedDs.getId()).add("persistentId", managedDs.getGlobalId()));
    } catch (WrappedResponse ex) {
        return ex.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) CreateDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetCommand) JsonObject(javax.json.JsonObject) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) Dataverse(edu.harvard.iq.dataverse.Dataverse) LinkedList(java.util.LinkedList) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) EJBException(javax.ejb.EJBException) JsonParsingException(javax.json.stream.JsonParsingException) ConstraintViolationException(javax.validation.ConstraintViolationException) StringReader(java.io.StringReader) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

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