Search in sources :

Example 11 with SwordError

use of org.swordapp.server.SwordError in project mycore by MyCoRe-Org.

the class MCRSwordMediaHandler method replaceMediaResource.

public void replaceMediaResource(String derivateId, String requestFilePath, Deposit deposit) throws SwordError, SwordServerException {
    if (!MCRAccessManager.checkPermission(derivateId, MCRAccessManager.PERMISSION_WRITE)) {
        throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "You dont have the right to write to the derivate!");
    }
    MCRPath path = MCRPath.getPath(derivateId, requestFilePath);
    if (!Files.exists(path)) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND, "Cannot replace a not existing file.");
    }
    final boolean pathIsDirectory = Files.isDirectory(path);
    if (pathIsDirectory) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "replaceMediaResource is not supported with directories");
    }
// TODO: replace file
}
Also used : SwordError(org.swordapp.server.SwordError) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 12 with SwordError

use of org.swordapp.server.SwordError in project mycore by MyCoRe-Org.

the class MCRSwordMediaHandler method getMediaResourceRepresentation.

public MediaResource getMediaResourceRepresentation(String derivateID, String requestFilePath, Map<String, String> accept) throws SwordError, SwordServerException {
    MediaResource resultRessource;
    if (!MCRAccessManager.checkPermission(derivateID, MCRAccessManager.PERMISSION_READ)) {
        throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "You dont have the right to read from the derivate!");
    }
    if (requestFilePath != null && isValidFilePath(requestFilePath)) {
        final MCRPath path = MCRPath.getPath(derivateID, requestFilePath);
        checkFile(path);
        InputStream is = null;
        try {
            // MediaResource/Sword2 api should close the stream.
            is = Files.newInputStream(path);
            resultRessource = new MediaResource(is, Files.probeContentType(path), UriRegistry.PACKAGE_BINARY);
        } catch (IOException e) {
            LOGGER.error("Error while opening File: {}", path, e);
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e1) {
                    LOGGER.error("Could not close Stream after error. ", e);
                }
            }
            throw new SwordError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        // if there is no file path or file is just "/" or "" then send the zipped Derivate
        resultRessource = MCRSwordUtil.getZippedDerivateMediaResource(derivateID);
    }
    MCRSessionMgr.getCurrentSession().commitTransaction();
    return resultRessource;
}
Also used : SwordError(org.swordapp.server.SwordError) InputStream(java.io.InputStream) MediaResource(org.swordapp.server.MediaResource) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 13 with SwordError

use of org.swordapp.server.SwordError in project dataverse by IQSS.

the class ContainerManagerImpl method getEntry.

@Override
public DepositReceipt getEntry(String uri, Map<String, String> map, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordServerException, SwordError, SwordAuthException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
    logger.fine("getEntry called with url: " + uri);
    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();
            Dataset dataset = datasetService.findByGlobalId(globalId);
            if (dataset != null) {
                if (!permissionService.isUserAllowedOn(user, new GetDraftDatasetVersionCommand(dvReq, dataset), dataset)) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to retrieve entry for " + dataset.getGlobalId());
                }
                Dataverse dvThatOwnsDataset = dataset.getOwner();
                ReceiptGenerator receiptGenerator = new ReceiptGenerator();
                String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri);
                DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, dataset);
                if (depositReceipt != null) {
                    return depositReceipt;
                } else {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not generate deposit receipt.");
                }
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset based on 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, "Unable to determine target type from URL: " + uri);
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) SwordError(org.swordapp.server.SwordError) DepositReceipt(org.swordapp.server.DepositReceipt) Dataset(edu.harvard.iq.dataverse.Dataset) GetDraftDatasetVersionCommand(edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse)

Example 14 with SwordError

use of org.swordapp.server.SwordError 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 15 with SwordError

use of org.swordapp.server.SwordError 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)

Aggregations

SwordError (org.swordapp.server.SwordError)21 Dataset (edu.harvard.iq.dataverse.Dataset)10 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)10 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)10 Dataverse (edu.harvard.iq.dataverse.Dataverse)9 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)6 DepositReceipt (org.swordapp.server.DepositReceipt)5 UpdateDatasetCommand (edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand)4 IOException (java.io.IOException)4 List (java.util.List)4 EJBException (javax.ejb.EJBException)4 MCRPath (org.mycore.datamodel.niofs.MCRPath)4 SwordServerException (org.swordapp.server.SwordServerException)4 DataFile (edu.harvard.iq.dataverse.DataFile)3 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)3 InputStream (java.io.InputStream)3 URISyntaxException (java.net.URISyntaxException)3 CommandExecutionException (edu.harvard.iq.dataverse.engine.command.exception.CommandExecutionException)2 GetDraftDatasetVersionCommand (edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand)2 URI (java.net.URI)2