Search in sources :

Example 16 with MCRAccessException

use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.

the class MCRObjectCommands method mergeDerivatesOfObject.

@MCRCommand(syntax = "merge derivates of object {0}", help = "Retrieves the MCRObject with the MCRObjectID {0} and if it has more then one MCRDerivate, then all" + " Files will be copied to the first Derivate and all other will be deleted.", order = 190)
public static void mergeDerivatesOfObject(String id) {
    MCRObjectID objectID = MCRObjectID.getInstance(id);
    if (!MCRMetadataManager.exists(objectID)) {
        LOGGER.error("The object with the id {} does not exist!", id);
        return;
    }
    MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
    List<MCRMetaLinkID> derivateLinkIDs = object.getStructure().getDerivates();
    List<MCRObjectID> derivateIDs = derivateLinkIDs.stream().map(MCRMetaLinkID::getXLinkHrefID).collect(Collectors.toList());
    if (derivateIDs.size() <= 1) {
        LOGGER.error("The object with the id {} has no Derivates to merge!", id);
        return;
    }
    String mainID = derivateIDs.get(0).toString();
    MCRPath mainDerivateRootPath = MCRPath.getPath(mainID, "/");
    derivateIDs.stream().skip(1).forEach(derivateID -> {
        LOGGER.info("Merge {} into {}...", derivateID, mainID);
        MCRPath copyRootPath = MCRPath.getPath(derivateID.toString(), "/");
        try {
            MCRTreeCopier treeCopier = new MCRTreeCopier(copyRootPath, mainDerivateRootPath);
            Files.walkFileTree(copyRootPath, treeCopier);
            Files.walkFileTree(copyRootPath, MCRRecursiveDeleter.instance());
            MCRMetadataManager.deleteMCRDerivate(derivateID);
        } catch (IOException | MCRAccessException e) {
            throw new MCRException(e);
        }
    });
}
Also used : MCRTreeCopier(org.mycore.datamodel.niofs.utils.MCRTreeCopier) MCRException(org.mycore.common.MCRException) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRAccessException(org.mycore.access.MCRAccessException) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 17 with MCRAccessException

use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.

the class MCRObjectCommands method replaceParent.

/**
 * Moves object to new parent.
 *
 * @param sourceId
 *            object that should be attached to new parent
 * @param newParentId
 *            the ID of the new parent
 * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)}
 */
@MCRCommand(syntax = "set parent of {0} to {1}", help = "replaces a parent of an object (first parameter) to the given new one (second parameter)", order = 300)
public static void replaceParent(String sourceId, String newParentId) throws MCRPersistenceException, MCRActiveLinkException, MCRAccessException {
    // child
    MCRObject sourceMCRObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(sourceId));
    // old parent
    MCRObjectID oldParentId = sourceMCRObject.getStructure().getParentID();
    MCRObjectID newParentObjectID = MCRObjectID.getInstance(newParentId);
    if (newParentObjectID.equals(oldParentId)) {
        LOGGER.info("Object {} is already child of {}", sourceId, newParentId);
        return;
    }
    MCRObject oldParentMCRObject = null;
    if (oldParentId != null) {
        try {
            oldParentMCRObject = MCRMetadataManager.retrieveMCRObject(oldParentId);
        } catch (Exception exc) {
            LOGGER.error("Unable to get old parent object {}, its probably deleted.", oldParentId, exc);
        }
    }
    // change href to new parent
    LOGGER.info("Setting link in \"{}\" to parent \"{}\"", sourceId, newParentObjectID);
    MCRMetaLinkID parentLinkId = new MCRMetaLinkID("parent", 0);
    parentLinkId.setReference(newParentObjectID, null, null);
    sourceMCRObject.getStructure().setParent(parentLinkId);
    if (oldParentMCRObject != null) {
        // remove Child in old parent
        LOGGER.info("Remove child \"{}\" in old parent \"{}\"", sourceId, oldParentId);
        oldParentMCRObject.getStructure().removeChild(sourceMCRObject.getId());
        LOGGER.info("Update old parent \"{}\n", oldParentId);
        MCRMetadataManager.update(oldParentMCRObject);
    }
    LOGGER.info("Update \"{}\" in datastore (saving new link)", sourceId);
    MCRMetadataManager.update(sourceMCRObject);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Structure: {}", sourceMCRObject.getStructure().isValid());
        LOGGER.debug("Object: {}", sourceMCRObject.isValid());
    }
}
Also used : MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) URISyntaxException(java.net.URISyntaxException) JDOMException(org.jdom2.JDOMException) MCRPersistenceException(org.mycore.common.MCRPersistenceException) SAXException(org.xml.sax.SAXException) MCRActiveLinkException(org.mycore.datamodel.common.MCRActiveLinkException) TransformerException(javax.xml.transform.TransformerException) MCRException(org.mycore.common.MCRException) MCRAccessException(org.mycore.access.MCRAccessException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 18 with MCRAccessException

use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.

the class MCRUploadHandlerIFS method receiveFile.

@Override
public synchronized long receiveFile(String path, InputStream in, long length, String checksum) throws IOException, MCRPersistenceException, MCRAccessException {
    LOGGER.debug("incoming receiveFile request: {} {} {} bytes", path, checksum, length);
    this.setProgressText(path);
    List<Path> tempFiles = new LinkedList<>();
    Supplier<Path> tempFileSupplier = () -> {
        try {
            Path tempFile = Files.createTempFile(derivateID + "-" + path.hashCode(), ".upload");
            tempFiles.add(tempFile);
            return tempFile;
        } catch (IOException e) {
            throw new UncheckedIOException("Error while creating temp File!", e);
        }
    };
    try (InputStream fIn = preprocessInputStream(path, in, length, tempFileSupplier)) {
        if (rootDir == null) {
            // MCR-1376: Create derivate only if at least one file was successfully uploaded
            prepareUpload();
        }
        MCRPath file = getFile(path);
        LOGGER.info("Creating file {}.", file);
        Files.copy(fIn, file, StandardCopyOption.REPLACE_EXISTING);
        return tempFiles.isEmpty() ? length : Files.size(tempFiles.stream().reduce((a, b) -> b).get());
    } finally {
        tempFiles.stream().filter(Files::exists).forEach((tempFilePath) -> {
            try {
                Files.delete(tempFilePath);
            } catch (IOException e) {
                LOGGER.error("Could not delete temp file {}", tempFilePath);
            }
        });
        this.filesUploaded++;
        int progress = (int) (((float) this.filesUploaded / (float) getNumFiles()) * 100f);
        this.setProgress(progress);
    }
}
Also used : Path(java.nio.file.Path) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRConfiguration(org.mycore.common.config.MCRConfiguration) MCRFileAttributes(org.mycore.datamodel.niofs.MCRFileAttributes) Constructor(java.lang.reflect.Constructor) Supplier(java.util.function.Supplier) MCRConfigurationException(org.mycore.common.config.MCRConfigurationException) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) StandardCopyOption(java.nio.file.StandardCopyOption) MCRAccessManager(org.mycore.access.MCRAccessManager) DirectoryStream(java.nio.file.DirectoryStream) MCRMetaIFS(org.mycore.datamodel.metadata.MCRMetaIFS) LinkedList(java.util.LinkedList) MCRAccessException(org.mycore.access.MCRAccessException) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRObjectDerivate(org.mycore.datamodel.metadata.MCRObjectDerivate) Files(java.nio.file.Files) MCRPath(org.mycore.datamodel.niofs.MCRPath) Collection(java.util.Collection) MCRPersistenceException(org.mycore.common.MCRPersistenceException) FileSystemException(java.nio.file.FileSystemException) IOException(java.io.IOException) MCRAccessInterface(org.mycore.access.MCRAccessInterface) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRProcessableStatus(org.mycore.common.processing.MCRProcessableStatus) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) InputStream(java.io.InputStream) InputStream(java.io.InputStream) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) MCRPath(org.mycore.datamodel.niofs.MCRPath) LinkedList(java.util.LinkedList)

Example 19 with MCRAccessException

use of org.mycore.access.MCRAccessException 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)

Example 20 with MCRAccessException

use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.

the class MCRIIIFImageResource method getImage.

@GET
@Path("{" + IDENTIFIER_PARAM + "}/{region}/{size}/{rotation}/{quality}.{format}")
public Response getImage(@PathParam(IMPL_PARAM) String implStr, @PathParam(IDENTIFIER_PARAM) String identifier, @PathParam("region") String region, @PathParam("size") String size, @PathParam("rotation") String rotation, @PathParam("quality") String quality, @PathParam("format") String format) {
    try {
        MCRIIIFImageImpl impl = getImpl(implStr);
        MCRIIIFImageInformation information = impl.getInformation(identifier);
        MCRIIIFRegionParser rp = new MCRIIIFRegionParser(region, information.width, information.height);
        MCRIIIFImageSourceRegion sourceRegion = rp.parseImageRegion();
        MCRIIIFScaleParser sp = new MCRIIIFScaleParser(size, sourceRegion.getX2() - sourceRegion.getX1(), sourceRegion.getY2() - sourceRegion.getY1());
        MCRIIIFImageTargetSize targetSize = sp.parseTargetScale();
        MCRIIIFRotationParser rotationParser = new MCRIIIFRotationParser(rotation);
        MCRIIIFImageTargetRotation parsedRotation = rotationParser.parse();
        MCRIIIFImageQuality imageQuality = MCRIIIFImageQuality.fromString(quality);
        BufferedImage provide = impl.provide(identifier, sourceRegion, targetSize, parsedRotation, imageQuality, format);
        Response.Status status = rp.isCompleteValid() ? Response.Status.OK : Response.Status.BAD_REQUEST;
        Response.ResponseBuilder responseBuilder = Response.status(status);
        return responseBuilder.header("Link", buildCanonicalURL(impl, identifier)).header("Profile", buildProfileURL()).type("image/" + format).entity((StreamingOutput) outputStream -> ImageIO.write(provide, format, outputStream)).build();
    } catch (MCRIIIFImageNotFoundException e) {
        return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
    } catch (IllegalArgumentException | MCRIIIFUnsupportedFormatException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
    } catch (MCRAccessException e) {
        return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
    } catch (Exception e) {
        LOGGER.error(() -> "Error while getting Image " + identifier + " from " + implStr + " with region: " + region + ", size: " + size + ", rotation: " + rotation + ", quality: " + quality + ", format: " + format, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
}
Also used : MCRIIIFImageTargetRotation(org.mycore.iiif.image.model.MCRIIIFImageTargetRotation) MCRIIIFImageInformation(org.mycore.iiif.image.model.MCRIIIFImageInformation) MCRAccessException(org.mycore.access.MCRAccessException) MCRIIIFImageQuality(org.mycore.iiif.image.model.MCRIIIFImageQuality) StreamingOutput(javax.ws.rs.core.StreamingOutput) MCRIIIFUnsupportedFormatException(org.mycore.iiif.image.impl.MCRIIIFUnsupportedFormatException) BufferedImage(java.awt.image.BufferedImage) URISyntaxException(java.net.URISyntaxException) MCRIIIFImageProvidingException(org.mycore.iiif.image.impl.MCRIIIFImageProvidingException) MCRAccessException(org.mycore.access.MCRAccessException) MCRIIIFUnsupportedFormatException(org.mycore.iiif.image.impl.MCRIIIFUnsupportedFormatException) MCRIIIFImageNotFoundException(org.mycore.iiif.image.impl.MCRIIIFImageNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(javax.ws.rs.core.Response) MCRIIIFImageNotFoundException(org.mycore.iiif.image.impl.MCRIIIFImageNotFoundException) MCRIIIFImageTargetSize(org.mycore.iiif.image.model.MCRIIIFImageTargetSize) MCRIIIFImageSourceRegion(org.mycore.iiif.image.model.MCRIIIFImageSourceRegion) MCRIIIFRotationParser(org.mycore.iiif.image.parser.MCRIIIFRotationParser) MCRIIIFRegionParser(org.mycore.iiif.image.parser.MCRIIIFRegionParser) MCRIIIFScaleParser(org.mycore.iiif.image.parser.MCRIIIFScaleParser) MCRIIIFImageImpl(org.mycore.iiif.image.impl.MCRIIIFImageImpl) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

MCRAccessException (org.mycore.access.MCRAccessException)23 MCRPersistenceException (org.mycore.common.MCRPersistenceException)12 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)12 IOException (java.io.IOException)11 MCRException (org.mycore.common.MCRException)9 MCRActiveLinkException (org.mycore.datamodel.common.MCRActiveLinkException)9 MCRPath (org.mycore.datamodel.niofs.MCRPath)7 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)6 MCRObject (org.mycore.datamodel.metadata.MCRObject)6 Path (java.nio.file.Path)4 JDOMException (org.jdom2.JDOMException)4 MCRMetaLinkID (org.mycore.datamodel.metadata.MCRMetaLinkID)4 SAXException (org.xml.sax.SAXException)4 List (java.util.List)3 Stream (java.util.stream.Stream)3 MCRPersistentIdentifierException (org.mycore.pi.exceptions.MCRPersistentIdentifierException)3 SignedJWT (com.nimbusds.jwt.SignedJWT)2 File (java.io.File)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 URISyntaxException (java.net.URISyntaxException)2