Example usage for javax.activation DataSource getInputStream

List of usage examples for javax.activation DataSource getInputStream

Introduction

In this page you can find the example usage for javax.activation DataSource getInputStream.

Prototype

public InputStream getInputStream() throws IOException;

Source Link

Document

This method returns an InputStream representing the data and throws the appropriate exception if it can not do so.

Usage

From source file:org.shredzone.cilla.service.impl.PageServiceImpl.java

@Override
public void addMedium(Page page, Medium medium, DataSource source) throws CillaServiceException {
    try {/*from ww  w .  jav a 2s.c  o m*/
        medium.setPage(page);

        Store store = medium.getImage();
        store.setContentType(source.getContentType());
        store.setLastModified(new Date());

        mediumDao.persist(medium);

        ResourceDataSource ds = storeDao.access(store);
        FileCopyUtils.copy(source.getInputStream(), ds.getOutputStream());
    } catch (IOException ex) {
        throw new CillaServiceException("Could not set medium", ex);
    }
}

From source file:com.jaeksoft.searchlib.parser.EmlParser.java

@Override
protected void parseContent(StreamLimiter streamLimiter, LanguageEnum lang)
        throws IOException, SearchLibException {
    Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);
    try {/*from w w  w.ja  v  a  2  s  . c  o  m*/

        MimeMessage mimeMessage = new MimeMessage(session, streamLimiter.getNewInputStream());
        MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();

        ParserResultItem result = getNewParserResultItem();
        String from = mimeMessageParser.getFrom();
        if (from != null)
            result.addField(ParserFieldEnum.email_display_from, from.toString());
        for (Address address : mimeMessageParser.getTo())
            result.addField(ParserFieldEnum.email_display_to, address.toString());
        for (Address address : mimeMessageParser.getCc())
            result.addField(ParserFieldEnum.email_display_cc, address.toString());
        for (Address address : mimeMessageParser.getBcc())
            result.addField(ParserFieldEnum.email_display_bcc, address.toString());
        result.addField(ParserFieldEnum.subject, mimeMessageParser.getSubject());
        result.addField(ParserFieldEnum.htmlSource, mimeMessageParser.getHtmlContent());
        result.addField(ParserFieldEnum.content, mimeMessageParser.getPlainContent());
        result.addField(ParserFieldEnum.email_sent_date, mimeMessage.getSentDate());
        result.addField(ParserFieldEnum.email_received_date, mimeMessage.getReceivedDate());

        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            result.addField(ParserFieldEnum.email_attachment_name, dataSource.getName());
            result.addField(ParserFieldEnum.email_attachment_type, dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(getSourceDocument(), dataSource.getName(),
                    dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults)
                    result.addField(ParserFieldEnum.email_attachment_content, parserResult);
        }
        if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
            result.langDetection(10000, ParserFieldEnum.content);
        else
            result.langDetection(10000, ParserFieldEnum.htmlSource);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.shredzone.cilla.service.resource.ImageProcessorImpl.java

@Override
@Cacheable(value = "processedImages", key = "#id + '-' + #process")
public ImageProcessorResult process(DataSource ds, long id, ImageProcessing process) throws IOException {
    ImageType type = process.getType();/*from  w w  w  .  j a  v a  2  s .  com*/
    int width = process.getWidth();
    int height = process.getHeight();

    if (type == null) {
        if (width > 0 && width <= 256 && height > 0 && height <= 256) {
            type = ImageType.PNG;
        } else {
            type = ImageType.JPEG;
        }
    }

    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        Thumbnails.Builder<? extends InputStream> builder = Thumbnails.of(ds.getInputStream());
        if (width > 0 && height > 0) {
            builder.size(width, height);
        } else if (width > 0) {
            builder.width(width);
        } else if (height > 0) {
            builder.height(height);
        }

        BufferedImage scaled = builder.asBufferedImage();

        if (type == ImageType.JPEG_LOW) {
            jpegQualityWriter(scaled, new MemoryCacheImageOutputStream(out), type.getCompression());
        } else {
            ImageIO.write(scaled, type.getFormatName(), out);
        }

        ImageProcessorResult result = new ImageProcessorResult();
        result.setData(out.toByteArray());
        result.setContentType(type.getContentType());
        return result;
    }
}

From source file:eu.domibus.ebms3.sender.EbMS3MessageBuilder.java

private void attachPayload(PartInfo partInfo, SOAPMessage message)
        throws ParserConfigurationException, SOAPException, IOException, SAXException {
    String mimeType = null;//from w w  w  .  j a  v  a  2 s. c  om
    boolean compressed = false;
    for (Property prop : partInfo.getPartProperties().getProperties()) {
        if (Property.MIME_TYPE.equals(prop.getName())) {
            mimeType = prop.getValue();
        }
        if (CompressionService.COMPRESSION_PROPERTY_KEY.equals(prop.getName())
                && CompressionService.COMPRESSION_PROPERTY_VALUE.equals(prop.getValue())) {
            compressed = true;
        }
    }
    byte[] binaryData = this.attachmentDAO.loadBinaryData(partInfo.getEntityId());
    DataSource dataSource = new ByteArrayDataSource(binaryData,
            compressed ? CompressionService.COMPRESSION_PROPERTY_VALUE : mimeType);
    DataHandler dataHandler = new DataHandler(dataSource);
    if (partInfo.isInBody() && mimeType != null && mimeType.toLowerCase().contains("xml")) { //TODO: respect empty soap body config
        this.documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = this.documentBuilderFactory.newDocumentBuilder();
        message.getSOAPBody().addDocument(builder.parse(dataSource.getInputStream()));
        partInfo.setHref(null);
        return;
    }
    AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler);
    attachmentPart.setContentId(partInfo.getHref());
    message.addAttachmentPart(attachmentPart);
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

private Document applyAnnotationsOnContentAsDocument(DataSource content, AnnotationView[] annotations)
        throws ApplicationException {
    Document doc = null;//w w w.ja va 2s .co  m

    if (log.isDebugEnabled())
        log.debug("Parsing article xml ...");

    try {
        doc = articleTransformService.createDocBuilder().parse(content.getInputStream());
    } catch (Exception e) {
        throw new ApplicationException(e.getMessage(), e);
    }

    try {
        if (annotations.length == 0)
            return doc;

        if (log.isDebugEnabled())
            log.debug("Applying " + annotations.length + " annotations to article ...");

        return Annotator.annotateAsDocument(doc, annotations);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Could not apply annotations to article: " + content.getName(), e);
        }
        throw new ApplicationException("Applying annotations failed for resource:" + content.getName(), e);
    }
}

From source file:org.shredzone.cilla.service.impl.PageServiceImpl.java

@Override
@CacheEvict(value = "processedImages", allEntries = true)
public void updateMedium(Page page, Medium medium, DataSource source) throws CillaServiceException {
    if (!medium.getPage().equals(page)) {
        throw new IllegalArgumentException(
                "Medium id " + medium.getId() + " does not belong to Page id " + page.getId());
    }/*from   w  w  w .  ja  va  2 s  .  com*/

    if (source != null) {
        try {
            Store store = medium.getImage();
            store.setContentType(source.getContentType());
            store.setName(source.getName());
            store.setLastModified(new Date());

            ResourceDataSource ds = storeDao.access(store);
            FileCopyUtils.copy(source.getInputStream(), ds.getOutputStream());
        } catch (IOException ex) {
            throw new CillaServiceException("Could not set medium", ex);
        }
    }
}

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

final public void readMessage(IndexDocument crawlIndexDocument, IndexDocument parserIndexDocument,
        Folder folder, Message message, String id) throws Exception {

    crawlIndexDocument.addString(MailboxFieldEnum.message_id.name(), id);
    crawlIndexDocument.addString(MailboxFieldEnum.message_number.name(),
            Integer.toString(message.getMessageNumber()));
    if (message instanceof MimeMessage)
        crawlIndexDocument.addString(MailboxFieldEnum.content_id.name(),
                ((MimeMessage) message).getContentID());
    crawlIndexDocument.addString(MailboxFieldEnum.subject.name(), message.getSubject());
    putAddresses(crawlIndexDocument, message.getFrom(), MailboxFieldEnum.from_address.name(),
            MailboxFieldEnum.from_personal.name());
    putAddresses(crawlIndexDocument, message.getReplyTo(), MailboxFieldEnum.reply_to_address.name(),
            MailboxFieldEnum.reply_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.TO),
            MailboxFieldEnum.recipient_to_address.name(), MailboxFieldEnum.recipient_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.CC),
            MailboxFieldEnum.recipient_cc_address.name(), MailboxFieldEnum.recipient_cc_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.BCC),
            MailboxFieldEnum.recipient_bcc_address.name(), MailboxFieldEnum.recipient_bcc_personal.name());
    Date dt = message.getSentDate();
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.send_date.name(), dt.toString());
    dt = message.getReceivedDate();/*w ww  .j a va 2  s.  c  o  m*/
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.received_date.name(), dt.toString());
    if (message.isSet(Flag.ANSWERED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "ANSWERED");
    if (message.isSet(Flag.DELETED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DELETED");
    if (message.isSet(Flag.DRAFT))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DRAFT");
    if (message.isSet(Flag.FLAGGED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "FLAGGED");
    if (message.isSet(Flag.SEEN))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "SEEN");

    if (message instanceof MimeMessage) {
        MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) message).parse();

        crawlIndexDocument.addString(MailboxFieldEnum.html_content.name(), mimeMessageParser.getHtmlContent());
        crawlIndexDocument.addString(MailboxFieldEnum.plain_content.name(),
                mimeMessageParser.getPlainContent());
        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_name.name(), dataSource.getName());
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_type.name(),
                    dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(null, dataSource.getName(),
                    dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults)
                    crawlIndexDocument.addFieldIndexDocument(MailboxFieldEnum.email_attachment_content.name(),
                            parserResult.getParserDocument());
        }
    }
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get the article xml/*  w ww.j a v  a  2 s.  c o m*/
 * @param article article uri
 *
 * @return article xml
 */
public Document getArticleDocument(final ArticleInfo article) {
    Document doc = null;
    DataSource content = null;
    String articleURI = article.getDoi();

    try {
        content = getArticleXML(articleURI);
    } catch (Exception e) {
        log.warn("Article " + articleURI + " not found.");
        return null;
    }

    try {
        doc = articleTransformService.createDocBuilder().parse(content.getInputStream());
    } catch (Exception e) {
        log.error("Error parsing the article xml for article " + articleURI, e);
        return null;
    }

    return doc;
}

From source file:at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.SignedDocAttributeRequestProvider.java

public IPersonalAttributeList parse(HttpServletRequest httpReq)
        throws MOAIDException, UnsupportedAttributeException {
    Logger.debug("Beginning to extract OASIS-DSS response out of HTTP Request");

    try {//from w  w  w. j a v a  2s  . c  om
        String base64 = httpReq.getParameter("signresponse");
        Logger.debug("signresponse url: " + httpReq.getRequestURI().toString());
        Logger.debug("signresponse querystring: " + httpReq.getQueryString());
        Logger.debug("signresponse method: " + httpReq.getMethod());
        Logger.debug("signresponse content type: " + httpReq.getContentType());
        Logger.debug("signresponse parameter:" + base64);
        String signResponseString = new String(Base64.decodeBase64(base64), "UTF8");
        Logger.debug("RECEIVED signresponse:" + signResponseString);
        //create SignResponse object
        Source response = new StreamSource(new java.io.StringReader(signResponseString));
        SignResponse signResponse = ApiUtils.unmarshal(response, SignResponse.class);
        //Check if Signing was successfully or not

        if (!signResponse.getResult().getResultMajor().equals(ResultMajor.RESULT_MAJOR_SUCCESS)) {
            //Pass unmodifed or unmarshal & marshal??
            InputStream istr = ApiUtils.marshalToInputStream(signResponse);
            StringWriter writer = new StringWriter();
            IOUtils.copy(istr, writer, "UTF-8");
            signResponseString = writer.toString();
            Logger.info("SignResponse with error (unmodified):" + signResponseString);
            istr.close();
        } else {
            //extract doc from signresponse
            DataSource dataSource = LightweightSourceResolver.getDataSource(signResponse);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(dataSource.getInputStream(), baos);
            byte[] data = baos.toByteArray();
            baos.close();

            //update doc in DTL
            String docId, dssId = "";
            docId = signResponse.getDocUI();
            //For reference dssId equals docId
            dssId = docId;
            if (dssId != null && data != null) {
                boolean success = false;
                try {
                    success = updateDocumentInDtl(data, docId, signResponseString);
                } catch (Exception e) {//No document service used?
                    Logger.info("No document service used?");
                    e.printStackTrace();
                    success = false;
                }
                if (success) {
                    // set the url in the SignResponse
                    DocumentWithSignature documentWithSignature = new DocumentWithSignature();
                    DocumentType value = new DocumentType();
                    if (dtlUrl.endsWith("?wsdl")) {
                        String tmp = dtlUrl.replace("?wsdl", "");
                        Logger.debug("DocumentUrl ends with ? wsdl, using " + tmp + " instead.");
                        value.setDocumentURL(tmp);
                    } else {
                        value.setDocumentURL(dtlUrl);
                    }
                    documentWithSignature.setDocument(value);
                    if (signResponse.getOptionalOutputs() != null) {
                        //signResponse.getOptionalOutputs().getAny().add(documentWithSignature);   
                        for (Object o : signResponse.getOptionalOutputs().getAny()) {
                            if (o instanceof DocumentWithSignature) {
                                signResponse.getOptionalOutputs().getAny().remove(o);
                                signResponse.getOptionalOutputs().getAny().add(documentWithSignature);
                                break;
                            }
                        }
                    } else {
                        AnyType anytype = new AnyType();
                        anytype.getAny().add(documentWithSignature);
                        signResponse.setOptionalOutputs(anytype);
                    }

                    //                  System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl);
                    InputStream istr = ApiUtils.marshalToInputStream(signResponse);
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(istr, writer, "UTF-8");
                    signResponseString = writer.toString();
                    Logger.info("SignResponse overwritten:" + signResponseString);
                    istr.close();
                } else {
                    //No document service used?
                    // do nothing....
                    //TODO temporary fix because document is deleted after fetching => SP can't download Doc
                    //Add doc to Signresponse

                    DocumentWithSignature documentWithSignature = new DocumentWithSignature();
                    DocumentType value = new DocumentType();
                    if (signResponse.getProfile().toLowerCase().contains("xades")) {
                        value.setBase64XML(data);
                    } else {
                        Base64Data base64data = new Base64Data();
                        base64data.setValue(data);
                        base64data.setMimeType(dataSource.getContentType());
                        value.setBase64Data(base64data);
                    }
                    documentWithSignature.setDocument(value);
                    if (signResponse.getOptionalOutputs() != null) {
                        //signResponse.getOptionalOutputs().getAny().add(documentWithSignature);
                        for (Object o : signResponse.getOptionalOutputs().getAny()) {
                            if (o instanceof DocumentWithSignature) {
                                signResponse.getOptionalOutputs().getAny().remove(o);
                                signResponse.getOptionalOutputs().getAny().add(documentWithSignature);
                                break;
                            }
                        }
                    } else {
                        AnyType anytype = new AnyType();
                        anytype.getAny().add(documentWithSignature);
                        signResponse.setOptionalOutputs(anytype);
                    }

                    //                  System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl);
                    InputStream istr = ApiUtils.marshalToInputStream(signResponse);
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(istr, writer, "UTF-8");
                    signResponseString = writer.toString();
                    Logger.info("SignResponse overwritten:" + signResponseString);
                    istr.close();
                }
            } else
                throw new Exception("No DSS id found.");
        }

        //alter signresponse
        //done
        List<String> values = new ArrayList<String>();
        values.add(signResponseString);

        Logger.debug("Assembling signedDoc attribute");
        PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values,
                AttributeStatusType.AVAILABLE.value());

        // pack and return the result
        PersonalAttributeList result = new PersonalAttributeList();
        result.add(signedDocAttribute);
        return result;
    } catch (UnsupportedEncodingException e) {
        Logger.error("Failed to assemble signedDoc attribute");
        throw new MOAIDException("stork.05", null);
    } catch (ApiUtilsException e) {
        e.printStackTrace();
        Logger.error("Failed to assemble signedDoc attribute");
        throw new MOAIDException("stork.05", null);
    } catch (IOException e) {
        e.printStackTrace();
        Logger.error("Failed to assemble signedDoc attribute");
        throw new MOAIDException("stork.05", null);
    } catch (Exception e) {
        e.printStackTrace();
        Logger.error("Failed to assemble signedDoc attribute");
        //throw new MOAIDException("stork.05", null);
        throw new UnsupportedAttributeException();
    }
}

From source file:com.jaspersoft.jasperserver.rest.utils.Utils.java

public void sendFile(DataSource ds, HttpServletResponse response) {
    response.setContentType(ds.getContentType());

    if (ds.getName() != null && ds.getName().length() > 0) {
        response.addHeader("Content-Disposition", "attachment; filename=" + ds.getName());
    }/*from w  w w  .j  a va2 s. c  o m*/

    OutputStream outputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {
        outputStream = response.getOutputStream();

        bufferedInputStream = new BufferedInputStream(ds.getInputStream());
        int readBytes = 0;

        while ((readBytes = bufferedInputStream.read()) != -1) {
            outputStream.write(readBytes);
        }

        if (log.isDebugEnabled()) {
            log.debug("finished sending bytes");
        }

    } catch (IOException ex) {
        log.error("Error serving a file: " + ex.getMessage(), ex);
    } finally {
        if (outputStream != null)
            try {
                outputStream.close();
            } catch (Exception ex) {
            }
        if (bufferedInputStream != null)
            try {
                bufferedInputStream.close();
            } catch (Exception ex) {
            }
    }
}