Search in sources :

Example 46 with MCRPath

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

the class MCRMETSServlet method doGetPost.

@Override
protected void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest request = job.getRequest();
    HttpServletResponse response = job.getResponse();
    LOGGER.info(request.getPathInfo());
    String derivate = getOwnerID(request.getPathInfo());
    MCRPath rootPath = MCRPath.getPath(derivate, "/");
    if (!Files.isDirectory(rootPath)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, MessageFormat.format("Derivate {0} does not exist.", derivate));
        return;
    }
    request.setAttribute("XSL.derivateID", derivate);
    Collection<String> linkList = MCRLinkTableManager.instance().getSourceOf(derivate);
    if (linkList.isEmpty()) {
        MCRDerivate derivate2 = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivate));
        MCRObjectID ownerID = derivate2.getOwnerID();
        if (ownerID != null && ownerID.toString().length() != 0) {
            linkList.add(ownerID.toString());
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, MessageFormat.format("Derivate {0} is not linked with a MCRObject. Please contact an administrator.", derivate));
            return;
        }
    }
    request.setAttribute("XSL.objectID", linkList.iterator().next());
    response.setContentType("text/xml");
    long lastModified = Files.getLastModifiedTime(rootPath).toMillis();
    MCRFrontendUtil.writeCacheHeaders(response, (long) CACHE_TIME, lastModified, useExpire);
    long start = System.currentTimeMillis();
    MCRContent metsContent = getMetsSource(job, useExistingMets(request), derivate);
    MCRLayoutService.instance().doLayout(request, response, metsContent);
    LOGGER.info("Generation of code by {} took {} ms", this.getClass().getSimpleName(), System.currentTimeMillis() - start);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRContent(org.mycore.common.content.MCRContent)

Example 47 with MCRPath

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

the class MCRIView2Commands method forAllImages.

private static List<String> forAllImages(String derivateID, String batchCommandSyntax) throws IOException {
    if (!MCRIView2Tools.isDerivateSupported(derivateID)) {
        LOGGER.info("Skipping tiling of derivate {} as it's main file is not supported by IView2.", derivateID);
        return null;
    }
    MCRPath derivateRoot = MCRPath.getPath(derivateID, "/");
    if (!Files.exists(derivateRoot)) {
        throw new MCRException("Derivate " + derivateID + " does not exist or is not a directory!");
    }
    List<MCRPath> supportedFiles = getSupportedFiles(derivateRoot);
    return supportedFiles.stream().map(image -> MessageFormat.format(batchCommandSyntax, derivateID, image.getOwnerRelativePath())).collect(Collectors.toList());
}
Also used : MCRIView2Tools(org.mycore.iview2.services.MCRIView2Tools) Enumeration(java.util.Enumeration) TypedQuery(javax.persistence.TypedQuery) MCRException(org.mycore.common.MCRException) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) MCRRecursiveDeleter(org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter) DirectoryStream(java.nio.file.DirectoryStream) JDOMException(org.jdom2.JDOMException) MCRImage(org.mycore.imagetiler.MCRImage) MCRTileJob(org.mycore.iview2.services.MCRTileJob) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRTiledPictureProps(org.mycore.imagetiler.MCRTiledPictureProps) ZipFile(java.util.zip.ZipFile) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRTilingQueue(org.mycore.iview2.services.MCRTilingQueue) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage) Files(java.nio.file.Files) MCRAbstractCommands(org.mycore.frontend.cli.MCRAbstractCommands) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRImageTiler(org.mycore.iview2.services.MCRImageTiler) IOException(java.io.IOException) EntityManager(javax.persistence.EntityManager) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) CRC32(java.util.zip.CRC32) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) MCRException(org.mycore.common.MCRException) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 48 with MCRPath

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

the class MCRIView2Commands method fixDeadEntries.

@MCRCommand(syntax = "fix dead tile jobs", help = "Deletes entries for files which dont exist anymore!")
public static void fixDeadEntries() {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class);
    List<MCRTileJob> tiles = allTileJobQuery.getResultList();
    tiles.stream().filter(tj -> {
        MCRPath path = MCRPath.getPath(tj.getDerivate(), tj.getPath());
        return !Files.exists(path);
    }).peek(tj -> LOGGER.info("Delete TileJob {}:{}", tj.getDerivate(), tj.getPath())).forEach(em::remove);
}
Also used : MCRIView2Tools(org.mycore.iview2.services.MCRIView2Tools) Enumeration(java.util.Enumeration) TypedQuery(javax.persistence.TypedQuery) MCRException(org.mycore.common.MCRException) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) MCRRecursiveDeleter(org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter) DirectoryStream(java.nio.file.DirectoryStream) JDOMException(org.jdom2.JDOMException) MCRImage(org.mycore.imagetiler.MCRImage) MCRTileJob(org.mycore.iview2.services.MCRTileJob) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRTiledPictureProps(org.mycore.imagetiler.MCRTiledPictureProps) ZipFile(java.util.zip.ZipFile) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRTilingQueue(org.mycore.iview2.services.MCRTilingQueue) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage) Files(java.nio.file.Files) MCRAbstractCommands(org.mycore.frontend.cli.MCRAbstractCommands) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRImageTiler(org.mycore.iview2.services.MCRImageTiler) IOException(java.io.IOException) EntityManager(javax.persistence.EntityManager) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) CRC32(java.util.zip.CRC32) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) EntityManager(javax.persistence.EntityManager) FileSystem(java.nio.file.FileSystem) MCRTileJob(org.mycore.iview2.services.MCRTileJob) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 49 with MCRPath

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

the class MCRPDFThumbnailServlet method getContent.

/* (non-Javadoc)
     * @see org.mycore.frontend.servlets.MCRContentServlet#getContent(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
@Override
public MCRContent getContent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        ThumnailInfo thumbnailInfo = getThumbnailInfo(req.getPathInfo());
        MCRPath pdfFile = MCRPath.getPath(thumbnailInfo.derivate, thumbnailInfo.filePath);
        LOGGER.info("PDF file: {}", pdfFile);
        if (Files.notExists(pdfFile)) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, MessageFormat.format("Could not find pdf file for {0}{1}", thumbnailInfo.derivate, thumbnailInfo.filePath));
            return null;
        }
        String centerThumb = req.getParameter("centerThumb");
        String imgSize = req.getParameter("ts");
        // defaults to "yes"
        boolean centered = !"no".equals(centerThumb);
        int thumbnailSize = imgSize == null ? this.thumbnailSize : Integer.parseInt(imgSize);
        BasicFileAttributes attrs = Files.readAttributes(pdfFile, BasicFileAttributes.class);
        MCRContent imageContent = pdfTools.getThumnail(pdfFile, attrs, thumbnailSize, centered);
        if (imageContent != null) {
            resp.setHeader("Cache-Control", "max-age=" + MAX_AGE);
            Date expires = new Date(System.currentTimeMillis() + MAX_AGE * 1000);
            LOGGER.debug("Last-Modified: {}, expire on: {}", new Date(attrs.lastModifiedTime().toMillis()), expires);
            resp.setDateHeader("Expires", expires.getTime());
        }
        return imageContent;
    } finally {
        LOGGER.debug("Finished sending {}", req.getPathInfo());
    }
}
Also used : MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRContent(org.mycore.common.content.MCRContent) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Date(java.util.Date)

Example 50 with MCRPath

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

the class MCRThumbnailResource method getThumbnail.

private Response getThumbnail(String documentId, int size, String ext) {
    List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(MCRJerseyUtil.getID(documentId), 1, TimeUnit.MINUTES);
    for (MCRObjectID derivateId : derivateIds) {
        if (MCRAccessManager.checkPermissionForReadingDerivate(derivateId.toString())) {
            String nameOfMainFile = MCRMetadataManager.retrieveMCRDerivate(derivateId).getDerivate().getInternals().getMainDoc();
            if (nameOfMainFile != null && !nameOfMainFile.equals("")) {
                MCRPath mainFile = MCRPath.getPath(derivateId.toString(), '/' + nameOfMainFile);
                try {
                    String mimeType = Files.probeContentType(mainFile);
                    String generators = MCRConfiguration.instance().getString("MCR.Media.Thumbnail.Generators");
                    for (String generator : generators.split(",")) {
                        Class<MCRThumbnailGenerator> classObject = (Class<MCRThumbnailGenerator>) Class.forName(generator);
                        Constructor<MCRThumbnailGenerator> constructor = classObject.getConstructor();
                        MCRThumbnailGenerator thumbnailGenerator = constructor.newInstance();
                        if (thumbnailGenerator.matchesFileType(mimeType, mainFile)) {
                            FileTime lastModified = Files.getLastModifiedTime(mainFile);
                            Date lastModifiedDate = new Date(lastModified.toMillis());
                            Response.ResponseBuilder resp = request.evaluatePreconditions(lastModifiedDate);
                            if (resp == null) {
                                Optional<BufferedImage> thumbnail = thumbnailGenerator.getThumbnail(mainFile, size);
                                if (thumbnail.isPresent()) {
                                    CacheControl cc = new CacheControl();
                                    cc.setMaxAge((int) TimeUnit.DAYS.toSeconds(1));
                                    String type = "image/png";
                                    if ("jpg".equals(ext) || "jpeg".equals(ext)) {
                                        type = "image/jpeg";
                                    }
                                    return Response.ok(thumbnail.get()).cacheControl(cc).lastModified(lastModifiedDate).type(type).build();
                                }
                                return Response.status(Response.Status.NOT_FOUND).build();
                            }
                            return resp.build();
                        }
                    }
                } catch (IOException | ReflectiveOperationException e) {
                    throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
                }
            }
        }
    }
    return Response.status(Response.Status.NOT_FOUND).build();
}
Also used : MCRThumbnailGenerator(org.mycore.media.services.MCRThumbnailGenerator) WebApplicationException(javax.ws.rs.WebApplicationException) FileTime(java.nio.file.attribute.FileTime) IOException(java.io.IOException) Date(java.util.Date) BufferedImage(java.awt.image.BufferedImage) Response(javax.ws.rs.core.Response) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) CacheControl(javax.ws.rs.core.CacheControl) MCRPath(org.mycore.datamodel.niofs.MCRPath)

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