Search in sources :

Example 71 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath 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 72 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRSolrIndexEventHandler method addFile.

protected synchronized void addFile(Path path, BasicFileAttributes attrs) {
    if (path instanceof MCRPath) {
        // check if the derivate is marked for deletion
        MCRPath mcrPath = (MCRPath) path;
        String owner = mcrPath.getOwner();
        if (MCRObjectID.isValid(owner)) {
            MCRObjectID mcrObjectID = MCRObjectID.getInstance(owner);
            if (MCRMarkManager.instance().isMarkedForDeletion(mcrObjectID)) {
                return;
            }
        }
    }
    MCRSessionMgr.getCurrentSession().onCommit(() -> {
        try {
            MCRSolrIndexer.submitIndexHandler(MCRSolrIndexHandlerFactory.getInstance().getIndexHandler(path, attrs, MCRSolrClientFactory.getSolrClient()), MCRSolrIndexer.HIGH_PRIORITY);
        } catch (Exception ex) {
            LOGGER.error("Error creating transfer thread for file {}", path, ex);
        }
    });
}
Also used : MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 73 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRSolrFilesIndexHandler method indexDerivate.

protected void indexDerivate(MCRObjectID derivateID) throws IOException {
    MCRPath rootPath = MCRPath.getPath(derivateID.toString(), "/");
    final MCRSolrIndexHandlerFactory ihf = MCRSolrIndexHandlerFactory.getInstance();
    final List<MCRSolrIndexHandler> subHandlerList = this.subHandlerList;
    final List<SolrInputDocument> docs = new ArrayList<>();
    final SolrClient solrClient = this.solrClient;
    Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            boolean sendContent = ihf.checkFile(file, attrs);
            try {
                if (sendContent) {
                    subHandlerList.add(ihf.getIndexHandler(file, attrs, solrClient, true));
                } else {
                    SolrInputDocument fileDoc = MCRSolrPathDocumentFactory.getInstance().getDocument(file, attrs);
                    docs.add(fileDoc);
                }
            } catch (Exception ex) {
                LOGGER.error("Error creating transfer thread", ex);
            }
            return super.visitFile(file, attrs);
        }
    });
    int fileCount = subHandlerList.size() + docs.size();
    LOGGER.info("Sending {} file(s) for derivate \"{}\"", fileCount, derivateID);
    if (!docs.isEmpty()) {
        MCRSolrInputDocumentsHandler subHandler = new MCRSolrInputDocumentsHandler(docs, solrClient);
        subHandler.setCommitWithin(getCommitWithin());
        this.subHandlerList.add(subHandler);
    }
}
Also used : MCRPath(org.mycore.datamodel.niofs.MCRPath) Path(java.nio.file.Path) MCRSolrInputDocumentsHandler(org.mycore.solr.index.handlers.document.MCRSolrInputDocumentsHandler) ArrayList(java.util.ArrayList) MCRSolrIndexHandler(org.mycore.solr.index.MCRSolrIndexHandler) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) IOException(java.io.IOException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) SolrInputDocument(org.apache.solr.common.SolrInputDocument) MCRSolrIndexHandlerFactory(org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory) SolrClient(org.apache.solr.client.solrj.SolrClient) MCRPath(org.mycore.datamodel.niofs.MCRPath) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 74 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRSwordUtil method createDerivate.

public static MCRDerivate createDerivate(String documentID) throws MCRPersistenceException, IOException, MCRAccessException {
    final String projectId = MCRObjectID.getInstance(documentID).getProjectId();
    MCRObjectID oid = MCRObjectID.getNextFreeId(projectId, "derivate");
    final String derivateID = oid.toString();
    MCRDerivate derivate = new MCRDerivate();
    derivate.setId(oid);
    derivate.setLabel("data object from " + documentID);
    String schema = CONFIG.getString("MCR.Metadata.Config.derivate", "datamodel-derivate.xml").replaceAll(".xml", ".xsd");
    derivate.setSchema(schema);
    MCRMetaLinkID linkId = new MCRMetaLinkID();
    linkId.setSubTag("linkmeta");
    linkId.setReference(documentID, null, null);
    derivate.getDerivate().setLinkMeta(linkId);
    MCRMetaIFS ifs = new MCRMetaIFS();
    ifs.setSubTag("internal");
    ifs.setSourcePath(null);
    derivate.getDerivate().setInternals(ifs);
    LOGGER.debug("Creating new derivate with ID {}", derivateID);
    MCRMetadataManager.create(derivate);
    if (CONFIG.getBoolean("MCR.Access.AddDerivateDefaultRule", true)) {
        MCRAccessInterface AI = MCRAccessManager.getAccessImpl();
        Collection<String> configuredPermissions = AI.getAccessPermissionsFromConfiguration();
        for (String permission : configuredPermissions) {
            MCRAccessManager.addRule(derivateID, permission, MCRAccessManager.getTrueRule(), "default derivate rule");
        }
    }
    final MCRPath rootDir = MCRPath.getPath(derivateID, "/");
    if (Files.notExists(rootDir)) {
        rootDir.getFileSystem().createRoot(derivateID);
    }
    return derivate;
}
Also used : MCRAccessInterface(org.mycore.access.MCRAccessInterface) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRMetaIFS(org.mycore.datamodel.metadata.MCRMetaIFS) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 75 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRSwordUtil method extractZipToPath.

public static void extractZipToPath(Path zipFilePath, MCRPath target) throws SwordError, IOException, NoSuchAlgorithmException, URISyntaxException {
    LOGGER.info("Extracting zip: {}", zipFilePath);
    try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFilePath.toUri()), new HashMap<>())) {
        final Path sourcePath = zipfs.getPath("/");
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                final Path relativeSP = sourcePath.relativize(dir);
                // WORKAROUND for bug
                Path targetdir = relativeSP.getNameCount() == 0 ? target : target.resolve(relativeSP);
                try {
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                MCRSession currentSession = MCRSessionMgr.getCurrentSession();
                LOGGER.info("Extracting: {}", file);
                Path targetFilePath = target.resolve(sourcePath.relativize(file));
                // and before completion we start the transaction to let niofs write the md5 to the table
                try (SeekableByteChannel destinationChannel = Files.newByteChannel(targetFilePath, StandardOpenOption.WRITE, StandardOpenOption.SYNC, StandardOpenOption.CREATE);
                    SeekableByteChannel sourceChannel = Files.newByteChannel(file, StandardOpenOption.READ)) {
                    if (currentSession.isTransactionActive()) {
                        currentSession.commitTransaction();
                    }
                    ByteBuffer buffer = ByteBuffer.allocateDirect(COPY_BUFFER_SIZE);
                    while (sourceChannel.read(buffer) != -1 || buffer.position() > 0) {
                        buffer.flip();
                        destinationChannel.write(buffer);
                        buffer.compact();
                    }
                } finally {
                    if (!currentSession.isTransactionActive()) {
                        currentSession.beginTransaction();
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
}
Also used : Path(java.nio.file.Path) MCRPath(org.mycore.datamodel.niofs.MCRPath) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) SeekableByteChannel(java.nio.channels.SeekableByteChannel) MCRSession(org.mycore.common.MCRSession) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

MCRPath (org.mycore.datamodel.niofs.MCRPath)96 IOException (java.io.IOException)49 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)26 Path (java.nio.file.Path)25 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)22 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)22 Document (org.jdom2.Document)15 JDOMException (org.jdom2.JDOMException)15 MCRPersistenceException (org.mycore.common.MCRPersistenceException)14 MCRException (org.mycore.common.MCRException)13 MCRDirectory (org.mycore.datamodel.ifs.MCRDirectory)13 MCRAccessException (org.mycore.access.MCRAccessException)12 Files (java.nio.file.Files)11 Collectors (java.util.stream.Collectors)11 LogManager (org.apache.logging.log4j.LogManager)11 Logger (org.apache.logging.log4j.Logger)11 FileVisitResult (java.nio.file.FileVisitResult)10 NoSuchFileException (java.nio.file.NoSuchFileException)10 Date (java.util.Date)10 List (java.util.List)10