Search in sources :

Example 16 with SwordError

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

the class SwordServiceBean method setDatasetLicenseAndTermsOfUse.

/**
 * The rules (from https://github.com/IQSS/dataverse/issues/805 ) are below.
 *
 * If you don't provide `<dcterms:license>` the license should be set to
 * "CC0" on dataset creation.
 *
 * If you don't provide `<dcterms:license>` the license on dataset
 * modification, the license should not change.
 *
 * To provide `<dcterms:rights>` you much either omit `<dcterms:license>`
 * (for backwards compatibility since `<dcterms:license>` was not a required
 * field for SWORD in DVN 3.6) or set `<dcterms:license>` to "NONE".
 *
 * It is invalid to provide "CC0" under `<dcterms:license>` in combination
 * with any value under `<dcterms:rights>`.
 *
 * It is invalid to attempt to change the license to "CC0" if Terms of Use
 * (`<dcterms:rights>`) is already on file.
 *
 * Both `<dcterms:rights>` and `<dcterms:license>` can only be specified
 * once. Multiples are not allowed.
 *
 * Blank values are not allowed for `<dcterms:license>` (since it's new) but
 * for backwards compatibility, blank values are allowed for
 * `<dcterms:rights>` per
 * https://github.com/IQSS/dataverse/issues/805#issuecomment-71670396
 *
 * @todo What about the "native" API? Are similar rules enforced? See also
 * https://github.com/IQSS/dataverse/issues/1385
 */
public void setDatasetLicenseAndTermsOfUse(DatasetVersion datasetVersionToMutate, SwordEntry swordEntry) throws SwordError {
    Map<String, List<String>> dcterms = swordEntry.getDublinCore();
    List<String> listOfLicensesProvided = dcterms.get("license");
    TermsOfUseAndAccess terms = new TermsOfUseAndAccess();
    datasetVersionToMutate.setTermsOfUseAndAccess(terms);
    if (listOfLicensesProvided == null) {
        TermsOfUseAndAccess.License existingLicense = datasetVersionToMutate.getTermsOfUseAndAccess().getLicense();
        if (existingLicense != null) {
            // leave the license alone but set terms of use
            setTermsOfUse(datasetVersionToMutate, dcterms, existingLicense);
        } else {
            TermsOfUseAndAccess.License unspecifiedLicense = TermsOfUseAndAccess.defaultLicense;
            List<String> listOfRights = dcterms.get("rights");
            if (listOfRights != null) {
                int numRightsProvided = listOfRights.size();
                if (numRightsProvided != 1) {
                    throw new SwordError("Only one Terms of Use (dcterms:rights) can be provided per dataset, not " + numRightsProvided);
                } else {
                    // Set to NONE for backwards combatibility. We didn't require a license for SWORD in DVN 3.x.
                    unspecifiedLicense = TermsOfUseAndAccess.License.NONE;
                }
            }
            terms.setLicense(existingLicense);
            terms.setLicense(unspecifiedLicense);
            setTermsOfUse(datasetVersionToMutate, dcterms, unspecifiedLicense);
        }
        return;
    }
    int numLicensesProvided = listOfLicensesProvided.size();
    if (numLicensesProvided != 1) {
        throw new SwordError("Only one license can be provided per dataset, not " + numLicensesProvided + ".");
    }
    String licenseProvided = listOfLicensesProvided.get(0);
    if (StringUtils.isBlank(licenseProvided)) {
        throw new SwordError("License provided was blank.");
    }
    TermsOfUseAndAccess.License licenseToSet;
    try {
        licenseToSet = TermsOfUseAndAccess.License.valueOf(licenseProvided);
    } catch (IllegalArgumentException ex) {
        throw new SwordError("License provided was \"" + licenseProvided + "\" but one " + Arrays.toString(DatasetVersion.License.values()) + " was expected.");
    }
    terms.setLicense(licenseToSet);
    setTermsOfUse(datasetVersionToMutate, dcterms, licenseToSet);
}
Also used : SwordError(org.swordapp.server.SwordError) List(java.util.List) TermsOfUseAndAccess(edu.harvard.iq.dataverse.TermsOfUseAndAccess)

Example 17 with SwordError

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

the class UrlManager method getHostnamePlusBaseUrlPath.

String getHostnamePlusBaseUrlPath(String url) throws SwordError {
    String optionalPort = "";
    URI u;
    try {
        u = new URI(url);
    } catch (URISyntaxException ex) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "unable to part URL");
    }
    int port = u.getPort();
    if (port != -1) {
        // https often runs on port 8181 in dev
        optionalPort = ":" + port;
    }
    String requestedHostname = u.getHost();
    String hostName = System.getProperty(SystemConfig.FQDN);
    if (hostName == null) {
        hostName = "localhost";
    }
    /**
     * @todo should this be configurable? In dev it's convenient to override
     * the JVM option and force traffic to localhost.
     */
    if (requestedHostname.equals("localhost")) {
        hostName = "localhost";
    }
    /**
     * @todo Any problem with returning the current API version rather than
     * the version that was operated on? Both should work. If SWORD API
     * users are operating on the URLs returned (as they should) returning
     * the current version will avoid deprecation warnings on the Dataverse
     * side.
     *
     * @todo Prevent "https://localhost:8080" from being returned. It should
     * either be "http://localhost:8080" or "https://localhost:8181". Use
     * SystemConfig.getDataverseSiteUrl instead of SystemConfig.FQDN above.
     * It's worse for security to not have https hard coded here but if
     * users have configured dataverse.siteUrl to be http rather than https
     * we assume they are doing this on purpose (despite our warnings in the
     * Installation Guide), perhaps because they are only kicking the tires
     * on Dataverse.
     */
    return "https://" + hostName + optionalPort + swordConfiguration.getBaseUrlPathCurrent();
}
Also used : SwordError(org.swordapp.server.SwordError) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 18 with SwordError

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

the class SwordUtil method throwRegularSwordErrorWithoutStackTrace.

/*
     * @todo get rid of this method
     */
public static SwordError throwRegularSwordErrorWithoutStackTrace(String error) {
    if (error == null) {
        error = "UNKNOWN";
    }
    SwordError swordError = new SwordError(error);
    StackTraceElement[] emptyStackTrace = new StackTraceElement[0];
    swordError.setStackTrace(emptyStackTrace);
    return swordError;
}
Also used : SwordError(org.swordapp.server.SwordError)

Example 19 with SwordError

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

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

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