Search in sources :

Example 1 with ImageOpException

use of digilib.image.ImageOpException in project digilib by robcast.

the class ServletOps method sendFile.

/**
 * Transfers an image file as-is with the mime type mt.
 *
 * The local file is copied to the <code>OutputStream</code> of the
 * <code>ServletResponse</code>. If mt is null then the mime-type is
 * auto-detected with mimeForFile.
 *
 * @param f
 *            Image file to be sent.
 * @param mt
 *            mime-type of the file.
 * @param name
 *            name of the download file (for application/x)
 * @param res
 *            ServletResponse where the image file will be sent.
 * @param logger
 *            Logger to use
 * @throws ImageOpException
 * @throws ServletException Exception on sending data.
 * @throws IOException
 */
public static void sendFile(File f, String mt, String name, HttpServletResponse response, Logger logger) throws ImageOpException, IOException {
    logger.debug("sendRawFile(" + mt + ", " + f + ")");
    if (response == null) {
        logger.error("No response!");
        return;
    }
    /*
         * set content-type
         */
    if (mt == null) {
        // auto-detect mime-type
        mt = FileOps.mimeForFile(f);
        if (mt == null) {
            throw new ImageOpException("Unknown file type.");
        }
    }
    if (!mt.isEmpty()) {
        response.setContentType(mt);
    }
    /*
         * set content-disposition with filename unless name="".
         */
    if (name == null) {
        // no download name -- use filename
        name = f.getName();
    }
    if (!name.isEmpty()) {
        if (mt.startsWith("application")) {
            response.addHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
        } else {
            response.addHeader("Content-Disposition", "inline; filename=\"" + name + "\"");
        }
    }
    /*
         * set CORS header ACAO "*" for image or info response
         */
    if (corsForImageRequests && !mt.isEmpty()) {
        // TODO: would be nice to check request for Origin header
        response.setHeader("Access-Control-Allow-Origin", "*");
    }
    /*
         * open file
         */
    FileInputStream inFile = null;
    try {
        inFile = new FileInputStream(f);
        OutputStream outStream = response.getOutputStream();
        // TODO: should we set content length?
        // see http://www.prozesse-und-systeme.de/servletFlush.html
        response.setContentLength((int) f.length());
        byte[] dataBuffer = new byte[4096];
        int len;
        /*
             * write file to stream
             */
        while ((len = inFile.read(dataBuffer)) != -1) {
            // copy out file
            outStream.write(dataBuffer, 0, len);
        }
    } finally {
        try {
            if (inFile != null) {
                inFile.close();
            }
        } catch (IOException e) {
        // nothing to do
        }
    }
}
Also used : ImageOpException(digilib.image.ImageOpException) OutputStream(java.io.OutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 2 with ImageOpException

use of digilib.image.ImageOpException in project digilib by robcast.

the class ScalerNoThread method processRequest.

/**
 * Service this request using the response.
 *
 * @param request
 * @param response
 * @throws ServletException
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    if (dlConfig == null) {
        logger.error("ERROR: No Configuration!");
        throw new ServletException("NO VALID digilib CONFIGURATION!");
    }
    accountlog.debug("request: " + request.getQueryString());
    logger.debug("request: " + request.getQueryString());
    long startTime = System.currentTimeMillis();
    // parse request
    DigilibServletRequest dlRequest = new DigilibServletRequest(request, dlConfig);
    // type of error reporting
    ErrMsg errMsgType = ErrMsg.IMAGE;
    if (dlRequest.hasOption(DigilibOption.errtxt)) {
        errMsgType = ErrMsg.TEXT;
    } else if (dlRequest.hasOption(DigilibOption.errcode)) {
        errMsgType = ErrMsg.CODE;
    }
    try {
        // extract the job information
        ImageJobDescription jobTicket = ImageJobDescription.getInstance(dlRequest, dlConfig);
        /*
             * check if we can fast-track without scaling
             */
        ImageInput fileToLoad = (ImageInput) jobTicket.getInput();
        // check permissions
        if (useAuthorization) {
            // is the current request/user authorized?
            if (!authzOp.isAuthorized(dlRequest)) {
                // send deny answer and abort
                throw new AuthOpException();
            }
        }
        // if requested, send image as a file
        if (sendFileAllowed && jobTicket.getSendAsFile()) {
            String mt = null;
            if (jobTicket.hasOption(DigilibOption.rawfile)) {
                mt = "application/octet-stream";
            }
            logger.debug("Sending RAW File as is.");
            ServletOps.sendFile(fileToLoad.getFile(), mt, null, response, logger);
            logger.info("Done in " + (System.currentTimeMillis() - startTime) + "ms");
            return;
        }
        // it
        if (!jobTicket.isTransformRequired()) {
            logger.debug("Sending File as is.");
            ServletOps.sendFile(fileToLoad.getFile(), null, null, response, logger);
            logger.info("Done in " + (System.currentTimeMillis() - startTime) + "ms");
            return;
        }
        // create job
        ImageWorker job = new ImageWorker(dlConfig, jobTicket);
        // get result immediately
        DocuImage img = job.call();
        // forced destination image type
        String mt = null;
        if (jobTicket.hasOption(DigilibOption.jpg)) {
            mt = "image/jpeg";
        } else if (jobTicket.hasOption(DigilibOption.png)) {
            mt = "image/png";
        }
        // send image
        ServletOps.sendImage(img, mt, response, logger);
        logger.debug("Job Processing Time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (ImageOpException e) {
        logger.error(e.getClass() + ": " + e.getMessage());
        digilibError(errMsgType, Error.IMAGE, null, response);
    } catch (IOException e) {
        logger.error(e.getClass() + ": " + e.getMessage());
        digilibError(errMsgType, Error.FILE, null, response);
    } catch (AuthOpException e) {
        logger.error(e.getClass() + ": " + e.getMessage());
        digilibError(errMsgType, Error.AUTH, null, response);
    }
}
Also used : ServletException(javax.servlet.ServletException) ImageOpException(digilib.image.ImageOpException) DigilibServletRequest(digilib.conf.DigilibServletRequest) ImageJobDescription(digilib.image.ImageJobDescription) ImageInput(digilib.io.ImageInput) AuthOpException(digilib.auth.AuthOpException) ImageWorker(digilib.image.ImageWorker) DocuImage(digilib.image.DocuImage) IOException(java.io.IOException)

Example 3 with ImageOpException

use of digilib.image.ImageOpException in project digilib by robcast.

the class AsyncServletWorker method run.

/**
 * runs the ImageWorker and writes the image to the ServletResponse.
 */
@Override
public void run() {
    try {
        /*
             * render the image
             */
        DocuImage img = imageWorker.call();
        if (completed) {
            logger.debug("AsyncServletWorker already completed (after scaling)!");
            return;
        }
        /*
             * set forced destination image type
             */
        String mt = null;
        if (jobinfo.hasOption(DigilibOption.jpg)) {
            mt = "image/jpeg";
        } else if (jobinfo.hasOption(DigilibOption.png)) {
            mt = "image/png";
        }
        /*
             *  send the image
             */
        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
        ServletOps.sendImage(img, mt, response, logger);
        logger.debug("Job done in: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (ImageOpException e) {
        logger.error(e.getClass() + ": " + e.getMessage());
        Scaler.digilibError(errMsgType, Error.IMAGE, null, (HttpServletResponse) asyncContext.getResponse());
    } catch (IOException e) {
        logger.error(e.getClass() + ": " + e.getMessage());
        Scaler.digilibError(errMsgType, Error.FILE, null, (HttpServletResponse) asyncContext.getResponse());
    } catch (ServletException e) {
        logger.error("Servlet error: ", e);
    } catch (Exception e) {
        logger.error("Other error: ", e);
    } finally {
        if (completed) {
            logger.debug("AsyncServletWorker already completed (finally)!");
        } else {
            // submit response
            logger.debug("context complete.");
            completed = true;
            asyncContext.complete();
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) ImageOpException(digilib.image.ImageOpException) DocuImage(digilib.image.DocuImage) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ImageOpException(digilib.image.ImageOpException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 4 with ImageOpException

use of digilib.image.ImageOpException in project digilib by robcast.

the class Manifester method processRequest.

protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
    try {
        // create DigilibRequest from ServletRequest, omit IIIF Image API parsing
        DigilibServletRequest dlRequest = new DigilibServletRequest(request, dlConfig, EnumSet.of(ParsingOption.omitIiifImageApi));
        // get list of IIIF parameters
        @SuppressWarnings("unchecked") List<String> iiifParams = (List<String>) dlRequest.getValue("request.iiif.elements");
        if (iiifParams == null) {
            logger.error("Invalid IIIF request.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid IIIF request.");
            return;
        }
        // get identifier (first parameter)
        // allow empty identifier for image root dir
        String identifier = "";
        if (iiifParams.size() > 0) {
            identifier = iiifParams.get(0);
        }
        // decode identifier to file path
        dlRequest.setValueFromString("fn", dlRequest.decodeIiifIdentifier(identifier));
        // get directory path
        String dlFn = dlRequest.getFilePath();
        // get information about the directory
        DocuDirectory dlDir = dirCache.getDirectory(dlFn);
        if (dlDir == null) {
            logger.error("Directory for manifest not found: " + dlFn);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // check for existing manifest file
        File mfFile = new File(dlDir.getDir(), "manifest.json");
        // check for image files
        if ((dlDir.size() == 0) && !mfFile.canRead()) {
            logger.debug("Directory has no files: " + dlFn);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        ManifestParams params = new ManifestParams();
        /*
			 * set CORS header ACAO "*" for info response as per IIIF spec
			 */
        if (corsForInfoRequests) {
            String origin = request.getHeader("Origin");
            if (origin != null) {
                response.setHeader("Access-Control-Allow-Origin", "*");
            }
        }
        /*
             * check permissions
             */
        if (useAuthorization) {
            // is the current request/user authorized?
            if (!authzOp.isAuthorized(dlRequest)) {
                // send deny answer and abort
                throw new AuthOpException("Access denied!");
            }
        }
        // use JSON-LD content type only when asked
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/ld+json")) {
            response.setContentType("application/ld+json");
        } else {
            response.setContentType("application/json");
        }
        if (mfFile.canRead()) {
            // send manifest file
            ServletOps.sendFile(mfFile, "", "", response);
            return;
        }
        // check for manifest-meta.json file with additional metadata
        File mfMetaFile = new File(dlDir.getDir(), "manifest-meta.json");
        if (mfMetaFile.canRead()) {
            params.mfMetaFile = mfMetaFile;
        }
        /*
			 * configure base URLs for manifest
			 */
        params.imgApiUrl = dlConfig.getAsString("iiif-image-base-url");
        String manifestBaseUrl = dlConfig.getAsString("iiif-manifest-base-url");
        if ("".equals(params.imgApiUrl) || "".equals(manifestBaseUrl)) {
            // try to figure out base URLs
            String servletBaseUrl = dlConfig.getAsString("webapp-base-url");
            if ("".equals(servletBaseUrl)) {
                String url = request.getRequestURL().toString();
                // get base URL for web application by last occurrence of Servlet path
                int srvPathLen = url.lastIndexOf(request.getServletPath());
                servletBaseUrl = url.substring(0, srvPathLen);
            }
            // manifest base URL
            manifestBaseUrl = servletBaseUrl + request.getServletPath() + "/" + dlConfig.getAsString("iiif-prefix");
            // Image API base URL
            params.imgApiUrl = servletBaseUrl + "/" + this.scalerServletPath + "/" + dlConfig.getAsString("iiif-prefix");
        }
        // full manifest URL with identifier
        params.manifestUrl = manifestBaseUrl + "/" + identifier;
        params.identifier = identifier;
        params.docuDir = dlDir;
        /*
			 * start json representation
			 */
        ServletOutputStream out = response.getOutputStream();
        JsonGenerator manifest = Json.createGenerator(out).writeStartObject();
        /*
			 * manifest metadata
			 */
        writeManifestMeta(manifest, dlFn, params);
        /*
			 * sequences
			 */
        writeSequences(manifest, params);
        // manifest
        manifest.writeEnd();
        manifest.close();
    } catch (IOException e) {
        logger.error("ERROR sending manifest: ", e);
    } catch (ImageOpException e) {
        logger.error("ERROR sending manifest: ", e);
    } catch (AuthOpException e) {
        logger.debug("Permission denied.");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            logger.error("Error sending error: ", e);
        }
    }
}
Also used : ImageOpException(digilib.image.ImageOpException) DigilibServletRequest(digilib.conf.DigilibServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) IOException(java.io.IOException) AuthOpException(digilib.auth.AuthOpException) DocuDirectory(digilib.io.DocuDirectory) JsonGenerator(javax.json.stream.JsonGenerator) List(java.util.List) File(java.io.File)

Example 5 with ImageOpException

use of digilib.image.ImageOpException in project digilib by robcast.

the class PDFStreamWorker method addTitlePage.

/**
 * Create a title page and append it to the document (should, of course, be
 * called first)
 *
 * @throws DocumentException
 */
public Document addTitlePage(Document doc) throws DocumentException {
    PDFTitlePage titlepage = new PDFTitlePage(job_info);
    try {
        doc.add(titlepage.getPageContents());
    } catch (IOException e) {
        throw new DocumentException(e);
    } catch (ImageOpException e) {
        throw new DocumentException(e);
    }
    doc.newPage();
    return doc;
}
Also used : ImageOpException(digilib.image.ImageOpException) DocumentException(com.itextpdf.text.DocumentException) IOException(java.io.IOException)

Aggregations

ImageOpException (digilib.image.ImageOpException)7 IOException (java.io.IOException)7 AuthOpException (digilib.auth.AuthOpException)3 DigilibServletRequest (digilib.conf.DigilibServletRequest)3 ServletException (javax.servlet.ServletException)3 DocuImage (digilib.image.DocuImage)2 ImageJobDescription (digilib.image.ImageJobDescription)2 ImageInput (digilib.io.ImageInput)2 File (java.io.File)2 ServletOutputStream (javax.servlet.ServletOutputStream)2 DocumentException (com.itextpdf.text.DocumentException)1 ImageWorker (digilib.image.ImageWorker)1 DocuDirectory (digilib.io.DocuDirectory)1 FileOpException (digilib.io.FileOpException)1 FileInputStream (java.io.FileInputStream)1 OutputStream (java.io.OutputStream)1 List (java.util.List)1 JsonGenerator (javax.json.stream.JsonGenerator)1 AsyncContext (javax.servlet.AsyncContext)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1