Search in sources :

Example 1 with OutOfRangeException

use of cz.incad.kramerius.pdf.OutOfRangeException in project kramerius by ceskaexpedice.

the class AbstractPDFResource method parent.

public File parent(String pid, int n, Rectangle rect, FirstPage fp) throws DocumentException, IOException, NumberFormatException, ProcessSubtreeException {
    FontMap fmap = new FontMap(deprectedService.fontsFolder());
    Map<String, AbstractObjectPath[]> pathsMap = solrAccess.getModelAndPidPaths(pid);
    ObjectPidsPath[] paths = (ObjectPidsPath[]) pathsMap.get(ObjectPidsPath.class.getName());
    final ObjectPidsPath path = AbstractPDFResource.selectOnePath(pid, paths);
    File parentFile = null;
    File firstPageFile = null;
    try {
        PreparedDocument rdoc = this.documentService.buildDocumentAsFlat(path, pid, n, new int[] { (int) rect.getWidth(), (int) rect.getHeight() });
        checkRenderedPDFDoc(rdoc);
        this.mostDesirable.saveAccess(pid, new Date());
        for (AbstractPage p : rdoc.getPages()) {
            reportAccess(p.getUuid());
        }
        parentFile = File.createTempFile("body", "pdf");
        FileOutputStream bodyTmpFos = new FileOutputStream(parentFile);
        firstPageFile = File.createTempFile("head", "pdf");
        FileOutputStream fpageFos = new FileOutputStream(firstPageFile);
        if (fp == FirstPage.IMAGES) {
            this.imageFirstPage.parent(rdoc, fpageFos, path, fmap);
        } else {
            this.textFirstPage.parent(rdoc, fpageFos, path, fmap);
        }
        this.simplePdfService.pdf(rdoc, bodyTmpFos, fmap);
        File generatedPDF = File.createTempFile("rendered", "pdf");
        FileOutputStream fos = new FileOutputStream(generatedPDF);
        AbstractPDFResource.mergeToOutput(fos, parentFile, firstPageFile);
        return generatedPDF;
    } catch (OutOfRangeException e) {
        throw new PDFResourceBadRequestException(e.getMessage());
    } finally {
        saveDeleteFile(parentFile, firstPageFile);
    }
}
Also used : AbstractPage(cz.incad.kramerius.document.model.AbstractPage) FileOutputStream(java.io.FileOutputStream) PreparedDocument(cz.incad.kramerius.document.model.PreparedDocument) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) ObjectPidsPath(cz.incad.kramerius.ObjectPidsPath) File(java.io.File) Date(java.util.Date) FontMap(cz.incad.kramerius.pdf.utils.pdf.FontMap)

Example 2 with OutOfRangeException

use of cz.incad.kramerius.pdf.OutOfRangeException in project kramerius by ceskaexpedice.

the class PDFResource method selection.

/**
 * Generate pdf from selection
 * @param pidsParam List of pids
 * @param pageType First page type. Possible values TEXT, IMAGE
 * @param format Page format. Possible values : A0,...A5, B0,...B5, LETTER, POSTCARD
 * @return
 * @throws OutOfRangeException
 */
@GET
@Path("selection")
@Produces({ "application/pdf", "application/json" })
public Response selection(@QueryParam("pids") String pidsParam, @QueryParam("firstPageType") @DefaultValue("TEXT") String pageType, @QueryParam("format") String format) throws OutOfRangeException {
    boolean acquired = false;
    try {
        acquired = PDFExlusiveGenerateSupport.PDF_SEMAPHORE.tryAcquire();
        if (acquired) {
            try {
                AbstractPDFResource.FirstPage fp = pageType != null ? AbstractPDFResource.FirstPage.valueOf(pageType) : AbstractPDFResource.FirstPage.TEXT;
                if (StringUtils.isAnyString(pidsParam)) {
                    String[] pids = pidsParam.split(",");
                    // max number test
                    ConfigurationUtils.checkNumber(pids);
                    Rectangle formatRect = formatRect(format);
                    final File generatedPDF = super.selection(pids, formatRect, fp);
                    final InputStream fis = new FileInputStream(generatedPDF);
                    StreamingOutput stream = new StreamingOutput() {

                        public void write(OutputStream output) throws IOException, WebApplicationException {
                            try {
                                IOUtils.copyStreams(fis, output);
                            } catch (Exception e) {
                                throw new WebApplicationException(e);
                            } finally {
                                if (generatedPDF != null)
                                    generatedPDF.delete();
                            }
                        }
                    };
                    SimpleDateFormat sdate = new SimpleDateFormat("yyyyMMdd_mmhhss");
                    return Response.ok().header("Content-disposition", "attachment; filename=" + sdate.format(new Date()) + ".pdf").entity(stream).type("application/pdf").build();
                } else {
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }
            } catch (MalformedURLException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (ProcessSubtreeException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (DocumentException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (SecurityException e) {
                LOGGER.log(Level.INFO, e.getMessage());
                throw new ActionNotAllowed(e.getMessage());
            }
        } else {
            throw new PDFResourceNotReadyException("not ready");
        }
    } finally {
        if (acquired)
            PDFExlusiveGenerateSupport.PDF_SEMAPHORE.release();
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) WebApplicationException(javax.ws.rs.WebApplicationException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Rectangle(com.lowagie.text.Rectangle) StreamingOutput(javax.ws.rs.core.StreamingOutput) SecurityException(cz.incad.kramerius.security.SecurityException) IOException(java.io.IOException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) ActionNotAllowed(cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed) FileInputStream(java.io.FileInputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) JSONException(org.json.JSONException) SecurityException(cz.incad.kramerius.security.SecurityException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) FileNotFoundException(java.io.FileNotFoundException) WebApplicationException(javax.ws.rs.WebApplicationException) MalformedURLException(java.net.MalformedURLException) BadRequestException(cz.incad.kramerius.rest.api.exceptions.BadRequestException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) Date(java.util.Date) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) DocumentException(com.lowagie.text.DocumentException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 3 with OutOfRangeException

use of cz.incad.kramerius.pdf.OutOfRangeException in project kramerius by ceskaexpedice.

the class PDFResource method parent.

/**
 * Generate whole document
 * @param pid PID of generating document
 * @param number Number of pages (whole document or maximum number of pages)
 * @param pageType Type of firt page. Possible values: TEXT,IMAGE
 * @param format Page format. Possible values : A0,...A5, B0,...B5, LETTER, POSTCARD
 * @return
 */
@GET
@Path("parent")
@Produces({ "application/pdf", "application/json" })
public Response parent(@QueryParam("pid") String pid, @QueryParam("number") String number, @QueryParam("firstPageType") @DefaultValue("TEXT") String pageType, @QueryParam("format") String format) {
    boolean acquired = false;
    try {
        acquired = PDFExlusiveGenerateSupport.PDF_SEMAPHORE.tryAcquire();
        if (acquired) {
            try {
                AbstractPDFResource.FirstPage fp = pageType != null ? AbstractPDFResource.FirstPage.valueOf(pageType) : AbstractPDFResource.FirstPage.TEXT;
                // max number test
                int n = ConfigurationUtils.checkNumber(number);
                Rectangle formatRect = formatRect(format);
                final File generatedPdf = super.parent(pid, n, formatRect, fp);
                final InputStream fis = new FileInputStream(generatedPdf);
                StreamingOutput stream = new StreamingOutput() {

                    public void write(OutputStream output) throws IOException, WebApplicationException {
                        try {
                            IOUtils.copyStreams(fis, output);
                        } catch (Exception e) {
                            throw new WebApplicationException(e);
                        } finally {
                            if (generatedPdf != null)
                                generatedPdf.delete();
                        }
                    }
                };
                SimpleDateFormat sdate = new SimpleDateFormat("yyyyMMdd_mmhhss");
                return Response.ok().header("Content-disposition", "attachment; filename=" + sdate.format(new Date()) + ".pdf").entity(stream).type("application/pdf").build();
            } catch (NumberFormatException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (FileNotFoundException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (DocumentException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (ProcessSubtreeException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (OutOfRangeException e1) {
                LOGGER.log(Level.WARNING, "too much pages for pdf generating - consider changing config attribute (generatePdfMaxRange)");
                throw new PDFResourceBadRequestException(e1.getMessage());
            } catch (SecurityException e1) {
                LOGGER.log(Level.INFO, e1.getMessage());
                throw new ActionNotAllowed(e1.getMessage());
            }
        } else {
            throw new PDFResourceNotReadyException("not ready");
        }
    } finally {
        if (acquired)
            PDFExlusiveGenerateSupport.PDF_SEMAPHORE.release();
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Rectangle(com.lowagie.text.Rectangle) FileNotFoundException(java.io.FileNotFoundException) StreamingOutput(javax.ws.rs.core.StreamingOutput) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) DocumentException(com.lowagie.text.DocumentException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SecurityException(cz.incad.kramerius.security.SecurityException) IOException(java.io.IOException) ActionNotAllowed(cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed) FileInputStream(java.io.FileInputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) JSONException(org.json.JSONException) SecurityException(cz.incad.kramerius.security.SecurityException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) FileNotFoundException(java.io.FileNotFoundException) WebApplicationException(javax.ws.rs.WebApplicationException) MalformedURLException(java.net.MalformedURLException) BadRequestException(cz.incad.kramerius.rest.api.exceptions.BadRequestException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) Date(java.util.Date) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 4 with OutOfRangeException

use of cz.incad.kramerius.pdf.OutOfRangeException in project kramerius by ceskaexpedice.

the class DocumentServiceTest2 method testDocumentService_turnOffPdfCheckFalse.

// Cely dokumennt - turnOffPdfCheck = false
@Test
public void testDocumentService_turnOffPdfCheckFalse() throws IOException, ParserConfigurationException, SAXException, LexerException, ProcessSubtreeException, SecurityException, NoSuchMethodException, OutOfRangeException {
    Injector injector = _DocumentServiceTestPrepare.prepareInjector("2", false);
    DocumentService docService = injector.getInstance(DocumentService.class);
    try {
        PreparedDocument doc = docService.buildDocumentAsFlat(DocumentServiceTest.PATHS_MAPPING.get(DataPrepare.DROBNUSTKY_PIDS[0]), DataPrepare.DROBNUSTKY_PIDS[0], 20, new int[] { 300, 300 });
        Assert.fail();
    } catch (OutOfRangeException e) {
    // ok
    }
}
Also used : Injector(com.google.inject.Injector) PreparedDocument(cz.incad.kramerius.document.model.PreparedDocument) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) Test(org.junit.Test)

Example 5 with OutOfRangeException

use of cz.incad.kramerius.pdf.OutOfRangeException in project kramerius by ceskaexpedice.

the class AbstractPDFResource method extractNumberOfPages.

// replaces ConfigurationUtils.checkNumber(string)
int extractNumberOfPages(String numberOfPagesStr) throws OutOfRangeException {
    Configuration config = KConfiguration.getInstance().getConfiguration();
    boolean ignoreMaxRange = config.getBoolean("turnOffPdfCheck");
    int maxRange = config.getInt("generatePdfMaxRange");
    if (numberOfPagesStr == null || numberOfPagesStr.trim().isEmpty()) {
        // numberOfPages not specified
        return ignoreMaxRange ? Integer.MAX_VALUE : maxRange;
    }
    // numberOfPages specified
    int numberOfPages = Integer.valueOf(numberOfPagesStr);
    if (!ignoreMaxRange && numberOfPages > maxRange) {
        throw new OutOfRangeException(String.format("too many pages (requested: %d, max: %d)", numberOfPages, maxRange));
    }
    return numberOfPages;
}
Also used : Configuration(org.apache.commons.configuration.Configuration) KConfiguration(cz.incad.kramerius.utils.conf.KConfiguration) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException)

Aggregations

OutOfRangeException (cz.incad.kramerius.pdf.OutOfRangeException)10 Date (java.util.Date)6 PreparedDocument (cz.incad.kramerius.document.model.PreparedDocument)5 DocumentException (com.lowagie.text.DocumentException)4 ProcessSubtreeException (cz.incad.kramerius.ProcessSubtreeException)4 ActionNotAllowed (cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed)4 BadRequestException (cz.incad.kramerius.rest.api.exceptions.BadRequestException)4 GenericApplicationException (cz.incad.kramerius.rest.api.exceptions.GenericApplicationException)4 SecurityException (cz.incad.kramerius.security.SecurityException)4 File (java.io.File)4 FileOutputStream (java.io.FileOutputStream)4 MalformedURLException (java.net.MalformedURLException)4 SimpleDateFormat (java.text.SimpleDateFormat)4 StreamingOutput (javax.ws.rs.core.StreamingOutput)4 XPathExpressionException (javax.xml.xpath.XPathExpressionException)4 JSONException (org.json.JSONException)4 PDFResourceBadRequestException (cz.incad.kramerius.rest.api.k5.client.pdf.PDFResourceBadRequestException)3 Rectangle (com.lowagie.text.Rectangle)2 ObjectPidsPath (cz.incad.kramerius.ObjectPidsPath)2 AbstractPage (cz.incad.kramerius.document.model.AbstractPage)2