Search in sources :

Example 1 with SwordServerException

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

the class CollectionDepositManagerImpl method createNew.

@Override
public DepositReceipt createNew(String collectionUri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration config) throws SwordError, SwordServerException, SwordAuthException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvReq = new DataverseRequest(user, request);
    urlManager.processUrl(collectionUri);
    String dvAlias = urlManager.getTargetIdentifier();
    if (urlManager.getTargetType().equals("dataverse") && dvAlias != null) {
        logger.log(Level.FINE, "attempting deposit into this dataverse alias: {0}", dvAlias);
        Dataverse dvThatWillOwnDataset = dataverseService.findByAlias(dvAlias);
        if (dvThatWillOwnDataset != null) {
            logger.log(Level.FINE, "multipart: {0}", deposit.isMultipart());
            logger.log(Level.FINE, "binary only: {0}", deposit.isBinaryOnly());
            logger.log(Level.FINE, "entry only: {0}", deposit.isEntryOnly());
            logger.log(Level.FINE, "in progress: {0}", deposit.isInProgress());
            logger.log(Level.FINE, "metadata relevant: {0}", deposit.isMetadataRelevant());
            if (deposit.isEntryOnly()) {
                // do a sanity check on the XML received
                try {
                    SwordEntry swordEntry = deposit.getSwordEntry();
                    logger.log(Level.FINE, "deposit XML received by createNew():\n{0}", swordEntry.toString());
                } catch (ParseException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Can not create dataset due to malformed Atom entry: " + ex);
                }
                Dataset dataset = new Dataset();
                dataset.setOwner(dvThatWillOwnDataset);
                String nonNullDefaultIfKeyNotFound = "";
                String protocol = settingsService.getValueForKey(SettingsServiceBean.Key.Protocol, nonNullDefaultIfKeyNotFound);
                String authority = settingsService.getValueForKey(SettingsServiceBean.Key.Authority, nonNullDefaultIfKeyNotFound);
                String separator = settingsService.getValueForKey(SettingsServiceBean.Key.DoiSeparator, nonNullDefaultIfKeyNotFound);
                dataset.setProtocol(protocol);
                dataset.setAuthority(authority);
                dataset.setDoiSeparator(separator);
                // Wait until the create command before actually getting an identifier
                // dataset.setIdentifier(datasetService.generateDatasetIdentifier(protocol, authority, separator));
                logger.log(Level.FINE, "DS Deposit identifier: {0}", dataset.getIdentifier());
                CreateDatasetCommand createDatasetCommand = new CreateDatasetCommand(dataset, dvReq, false);
                if (!permissionService.isUserAllowedOn(user, createDatasetCommand, dataset)) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to create a dataset in this dataverse.");
                }
                DatasetVersion newDatasetVersion = dataset.getEditVersion();
                String foreignFormat = SwordUtil.DCTERMS;
                try {
                    importGenericService.importXML(deposit.getSwordEntry().toString(), foreignFormat, newDatasetVersion);
                } catch (Exception ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "problem calling importXML: " + ex);
                }
                swordService.addDatasetContact(newDatasetVersion, user);
                swordService.addDatasetDepositor(newDatasetVersion, user);
                swordService.addDatasetSubjectIfMissing(newDatasetVersion);
                swordService.setDatasetLicenseAndTermsOfUse(newDatasetVersion, deposit.getSwordEntry());
                Dataset createdDataset = null;
                try {
                    createdDataset = engineSvc.submit(createDatasetCommand);
                } catch (EJBException | CommandException ex) {
                    Throwable cause = ex;
                    StringBuilder sb = new StringBuilder();
                    sb.append(ex.getLocalizedMessage());
                    while (cause.getCause() != null) {
                        cause = cause.getCause();
                        /**
                         * @todo move this ConstraintViolationException
                         * check to CreateDatasetCommand. Can be triggered
                         * if you don't call dataset.setIdentifier() or if
                         * you feed it date format we don't like. Once this
                         * is done we should be able to drop EJBException
                         * from the catch above and only catch
                         * CommandException
                         *
                         * See also Have commands catch
                         * ConstraintViolationException and turn them into
                         * something that inherits from CommandException ·
                         * Issue #1009 · IQSS/dataverse -
                         * https://github.com/IQSS/dataverse/issues/1009
                         */
                        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.info(sb.toString());
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't create dataset: " + sb.toString());
                }
                if (createdDataset != null) {
                    ReceiptGenerator receiptGenerator = new ReceiptGenerator();
                    String baseUrl = urlManager.getHostnamePlusBaseUrlPath(collectionUri);
                    DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, createdDataset);
                    return depositReceipt;
                } else {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Problem creating dataset. Null returned.");
                }
            } else if (deposit.isBinaryOnly()) {
                // curl --insecure -s --data-binary "@example.zip" -H "Content-Disposition: filename=example.zip" -H "Content-Type: application/zip" https://sword:sword@localhost:8181/dvn/api/data-deposit/v1/swordv2/collection/dataverse/sword/
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Binary deposit to the collection IRI via POST is not supported. Please POST an Atom entry instead.");
            } else if (deposit.isMultipart()) {
                // "Yeah, multipart is critically broken across all implementations" -- http://www.mail-archive.com/sword-app-tech@lists.sourceforge.net/msg00327.html
                throw new UnsupportedOperationException("Not yet implemented");
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "expected deposit types are isEntryOnly, isBinaryOnly, and isMultiPart");
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataverse: " + dvAlias);
        }
    } else {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine target type or identifier from URL: " + collectionUri);
    }
}
Also used : SwordError(org.swordapp.server.SwordError) Dataset(edu.harvard.iq.dataverse.Dataset) CreateDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetCommand) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) SwordAuthException(org.swordapp.server.SwordAuthException) SwordServerException(org.swordapp.server.SwordServerException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) EJBException(javax.ejb.EJBException) ConstraintViolationException(javax.validation.ConstraintViolationException) ParseException(org.apache.abdera.parser.ParseException) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) DepositReceipt(org.swordapp.server.DepositReceipt) ConstraintViolation(javax.validation.ConstraintViolation) SwordEntry(org.swordapp.server.SwordEntry) ConstraintViolationException(javax.validation.ConstraintViolationException) ParseException(org.apache.abdera.parser.ParseException) EJBException(javax.ejb.EJBException)

Example 2 with SwordServerException

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

the class ContainerManagerImpl method replaceMetadata.

@Override
public DepositReceipt replaceMetadata(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
    logger.fine("replaceMetadata called with url: " + uri);
    urlManager.processUrl(uri);
    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, "Metadata replace of dataverse is not supported.");
        } else if ("study".equals(targetType)) {
            logger.fine("replacing metadata for dataset");
            // do a sanity check on the XML received
            try {
                SwordEntry swordEntry = deposit.getSwordEntry();
                logger.fine("deposit XML received by replaceMetadata():\n" + swordEntry);
            } catch (ParseException ex) {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Can not replace dataset metadata due to malformed Atom entry: " + ex);
            }
            String globalId = urlManager.getTargetIdentifier();
            Dataset dataset = datasetService.findByGlobalId(globalId);
            if (dataset != null) {
                Dataverse dvThatOwnsDataset = dataset.getOwner();
                UpdateDatasetCommand updateDatasetCommand = new UpdateDatasetCommand(dataset, dvReq);
                if (!permissionService.isUserAllowedOn(user, updateDatasetCommand, dataset)) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to modify dataverse " + dvThatOwnsDataset.getAlias());
                }
                DatasetVersion datasetVersion = dataset.getEditVersion();
                // erase all metadata before creating populating dataset version
                List<DatasetField> emptyDatasetFields = new ArrayList<>();
                datasetVersion.setDatasetFields(emptyDatasetFields);
                String foreignFormat = SwordUtil.DCTERMS;
                try {
                    importGenericService.importXML(deposit.getSwordEntry().toString(), foreignFormat, datasetVersion);
                } catch (Exception ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "problem calling importXML: " + ex);
                }
                swordService.addDatasetContact(datasetVersion, user);
                swordService.addDatasetDepositor(datasetVersion, user);
                swordService.addDatasetSubjectIfMissing(datasetVersion);
                swordService.setDatasetLicenseAndTermsOfUse(datasetVersion, deposit.getSwordEntry());
                try {
                    engineSvc.submit(updateDatasetCommand);
                } catch (CommandException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "problem updating dataset: " + ex);
                }
                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, "Could not find dataset based on global id (" + globalId + ") in URL: " + uri);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unknown target type specified on which to replace metadata: " + uri);
        }
    } else {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No target specified on which to replace metadata: " + uri);
    }
}
Also used : SwordError(org.swordapp.server.SwordError) Dataset(edu.harvard.iq.dataverse.Dataset) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) SwordAuthException(org.swordapp.server.SwordAuthException) SwordServerException(org.swordapp.server.SwordServerException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) EJBException(javax.ejb.EJBException) CommandExecutionException(edu.harvard.iq.dataverse.engine.command.exception.CommandExecutionException) ParseException(org.apache.abdera.parser.ParseException) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) DepositReceipt(org.swordapp.server.DepositReceipt) SwordEntry(org.swordapp.server.SwordEntry) ArrayList(java.util.ArrayList) List(java.util.List) ParseException(org.apache.abdera.parser.ParseException) UpdateDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand)

Example 3 with SwordServerException

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

the class MCRSwordContainerHandler method deleteObject.

public void deleteObject(MCRObject object) throws SwordServerException {
    try {
        object.getStructure().getDerivates().stream().map(MCRMetaLinkID::getXLinkHrefID).forEach(id -> {
            try {
                MCRMetadataManager.deleteMCRDerivate(id);
            } catch (Exception e) {
                throw new MCRException(e);
            }
        });
        MCRMetadataManager.delete(object);
    } catch (MCRActiveLinkException | MCRAccessException | MCRException e) {
        Throwable ex = e;
        if (e instanceof MCRException && Optional.ofNullable(e.getCause()).map(Object::getClass).filter(MCRAccessException.class::isAssignableFrom).isPresent()) {
            // unwrapp
            ex = e.getCause();
        }
        throw new SwordServerException("Error while deleting Object.", ex);
    }
}
Also used : MCRException(org.mycore.common.MCRException) MCRActiveLinkException(org.mycore.datamodel.common.MCRActiveLinkException) SwordServerException(org.swordapp.server.SwordServerException) MCRAccessException(org.mycore.access.MCRAccessException) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRException(org.mycore.common.MCRException) SwordServerException(org.swordapp.server.SwordServerException) MCRActiveLinkException(org.mycore.datamodel.common.MCRActiveLinkException) MCRAccessException(org.mycore.access.MCRAccessException)

Example 4 with SwordServerException

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

the class MCRSwordMediaHandler method addResource.

public void addResource(String derivateId, String requestFilePath, Deposit deposit) throws SwordError, SwordServerException {
    MCRPath ifsRootPath = MCRPath.getPath(derivateId, requestFilePath);
    final boolean pathIsDirectory = Files.isDirectory(ifsRootPath);
    final String depositFilename = deposit.getFilename();
    final String packaging = deposit.getPackaging();
    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!");
    }
    Path tempFile = null;
    try {
        try {
            tempFile = MCRSwordUtil.createTempFileFromStream(deposit.getFilename(), deposit.getInputStream(), deposit.getMd5());
        } catch (IOException e) {
            throw new SwordServerException("Could not store deposit to temp files", e);
        }
        if (packaging != null && packaging.equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) {
            if (pathIsDirectory && deposit.getMimeType().equals(MCRSwordConstants.MIME_TYPE_APPLICATION_ZIP)) {
                ifsRootPath = MCRPath.getPath(derivateId, requestFilePath);
                try {
                    List<MCRSwordUtil.MCRValidationResult> invalidResults = MCRSwordUtil.validateZipFile(this, tempFile).stream().filter(validationResult -> !validationResult.isValid()).collect(Collectors.toList());
                    if (invalidResults.size() > 0) {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST, invalidResults.stream().map(MCRSwordUtil.MCRValidationResult::getMessage).filter(Optional::isPresent).map(Optional::get).collect(Collectors.joining(System.lineSeparator())));
                    }
                    MCRSwordUtil.extractZipToPath(tempFile, ifsRootPath);
                } catch (IOException | NoSuchAlgorithmException | URISyntaxException e) {
                    throw new SwordServerException("Error while extracting ZIP.", e);
                }
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST, "The Request makes no sense. (mime type must be " + MCRSwordConstants.MIME_TYPE_APPLICATION_ZIP + " and path must be a directory)");
            }
        } else if (packaging != null && packaging.equals(UriRegistry.PACKAGE_BINARY)) {
            try {
                MCRSwordUtil.MCRValidationResult validationResult = validate(tempFile);
                if (!validationResult.isValid()) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST, validationResult.getMessage().get());
                }
                ifsRootPath = MCRPath.getPath(derivateId, requestFilePath + depositFilename);
                try (InputStream is = Files.newInputStream(tempFile)) {
                    Files.copy(is, ifsRootPath, StandardCopyOption.REPLACE_EXISTING);
                }
            } catch (IOException e) {
                throw new SwordServerException("Error while adding file " + ifsRootPath, e);
            }
        }
    } finally {
        if (tempFile != null) {
            try {
                LOGGER.info("Delete temp file: {}", tempFile);
                Files.delete(tempFile);
            } catch (IOException e) {
                LOGGER.error("Could not delete temp file: {}", tempFile, e);
            }
        }
    }
}
Also used : Path(java.nio.file.Path) MCRPath(org.mycore.datamodel.niofs.MCRPath) SwordError(org.swordapp.server.SwordError) URISyntaxException(java.net.URISyntaxException) ValidationException(org.mycore.mets.validator.validators.ValidationException) Deposit(org.swordapp.server.Deposit) UriRegistry(org.swordapp.server.UriRegistry) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) METSValidator(org.mycore.mets.validator.METSValidator) StandardCopyOption(java.nio.file.StandardCopyOption) MCRAccessManager(org.mycore.access.MCRAccessManager) MCRSwordUtil(org.mycore.sword.MCRSwordUtil) JDOMException(org.jdom2.JDOMException) Map(java.util.Map) SwordServerException(org.swordapp.server.SwordServerException) MCRAccessException(org.mycore.access.MCRAccessException) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) Files(java.nio.file.Files) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRSwordConstants(org.mycore.sword.MCRSwordConstants) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) MediaResource(org.swordapp.server.MediaResource) Collectors(java.util.stream.Collectors) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MCRSessionMgr(org.mycore.common.MCRSessionMgr) Optional(java.util.Optional) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) Optional(java.util.Optional) SwordError(org.swordapp.server.SwordError) InputStream(java.io.InputStream) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URISyntaxException(java.net.URISyntaxException) SwordServerException(org.swordapp.server.SwordServerException) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 5 with SwordServerException

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

the class MCRSwordMediaHandler method deleteMediaResource.

public void deleteMediaResource(String derivateId, String requestFilePath) throws SwordError, SwordServerException {
    if (!MCRAccessManager.checkPermission(derivateId, MCRAccessManager.PERMISSION_DELETE)) {
        throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "You dont have the right to delete (from) the derivate!");
    }
    if (requestFilePath == null || requestFilePath.equals("/")) {
        final MCRObjectID derivateID = MCRObjectID.getInstance(derivateId);
        if (MCRMetadataManager.exists(derivateID)) {
            final MCRDerivate mcrDerivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
            try {
                MCRMetadataManager.delete(mcrDerivate);
            } catch (MCRAccessException e) {
                throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, e);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND, "The requested Object '" + requestFilePath + "' does not exists.");
        }
    } else {
        final MCRPath path = MCRPath.getPath(derivateId, requestFilePath);
        checkFile(path);
        try {
            if (Files.isDirectory(path)) {
                Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.delete(file);
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            } else {
                Files.delete(path);
            }
        } catch (IOException e) {
            throw new SwordServerException("Error while deleting media resource!", e);
        }
    }
}
Also used : Path(java.nio.file.Path) MCRPath(org.mycore.datamodel.niofs.MCRPath) SwordServerException(org.swordapp.server.SwordServerException) SwordError(org.swordapp.server.SwordError) MCRAccessException(org.mycore.access.MCRAccessException) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) FileVisitResult(java.nio.file.FileVisitResult) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

SwordServerException (org.swordapp.server.SwordServerException)7 IOException (java.io.IOException)4 SwordError (org.swordapp.server.SwordError)4 MCRAccessException (org.mycore.access.MCRAccessException)3 Dataset (edu.harvard.iq.dataverse.Dataset)2 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)2 Dataverse (edu.harvard.iq.dataverse.Dataverse)2 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)2 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)2 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)2 FileVisitResult (java.nio.file.FileVisitResult)2 Path (java.nio.file.Path)2 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)2 List (java.util.List)2 EJBException (javax.ejb.EJBException)2 ParseException (org.apache.abdera.parser.ParseException)2 SolrQuery (org.apache.solr.client.solrj.SolrQuery)2 SolrServerException (org.apache.solr.client.solrj.SolrServerException)2 QueryResponse (org.apache.solr.client.solrj.response.QueryResponse)2 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)2