Example usage for org.apache.pdfbox.io IOUtils toByteArray

List of usage examples for org.apache.pdfbox.io IOUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.pdfbox.io IOUtils toByteArray.

Prototype

public static byte[] toByteArray(InputStream in) throws IOException 

Source Link

Document

Reads the input stream and returns its contents as a byte array.

Usage

From source file:gov.anl.aps.cdb.portal.controllers.ItemDomainMAARCController.java

License:Open Source License

public String getPreviewPath(ItemDomainMAARC item, boolean storedOnly) {
    if (!isEntityTypeFile(item)) {
        return null;
    }//w ww .ja  va  2s.co m

    PropertyValue pv = getMAARCFilePropertyValueFromItem(item);

    if (pv == null) {
        return null;
    }

    if (!GalleryUtility.viewableFileName(pv.getValue())) {
        return null;
    }

    PropertyMetadata metadata = pv.getPropertyMetadataForKey(FILE_PROPERTY_VIEWABLE_UUID_METADATA_KEY);

    if (metadata != null) {
        String metadataValue = metadata.getMetadataValue();
        return metadataValue;
    }

    if (storedOnly) {
        return null;
    }

    try {
        // Prepare storage directory 
        String basePath = StorageUtility.getFileSystemMAARCPreviewsDirectory();
        Path uploadPath = Paths.get(basePath);
        if (Files.notExists(uploadPath)) {
            logger.debug("Creating inidial maarc previews directory: " + basePath);
            Files.createDirectory(uploadPath);
        }

        PropertyTypeHandlerInterface handler = PropertyTypeHandlerFactory.getHandler(pv);

        StreamedContent contentStream;
        try {
            contentStream = handler.fileDownloadActionCommand(pv);
        } catch (ExternalServiceError ex) {
            SessionUtility.addErrorMessage("Error Download File", ex.getMessage());
            return null;
        }

        InputStream stream = contentStream.getStream();

        byte[] originalData = IOUtils.toByteArray(stream);

        String fileName = pv.getValue();
        int extStart = fileName.lastIndexOf(".") + 1;
        String imageFormat = fileName.substring(extStart);

        if (imageFormat.equalsIgnoreCase("pdf")) {
            imageFormat = "png";
            originalData = GalleryUtility.createPNGFromPDF(originalData);
            if (originalData == null) {
                return null;
            }
        }

        UUID randomUUID = UUID.randomUUID();
        String uniqueFileName = randomUUID.toString();
        uniqueFileName += "." + imageFormat;

        GalleryUtility.storePreviewsFromViewableData(originalData, imageFormat, basePath, uniqueFileName);

        pv.setPropertyMetadataValue(FILE_PROPERTY_VIEWABLE_UUID_METADATA_KEY, uniqueFileName);

        // System save the metadata value
        PropertyMetadata viewableKeyMetadata = pv
                .getPropertyMetadataForKey(FILE_PROPERTY_VIEWABLE_UUID_METADATA_KEY);
        propertyMetadataFacade.create(viewableKeyMetadata);
        logger.debug("Created cdb viewable metadata id: " + viewableKeyMetadata.getId());

        return uniqueFileName;
    } catch (IOException ex) {
        logger.error(ex);
        SessionUtility.addErrorMessage("Error", ex.getMessage());
        return null;
    }
}

From source file:io.konik.carriage.pdfbox.PDFBoxInvoiceExtractor.java

License:Open Source License

@Override
public byte[] extract(InputStream pdfInput) {
    InputStream attachmentFile = null;
    try {/*from   ww w.j  a va 2 s . com*/
        attachmentFile = extractToStream(pdfInput);
        return IOUtils.toByteArray(attachmentFile);
    } catch (IOException e) {
        throw new InvoiceExtractionError("Error extracting content from PDF", e);
    } finally {
        IOUtils.closeQuietly(attachmentFile);
    }
}

From source file:io.konik.carriage.pdfbox.PDFBoxInvoiceExtractorTest.java

License:Open Source License

@Test
public void extractToStream() throws Exception {
    //setup//from  w  w  w .  ja  va2  s.c  o m
    InputStream pdfStream = getClass().getResourceAsStream(PDF_INVOICE_LOCATION);

    //exec
    InputStream inputStream = invoiceExtractor.extractToStream(pdfStream);
    String invoice = new String(IOUtils.toByteArray(inputStream), "UTF-8");

    assertThat(inputStream).isNotNull();
    assertThat(invoice).containsOnlyOnce("<ram:ID>471102</ram:ID>");
    assertThat(invoice).containsOnlyOnce("</rsm:CrossIndustryDocument>");
    inputStream.close();
}

From source file:org.apache.fop.render.pdf.pdfbox.PreloaderImageRawData.java

License:Apache License

public ImageInfo preloadImage(String s, Source source, ImageContext imageContext)
        throws ImageException, IOException {
    if (source instanceof ImageSource && s.contains(DataBufferInt.class.getName())) {
        InputStream is = ((ImageSource) source).getInputStream();
        byte[] input = IOUtils.toByteArray(is);
        is.reset();/*from w ww.  j a va 2s.  c o m*/
        IntBuffer intBuf = ByteBuffer.wrap(input).order(ByteOrder.BIG_ENDIAN).asIntBuffer();
        int[] array = new int[intBuf.remaining()];
        intBuf.get(array);
        int width = array[0];
        int height = array[1];
        ImageInfo info = new ImageInfo(s, "image/DataBufferInt");
        ImageSize size = new ImageSize(width, height, imageContext.getSourceResolution());
        size.calcSizeFromPixels();
        info.setSize(size);
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        DataBufferInt db = (DataBufferInt) img.getRaster().getDataBuffer();
        System.arraycopy(array, 2, db.getData(), 0, db.getData().length);
        info.getCustomObjects().put(ImageInfo.ORIGINAL_IMAGE, new ImageRendered(info, img, null));
        return info;
    }
    return null;
}

From source file:org.isisaddons.module.pdfbox.dom.service.PdfBoxServiceTest.java

License:Apache License

@Test
public void simple() throws Exception {

    // given//from w  w  w  .  ja v  a  2s . c om
    InputStream pdf1 = new FileInputStream(
            new File("src/test/java/org/isisaddons/module/pdfbox/dom/service/input-1.pdf"));
    final byte[] pdf1Bytes = IOUtils.toByteArray(pdf1);

    InputStream pdf2 = new FileInputStream(
            new File("src/test/java/org/isisaddons/module/pdfbox/dom/service/input-2.pdf"));
    final byte[] pdf2Bytes = IOUtils.toByteArray(pdf2);

    InputStream expected = new FileInputStream(
            new File("src/test/java/org/isisaddons/module/pdfbox/dom/service/output-expected.pdf"));
    final byte[] expectedBytes = IOUtils.toByteArray(expected);

    // when
    final byte[] mergedBytes = service.merge(pdf1Bytes, pdf2Bytes);

    // then
    assertThat(mergedBytes.length, is(equalTo(expectedBytes.length)));

}

From source file:org.jesterj.ingest.scanners.JdbcScanner.java

License:Apache License

private byte[] getContentBytes(ResultSet rs) throws SQLException {
    byte[] rawBytes = null;

    // If the content column was specified
    if (StringUtils.isNotBlank(contentColumn)) {
        // Get its value.
        Object content = rs.getObject(contentColumn);

        if (content != null) {
            // Clob
            if (content instanceof Clob) {
                Clob clob = (Clob) content;
                try (Reader reader = clob.getCharacterStream()) {
                    rawBytes = CharStreams.toString(reader).getBytes();
                } catch (IOException ex) {
                    String msg = String.format("I/O error while reading value of content column '%s'.",
                            contentColumn);
                    log.error(msg, ex);/* w w  w . j av  a 2 s .  co  m*/
                }
            }
            // Blob
            else if (content instanceof Blob) {
                Blob blob = (Blob) content;
                try (InputStream stream = blob.getBinaryStream()) {
                    rawBytes = IOUtils.toByteArray(stream);
                } catch (IOException ex) {
                    String msg = String.format("I/O error while reading value of content column '%s'.",
                            contentColumn);
                    log.error(msg, ex);
                }
            }
            // Date (unlikely, but)
            else if (content instanceof Date) {
                rawBytes = convertDateToString(content).getBytes();
            }
            // Anything else
            else {
                rawBytes = content.toString().getBytes();
            }
        }
    }
    return rawBytes;
}

From source file:org.structr.web.servlet.DeploymentServlet.java

License:Open Source License

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    try (final Tx tx = StructrApp.getInstance().tx()) {

        if (!ServletFileUpload.isMultipartContent(request)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getOutputStream()//from   w  ww .  j a v  a 2 s.co m
                    .write("ERROR (400): Request does not contain multipart content.\n".getBytes("UTF-8"));
            return;
        }

        final SecurityContext securityContext;
        try {
            securityContext = getConfig().getAuthenticator().initializeAndExamineRequest(request, response);

        } catch (AuthenticationException ae) {

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getOutputStream().write("ERROR (401): Invalid user or password.\n".getBytes("UTF-8"));
            return;
        }

        if (securityContext.getUser(false) == null && !Settings.DeploymentAllowAnonymousUploads.getValue()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getOutputStream().write("ERROR (401): Anonymous uploads forbidden.\n".getBytes("UTF-8"));
            return;
        }

        // Ensure access mode is frontend
        securityContext.setAccessMode(AccessMode.Frontend);

        request.setCharacterEncoding("UTF-8");

        // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
        response.setCharacterEncoding("UTF-8");

        // don't continue on redirects
        if (response.getStatus() == 302) {
            return;
        }

        final String pathInfo = request.getPathInfo();
        String type = null;

        if (StringUtils.isNotBlank(pathInfo)) {

            type = SchemaHelper.normalizeEntityName(StringUtils.stripStart(pathInfo.trim(), "/"));

        }

        uploader.setFileSizeMax(MEGABYTE * Settings.DeploymentMaxFileSize.getValue());
        uploader.setSizeMax(MEGABYTE * Settings.DeploymentMaxRequestSize.getValue());

        response.setContentType("text/html");

        final List<FileItem> fileItemsList = uploader.parseRequest(request);
        final Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        final Map<String, Object> params = new HashMap<>();

        while (fileItemsIterator.hasNext()) {

            final FileItem item = fileItemsIterator.next();

            try {
                final String directoryPath = "/tmp/" + UUID.randomUUID();
                final String filePath = directoryPath + ".zip";

                File file = new File(filePath);
                Files.write(IOUtils.toByteArray(item.getInputStream()), file);

                unzip(file, directoryPath);

                DeployCommand deployCommand = StructrApp.getInstance(securityContext)
                        .command(DeployCommand.class);

                final Map<String, Object> attributes = new HashMap<>();
                attributes.put("source",
                        directoryPath + "/" + StringUtils.substringBeforeLast(item.getName(), "."));

                deployCommand.execute(attributes);

                file.deleteOnExit();
                File dir = new File(directoryPath);

                dir.deleteOnExit();

            } catch (IOException ex) {
                logger.warn("Could not upload file", ex);
            }

        }

        tx.success();

    } catch (FrameworkException | IOException | FileUploadException t) {

        logger.error("Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}

From source file:uk.ac.kcl.rowmappers.DocumentRowMapper.java

License:Apache License

private void mapDBFields(Document doc, ResultSet rs) throws SQLException, IOException {
    //add additional query fields for ES export
    ResultSetMetaData meta = rs.getMetaData();

    int colCount = meta.getColumnCount();

    for (int col = 1; col <= colCount; col++) {
        Object value = rs.getObject(col);
        if (value != null) {
            String colLabel = meta.getColumnLabel(col).toLowerCase();
            if (!fieldsToIgnore.contains(colLabel)) {
                DateTime dateTime;/*  w ww. j a v  a2  s .co  m*/
                //map correct SQL time types
                switch (meta.getColumnType(col)) {
                case 91:
                    Date dt = (Date) value;
                    dateTime = new DateTime(dt.getTime());
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(),
                            eSCompatibleDateTimeFormatter.print(dateTime));
                    break;
                case 93:
                    Timestamp ts = (Timestamp) value;
                    dateTime = new DateTime(ts.getTime());
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(),
                            eSCompatibleDateTimeFormatter.print(dateTime));
                    break;
                default:
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(), rs.getString(col));
                    break;
                }
            }
        }

        //map binary content from FS or database if required (as per docman reader)
        if (value != null && meta.getColumnLabel(col).equalsIgnoreCase(binaryContentFieldName)) {
            switch (binaryContentSource) {
            case "database":
                doc.setBinaryContent(rs.getBytes(col));
                break;
            case "fileSystemWithDBPath":
                for (int i = 0; possibleFileExtensions != null && i < possibleFileExtensions.length; i++) {
                    String fileFullPath = pathPrefix + rs.getString(col) + possibleFileExtensions[i];
                    File f = new File(fileFullPath);
                    if (f.exists() && !f.isDirectory()) {
                        LOG.info("File found, working on " + fileFullPath);
                        Resource resource = context.getResource("file:" + fileFullPath);
                        doc.setBinaryContent(IOUtils.toByteArray(resource.getInputStream()));
                        break;
                    }
                }
                break;
            default:
                break;
            }
        }
    }
}