Search in sources :

Example 1 with ContentLibException

use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.

the class MetadatenImagesHelper method scaleFile.

/**
 * scale given image file to png using internal embedded content server
 *
 * @throws ImageManagerException
 * @throws IOException
 * @throws ImageManipulatorException
 */
public void scaleFile(String inFileName, String outFileName, int inSize, int intRotation) throws ContentLibException, IOException, ImageManipulatorException {
    ConfigurationHelper conf = ConfigurationHelper.getInstance();
    Path inPath = Paths.get(inFileName);
    URI s3URI = null;
    try {
        s3URI = new URI("s3://" + conf.getS3Bucket() + "/" + S3FileUtils.path2Key(inPath));
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        log.error(e);
    }
    log.trace("start scaleFile");
    int tmpSize = inSize;
    if (tmpSize < 1) {
        tmpSize = 1;
    }
    log.trace("Scale to " + tmpSize + "%");
    if (ConfigurationHelper.getInstance().getContentServerUrl() == null) {
        log.trace("api");
        ImageManager im = null;
        JpegInterpreter pi = null;
        try {
            im = conf.useS3() ? new ImageManager(s3URI) : new ImageManager(inPath.toUri());
            // im = new ImageManager(Paths.get(inFileName).toUri());
            log.trace("im");
            ImageInterpreter ii = im.getMyInterpreter();
            Dimension inputResolution = new Dimension((int) ii.getXResolution(), (int) ii.getYResolution());
            log.trace("input resolution: " + inputResolution.width + "x" + inputResolution.height + "dpi");
            Dimension outputResolution = new Dimension(144, 144);
            log.trace("output resolution: " + outputResolution.width + "x" + outputResolution.height + "dpi");
            Dimension dim = new Dimension(tmpSize * outputResolution.width / inputResolution.width, tmpSize * outputResolution.height / inputResolution.height);
            log.trace("Absolute scale: " + dim.width + "x" + dim.height + "%");
            RenderedImage ri = im.scaleImageByPixel(dim, ImageManager.SCALE_BY_PERCENT, intRotation);
            log.trace("ri");
            pi = new JpegInterpreter(ri);
            log.trace("pi");
            pi.setXResolution(outputResolution.width);
            log.trace("xres = " + pi.getXResolution());
            pi.setYResolution(outputResolution.height);
            log.trace("yres = " + pi.getYResolution());
            FileOutputStream outputFileStream = new FileOutputStream(outFileName);
            log.trace("output");
            pi.writeToStream(null, outputFileStream);
            log.trace("write stream");
            outputFileStream.close();
            log.trace("close stream");
        } finally {
            if (im != null) {
                im.close();
            }
            if (pi != null) {
                pi.close();
            }
        }
    } else {
        String imageURIString = conf.useS3() ? s3URI.toString() : inFileName;
        String cs = conf.getContentServerUrl() + imageURIString + "&scale=" + tmpSize + "&rotate=" + intRotation + "&format=jpg";
        cs = cs.replace("\\", "/");
        log.trace("url: " + cs);
        URL csUrl = new URL(cs);
        CloseableHttpClient httpclient = null;
        HttpGet method = null;
        InputStream istr = null;
        OutputStream fos = null;
        try {
            httpclient = HttpClientBuilder.create().build();
            method = new HttpGet(csUrl.toString());
            log.trace("get");
            Integer contentServerTimeOut = ConfigurationHelper.getInstance().getGoobiContentServerTimeOut();
            Builder builder = RequestConfig.custom();
            builder.setSocketTimeout(contentServerTimeOut);
            RequestConfig rc = builder.build();
            method.setConfig(rc);
            byte[] response = httpclient.execute(method, HttpClientHelper.byteArrayResponseHandler);
            if (response == null) {
                log.error("Response stream is null");
                return;
            }
            istr = new ByteArrayInputStream(response);
            fos = new FileOutputStream(outFileName);
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = istr.read(buf)) > 0) {
                fos.write(buf, 0, len);
            }
        } catch (Exception e) {
            log.error("Unable to connect to url " + cs, e);
            return;
        } finally {
            method.releaseConnection();
            if (httpclient != null) {
                httpclient.close();
            }
            if (istr != null) {
                try {
                    istr.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    }
}
Also used : Path(java.nio.file.Path) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Builder(org.apache.http.client.config.RequestConfig.Builder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ImageInterpreter(de.unigoettingen.sub.commons.contentlib.imagelib.ImageInterpreter) URISyntaxException(java.net.URISyntaxException) JpegInterpreter(de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter) Dimension(java.awt.Dimension) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) ContentLibException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) ImageManipulatorException(de.unigoettingen.sub.commons.contentlib.exceptions.ImageManipulatorException) ImageManagerException(de.unigoettingen.sub.commons.contentlib.exceptions.ImageManagerException) IOException(java.io.IOException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) InvalidImagesException(de.sub.goobi.helper.exceptions.InvalidImagesException) ContentFileNotLinkedException(ugh.exceptions.ContentFileNotLinkedException) ImageManager(de.unigoettingen.sub.commons.contentlib.imagelib.ImageManager) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) ConfigurationHelper(de.sub.goobi.config.ConfigurationHelper) RenderedImage(java.awt.image.RenderedImage)

Example 2 with ContentLibException

use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.

the class GoobiImageResource method getImageSize.

private Dimension getImageSize(String uri) {
    Dimension size = IMAGE_SIZES.get(uri);
    if (size == null) {
        try (ImageManager manager = new ImageManager(URI.create(uri))) {
            size = new Dimension(manager.getMyInterpreter().getOriginalImageWidth(), manager.getMyInterpreter().getOriginalImageHeight());
            setImageSize(uri, size);
        } catch (ContentLibException e) {
            log.error("Error retrieving image size of " + uri);
        } catch (FileNotFoundException e1) {
            log.error("Error retrieving image size of " + uri + ". Reason: url could not be resolved");
        }
    }
    return size;
}
Also used : ContentLibException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException) FileNotFoundException(java.io.FileNotFoundException) Dimension(java.awt.Dimension) ImageManager(de.unigoettingen.sub.commons.contentlib.imagelib.ImageManager)

Example 3 with ContentLibException

use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.

the class GoobiImageResource method createGoobiImageURI.

private URI createGoobiImageURI(HttpServletRequest request, Path processFolder, String folder, String filename) throws ContentLibException {
    try {
        this.imageFolder = getImagesFolder(processFolder, folder);
        Path imagePath = imageFolder.resolve(filename);
        this.thumbnailFolder = processFolder.resolve("thumbs");
        // replace image Path with thumbnail path if image file does not exist
        if (!Files.exists(imagePath) && hasThumbnailDirectories(imageFolder, thumbnailFolder)) {
            imagePath = getThumbnailPath(imagePath, thumbnailFolder, Optional.empty(), true).orElse(imagePath);
        }
        URI originalImageURI = Image.toURI(imagePath);
        Optional<Dimension> requestedImageSize = getRequestedImageSize(request);
        if (requestedImageSize.isPresent()) {
            // actual image request, no info.json
            boolean imageTooLarge = isFileTooLarge(imagePath);
            Dimension imageSize = getImageSize(originalImageURI.toString());
            if (!imageTooLarge) {
                int maxImageSize = ConfigurationHelper.getInstance().getMaximalImageSize();
                imageTooLarge = maxImageSize > 0 && Math.max(imageSize.getWidth(), imageSize.getHeight()) > maxImageSize;
            }
            Optional<Dimension> requestedRegionSize = getRequestedRegionSize(request);
            requestedImageSize = completeRequestedSize(requestedImageSize, requestedRegionSize, imageSize);
            if (hasThumbnailDirectories(imageFolder, thumbnailFolder)) {
                // requested image if the entire image were requested
                if (requestedImageSize.isPresent() && requestedRegionSize.isPresent()) {
                    double regionScaleW = requestedImageSize.get().getWidth() / requestedRegionSize.get().getWidth();
                    double regionScaleH = requestedImageSize.get().getHeight() / requestedRegionSize.get().getHeight();
                    requestedImageSize = Optional.of(new Dimension((int) Math.round(regionScaleW * imageSize.getWidth()), (int) Math.round(regionScaleH * imageSize.getHeight())));
                }
                // set the path of the thumbnail/image to use
                imagePath = getThumbnailPath(imagePath, thumbnailFolder, requestedImageSize, imageTooLarge).orElse(imagePath);
                // add an attribute to the request on how to scale the requested region to its
                // size on the original image
                Dimension size = requestedImageSize.orElse(null);
                getThumbnailSize(imagePath.getParent().getFileName().toString()).map(sizeString -> calcThumbnailScale(imageSize, sizeString, size, requestedRegionSize.isPresent())).ifPresent(scale -> setThumbnailScale(scale, request));
                log.debug("Using thumbnail {} for image width {} and region width {}", imagePath, requestedImageSize.map(Object::toString).orElse("max"), requestedRegionSize.map(Dimension::getWidth).map(Object::toString).orElse("full"));
            } else if (imageTooLarge) {
                // image too large for display and no thumbnails available
                throw new ContentLibException("Image size is larger than the allowed maximal size. Please consider using a compressed derivate or generating thumbnails for these images.");
            } else {
                // ignore thumbnail folder for this request
                this.thumbnailFolder = null;
            }
        } else {
        // info request
        }
        return Image.toURI(imagePath);
    } catch (NumberFormatException | NullPointerException e) {
        throw new ContentNotFoundException("No process found with id " + processFolder.getFileName().toString(), e);
    } catch (IOException | InterruptedException | SwapException | DAOException | ContentLibException e) {
        throw new ContentNotFoundException("Error initializing image resource for  " + processFolder.getFileName().toString() + ". Reason: " + e.getMessage(), e);
    }
}
Also used : Path(java.nio.file.Path) URLDecoder(java.net.URLDecoder) Produces(javax.ws.rs.Produces) URISyntaxException(java.net.URISyntaxException) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) MediaType(javax.ws.rs.core.MediaType) Matcher(java.util.regex.Matcher) ImageResource(de.unigoettingen.sub.commons.contentlib.servlet.rest.ImageResource) Map(java.util.Map) URI(java.net.URI) Path(java.nio.file.Path) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) Context(javax.ws.rs.core.Context) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ContentServerBinding(de.unigoettingen.sub.commons.contentlib.servlet.rest.ContentServerBinding) StreamingOutput(javax.ws.rs.core.StreamingOutput) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) ImageInformation(de.intranda.api.iiif.image.ImageInformation) Dimension(java.awt.Dimension) List(java.util.List) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) IllegalRequestException(de.unigoettingen.sub.commons.contentlib.exceptions.IllegalRequestException) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FilenameUtils(org.apache.commons.io.FilenameUtils) ContentLibException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ConfigurationHelper(de.sub.goobi.config.ConfigurationHelper) ContentServerPdfBinding(de.unigoettingen.sub.commons.contentlib.servlet.rest.ContentServerPdfBinding) ContentServerImageBinding(de.unigoettingen.sub.commons.contentlib.servlet.rest.ContentServerImageBinding) HttpServletRequest(javax.servlet.http.HttpServletRequest) ProcessManager(de.sub.goobi.persistence.managers.ProcessManager) Operation(io.swagger.v3.oas.annotations.Operation) ImageTile(de.intranda.api.iiif.image.ImageTile) StringUtils(spark.utils.StringUtils) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) Image(de.sub.goobi.metadaten.Image) Files(java.nio.file.Files) ImageManager(de.unigoettingen.sub.commons.contentlib.imagelib.ImageManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) PathConverter(de.unigoettingen.sub.commons.util.PathConverter) ContentServerImageInfoBinding(de.unigoettingen.sub.commons.contentlib.servlet.rest.ContentServerImageInfoBinding) StorageProvider(de.sub.goobi.helper.StorageProvider) ContentNotFoundException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentNotFoundException) URLEncoder(java.net.URLEncoder) Paths(java.nio.file.Paths) Log4j2(lombok.extern.log4j.Log4j2) Collections(java.util.Collections) ContentNotFoundException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentNotFoundException) SwapException(de.sub.goobi.helper.exceptions.SwapException) Dimension(java.awt.Dimension) IOException(java.io.IOException) URI(java.net.URI) DAOException(de.sub.goobi.helper.exceptions.DAOException) ContentLibException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException)

Example 4 with ContentLibException

use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.

the class AutomaticThumbnailHandler method generateThumbnailsFromDirectory.

private void generateThumbnailsFromDirectory(Process process, String imageDirectory, int[] sizes, String command) throws SwapException, DAOException, ContentLibException {
    try {
        File[] fileList = new File(imageDirectory).listFiles();
        for (int size : sizes) {
            String thumbnailDirectory = process.getThumbsDirectory() + Paths.get(imageDirectory).getFileName().toString() + "_" + String.valueOf(size);
            File outputDirectory = new File(thumbnailDirectory);
            if (outputDirectory.exists()) {
                if (!checkIfChanged(outputDirectory, fileList)) {
                    return;
                }
            } else {
                outputDirectory.mkdirs();
            }
            Scale scale = new Scale.ScaleToBox(new Dimension(size, size));
            for (File img : fileList) {
                if (img.isDirectory()) {
                    continue;
                }
                String basename = FilenameUtils.getBaseName(img.toString());
                OutputStream out = new FileOutputStream(thumbnailDirectory + FileSystems.getDefault().getSeparator() + basename + "_" + size + ".jpg");
                // remove spaces from url
                ImageRequest request = new ImageRequest(new URI(img.getAbsolutePath().replace(" ", "%20")), RegionRequest.FULL, scale, Rotation.NONE, Colortype.DEFAULT, ImageFileFormat.JPG, Map.of("ignoreWatermark", "true"));
                new GetImageAction().writeImage(request, out);
            }
        }
    } catch (Exception e) {
        log.error(e);
    }
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Scale(de.unigoettingen.sub.commons.contentlib.imagelib.transform.Scale) Dimension(java.awt.Dimension) URI(java.net.URI) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) IOException(java.io.IOException) ContentLibException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException) FileOutputStream(java.io.FileOutputStream) ImageRequest(de.unigoettingen.sub.commons.contentlib.servlet.model.ImageRequest) GetImageAction(de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction) File(java.io.File)

Aggregations

ContentLibException (de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException)4 Dimension (java.awt.Dimension)4 DAOException (de.sub.goobi.helper.exceptions.DAOException)3 SwapException (de.sub.goobi.helper.exceptions.SwapException)3 ImageManager (de.unigoettingen.sub.commons.contentlib.imagelib.ImageManager)3 IOException (java.io.IOException)3 URI (java.net.URI)3 ConfigurationHelper (de.sub.goobi.config.ConfigurationHelper)2 FileNotFoundException (java.io.FileNotFoundException)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2 URISyntaxException (java.net.URISyntaxException)2 Path (java.nio.file.Path)2 ImageInformation (de.intranda.api.iiif.image.ImageInformation)1 ImageTile (de.intranda.api.iiif.image.ImageTile)1 StorageProvider (de.sub.goobi.helper.StorageProvider)1 InvalidImagesException (de.sub.goobi.helper.exceptions.InvalidImagesException)1 Image (de.sub.goobi.metadaten.Image)1 ProcessManager (de.sub.goobi.persistence.managers.ProcessManager)1 ContentNotFoundException (de.unigoettingen.sub.commons.contentlib.exceptions.ContentNotFoundException)1