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:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the {@link HttpUriRequest} that will be used to {@linkplain #doProxyRequest(Page.Request, Channel.Mode)
 * proxy} content while fulfilling the specified <code>pageRequest</code>. This method will
 * {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) calculate} the proxied file URL,
 * {@linkplain #createProxyRequestObject(Page.Request, Channel.Mode, URL) create} the appropriate type of request
 * object, set it's {@linkplain HttpUriRequest#setHeader(String, String) headers}, and, if this channel is
 * {@linkplain net.www_eee.portal.Page.Request#isMaximized(Channel) maximized}, set any
 * {@linkplain HttpEntityEnclosingRequest#setEntity(HttpEntity) entity} that was
 * {@linkplain net.www_eee.portal.Page.Request#getEntity() provided} by the <code>pageRequest</code>.
 * /* w w  w  .ja  va  2s. c o  m*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param proxyClient The {@link #createProxyClient(Page.Request) HttpClient} performing the proxy request.
 * @return The proxy {@link HttpUriRequest} object.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #doProxyRequest(Page.Request, Channel.Mode)
 * @see #PROXY_REQUEST_HOOK
 */
protected HttpRequestBase createProxyRequest(final Page.Request pageRequest, final Mode mode,
        final CloseableHttpClient proxyClient) throws WWWEEEPortal.Exception, WebApplicationException {
    final URL proxiedFileURL = getProxiedFileURL(pageRequest, mode, true);

    final Object[] context = new Object[] { mode, proxiedFileURL };
    HttpRequestBase proxyRequest = PROXY_REQUEST_HOOK.value(plugins, context, pageRequest);
    if (proxyRequest == null) {

        proxyRequest = createProxyRequestObject(pageRequest, mode, proxiedFileURL);

        final String userAgent = getProxyRequestUserAgentHeader(pageRequest, mode, proxyClient, proxiedFileURL,
                proxyRequest);
        if (userAgent != null)
            proxyRequest.setHeader("User-Agent", userAgent);
        final String acceptLanguage = getProxyRequestAcceptLanguageHeader(pageRequest, mode, proxyClient,
                proxiedFileURL, proxyRequest);
        if (acceptLanguage != null)
            proxyRequest.setHeader("Accept-Language", acceptLanguage);
        final String accept = getProxyRequestAcceptHeader(pageRequest, mode, proxyClient, proxiedFileURL,
                proxyRequest);
        if (accept != null)
            proxyRequest.setHeader("Accept", accept);
        final String authorization = getProxyRequestAuthorizationHeader(pageRequest, mode, proxyClient,
                proxiedFileURL, proxyRequest);
        if (authorization != null)
            proxyRequest.setHeader("Authorization", authorization);

        if (Mode.RESOURCE.equals(mode)) {
            final Optional<String> ifMatch = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(),
                    "If-Match", Function.identity());
            if (ifMatch.isPresent())
                proxyRequest.setHeader("If-Match", ifMatch.get());
            final Optional<String> ifModifiedSince = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(),
                    "If-Modified-Since", Function.identity());
            if (ifModifiedSince.isPresent())
                proxyRequest.setHeader("If-Modified-Since", ifModifiedSince.get());
            final Optional<String> ifNoneMatch = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(),
                    "If-None-Match", Function.identity());
            if (ifNoneMatch.isPresent())
                proxyRequest.setHeader("If-None-Match", ifNoneMatch.get());
            final Optional<String> ifUnmodifiedSince = RESTUtil.getFirstHeaderValue(
                    pageRequest.getHttpHeaders(), "If-Unmodified-Since", Function.identity());
            if (ifUnmodifiedSince.isPresent())
                proxyRequest.setHeader("If-Unmodified-Since", ifUnmodifiedSince.get());
        }

        if (!isCacheControlClientDirectivesDisabled(pageRequest)) {
            final Optional<CacheControl> cacheControl = RESTUtil
                    .getFirstHeaderValue(pageRequest.getHttpHeaders(), "Cache-Control", CacheControl::valueOf);
            if (cacheControl.isPresent())
                proxyRequest.setHeader("Cache-Control", cacheControl.get().toString());
        }

        if (pageRequest.isMaximized(this)) {

            final MediaType contentType = pageRequest.getHttpHeaders().getMediaType();
            if (contentType != null)
                proxyRequest.setHeader("Content-Type", contentType.toString());

            final DataSource entity = pageRequest.getEntity();
            if ((entity != null) && (proxyRequest instanceof HttpEntityEnclosingRequest)) {
                try {
                    final Optional<String> contentLengthString = RESTUtil.getFirstHeaderValue(
                            pageRequest.getHttpHeaders(), "Content-Length", Function.identity());
                    final HttpEntity httpEntity = new InputStreamEntity(entity.getInputStream(),
                            (contentLengthString.isPresent()) ? Long.parseLong(contentLengthString.get()) : -1);
                    ((HttpEntityEnclosingRequest) proxyRequest).setEntity(httpEntity);
                } catch (NumberFormatException nfe) {
                    throw new WebApplicationException(nfe, Response.Status.INTERNAL_SERVER_ERROR);
                } catch (IOException ioe) {
                    throw new WWWEEEPortal.OperationalException(ioe);
                }
            }

        } // if (pageRequest.isMaximized(this))

    } // if (proxyRequest == null)
    proxyRequest = PROXY_REQUEST_HOOK
            .requireFilteredResult(PROXY_REQUEST_HOOK.filter(plugins, context, pageRequest, proxyRequest));
    return proxyRequest;
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void writeWholeData(DataSource data, HttpServletRequest request, HttpServletResponse response,
        String characterEncoding, String dbHint)
        throws IOException, HttpErrorException, UnsupportedEncodingException {

    Reader reader = null;//  ww  w . ja v  a2s. co m
    InputStream in = data.getInputStream();
    if (in == null) {
        throw new HttpErrorException(404, "File not found: " + data.getName(), dbHint);
    }

    try {
        if (!isBinary(request, response)) {
            // this is a textual reponse
            if (characterEncoding != null && !characterEncoding.equals(response.getCharacterEncoding())) {
                reader = new InputStreamReader(in, characterEncoding);
                WGUtils.inToOut(reader, response.getWriter(), 2048);
            } else {
                WGUtils.inToOut(in, response.getOutputStream(), 2048);
            }
        } else {
            WGUtils.inToOut(in, response.getOutputStream(), 2048);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void writeRangesData(DataSource data, List<AcceptRange> ranges, HttpServletResponse response,
        String dbHint, long size) throws IOException, HttpErrorException, UnsupportedEncodingException {

    ServletOutputStream out = response.getOutputStream();
    for (AcceptRange range : ranges) {
        InputStream in = data.getInputStream();
        if (in == null) {
            throw new HttpErrorException(404, "File not found: " + data.getName(), dbHint);
        }/* www. j  av  a2 s. c om*/

        if (ranges.size() != 1) {
            out.println();
            out.println("--" + BYTERANGE_BOUNDARY);
            out.println("Content-Type: " + data.getContentType());
            out.println("Content-Range: bytes " + range.from + "-" + range.to + "/" + size);
            out.println();
        }

        if (range.from > 0) {
            in.skip(range.from);
        }

        try {
            WGUtils.inToOutLimited(in, out, (new Long(range.to - range.from + 1)).intValue(), 2048);
            out.flush();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (ranges.size() != 1) {
        out.println();
        out.print("--" + BYTERANGE_BOUNDARY + "--");
        out.flush();
    }

}

From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

public static EbMSMessageContent EbMSMessageToEbMSMessageContent(EbMSMessage message) throws IOException {
    List<EbMSAttachment> attachments = new ArrayList<EbMSAttachment>();
    for (DataSource attachment : message.getAttachments())
        attachments.add(new EbMSAttachment(attachment.getName(), attachment.getContentType(),
                IOUtils.toByteArray(attachment.getInputStream())));

    return new EbMSMessageContent(new EbMSMessageContext(message.getMessageHeader()), attachments);
}

From source file:org.adempiere.webui.apps.FeedbackRequestWindow.java

protected void saveRequest() throws IOException {
    Trx trx = Trx.get(Trx.createTrxName("SaveNewRequest"), true);
    try {//from   w w w  .  j  av  a 2  s . co  m
        trx.start();
        MRequest request = createMRequest(trx);

        boolean success = request.save();
        if (success) {
            MAttachment attachment = null;
            for (DataSource ds : attachments) {
                if (attachment == null) {
                    attachment = new MAttachment(Env.getCtx(), 0, request.get_TrxName());
                    attachment.setAD_Table_ID(request.get_Table_ID());
                    attachment.setRecord_ID(request.get_ID());
                }

                attachment.addEntry(ds.getName(), IOUtils.toByteArray(ds.getInputStream()));
            }
            if (attachment != null)
                success = attachment.save();

            if (success)
                success = trx.commit();

        }

        if (success) {
            FDialog.info(0, null, Msg.getMsg(Env.getCtx(), "Saved"));
        } else {
            trx.rollback();
            FDialog.error(0, this, Msg.getMsg(Env.getCtx(), "SaveError"));
        }
    } finally {
        trx.close();
    }
}

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

/**
 * For the articleInfo, get the article HTML
 *
 * @param article the articleInfo object
 *
 * @return the article HTML//from   w  ww. ja  v a 2  s .co m
 *
 * @throws ApplicationException
 * @throws NoSuchArticleIdException
 */
private String getTransformedArticle(final ArticleInfo article)
        throws ApplicationException, NoSuchArticleIdException {
    try {
        DataSource content = getArticleXML(article.getDoi());
        Document doc = articleTransformService.createDocBuilder().parse(content.getInputStream());

        doc = addExtraCitationInfo(doc, article.getCitedArticles());

        return articleTransformService.getTransformedDocument(doc);
    } catch (Exception e) {
        throw new ApplicationException(e);
    }
}

From source file:org.apache.axiom.om.util.ElementHelperTest.java

public void testGetTextAsStreamWithOMSourcedElement() throws Exception {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    DataSource ds = new RandomDataSource(445566, 32, 128, 20000000);
    QName qname = new QName("a");
    Charset cs = Charset.forName("ascii");
    OMSourcedElement element = new OMSourcedElementImpl(qname, factory,
            new WrappedTextNodeOMDataSourceFromDataSource(qname, ds, cs));
    Reader in = ElementHelper.getTextAsStream(element, true);
    assertFalse(in instanceof StringReader);
    IOTestUtils.compareStreams(new InputStreamReader(ds.getInputStream(), cs), in);
}

From source file:org.apache.axiom.om.util.ElementHelperTest.java

public void testGetTextAsStreamWithoutCaching() throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    if (factory.getClass().getName().equals("com.bea.xml.stream.MXParserFactory")) {
        // Skip the test on the StAX reference implementation because it
        // causes an out of memory error
        return;/*ww  w  .  j  av  a2s . co  m*/
    }
    DataSource ds = new RandomDataSource(654321, 64, 128, 20000000);
    Vector/*<InputStream>*/ v = new Vector/*<InputStream>*/();
    v.add(new ByteArrayInputStream("<a>".getBytes("ascii")));
    v.add(ds.getInputStream());
    v.add(new ByteArrayInputStream("</a>".getBytes("ascii")));
    factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
    XMLStreamReader reader = factory.createXMLStreamReader(new SequenceInputStream(v.elements()), "ascii");
    OMElement element = new StAXOMBuilder(reader).getDocumentElement();
    Reader in = ElementHelper.getTextAsStream(element, false);
    IOTestUtils.compareStreams(new InputStreamReader(ds.getInputStream(), "ascii"), in);
}

From source file:org.apache.axiom.om.util.ElementHelperTest.java

public void testWriteTextToWithOMSourcedElement() throws Exception {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    DataSource ds = new RandomDataSource(665544, 32, 128, 20000000);
    QName qname = new QName("a");
    OMSourcedElement element = new OMSourcedElementImpl(qname, factory,
            new WrappedTextNodeOMDataSourceFromDataSource(qname, ds, Charset.forName("ascii")));
    Reader in = new InputStreamReader(ds.getInputStream(), "ascii");
    Writer out = new CharacterStreamComparator(in);
    ElementHelper.writeTextTo(element, out, true); // cache doesn't matter here
    out.close();//from   w  w w  . j a v a 2s.  c o m
}

From source file:org.apache.axis.attachments.AttachmentPart.java

/**
 * Gets the content of this <CODE>AttachmentPart</CODE> object
 *   as a Java object. The type of the returned Java object
 *   depends on (1) the <CODE>DataContentHandler</CODE> object
 *   that is used to interpret the bytes and (2) the <CODE>
 *   Content-Type</CODE> given in the header.
 *
 *   <P>For the MIME content types "text/plain", "text/html" and
 *   "text/xml", the <CODE>DataContentHandler</CODE> object does
 *   the conversions to and from the Java types corresponding to
 *   the MIME types. For other MIME types,the <CODE>
 *   DataContentHandler</CODE> object can return an <CODE>
 *   InputStream</CODE> object that contains the content data as
 *   raw bytes.</P>//from  www  .  j  a  v  a  2 s .  c  om
 *
 *   <P>A JAXM-compliant implementation must, as a minimum,
 *   return a <CODE>java.lang.String</CODE> object corresponding
 *   to any content stream with a <CODE>Content-Type</CODE>
 *   value of <CODE>text/plain</CODE> and a <CODE>
 *   javax.xml.transform.StreamSource</CODE> object
 *   corresponding to a content stream with a <CODE>
 *   Content-Type</CODE> value of <CODE>text/xml</CODE>. For
 *   those content types that an installed <CODE>
 *   DataContentHandler</CODE> object does not understand, the
 *   <CODE>DataContentHandler</CODE> object is required to
 *   return a <CODE>java.io.InputStream</CODE> object with the
 *   raw bytes.</P>
 * @return a Java object with the content of this <CODE>
 *     AttachmentPart</CODE> object
 * @throws  SOAPException  if there is no content set
 *     into this <CODE>AttachmentPart</CODE> object or if there
 *     was a data transformation error
 */
public Object getContent() throws SOAPException {
    if (contentObject != null) {
        return contentObject;
    }

    if (datahandler == null) {
        throw new SOAPException(Messages.getMessage("noContent"));
    }

    javax.activation.DataSource ds = datahandler.getDataSource();
    InputStream is = null;
    try {
        is = ds.getInputStream();
        ;
    } catch (java.io.IOException io) {
        log.error(Messages.getMessage("javaIOException00"), io);
        throw new SOAPException(io);
    }
    if (ds.getContentType().equals("text/plain")) {
        try {
            byte[] bytes = new byte[is.available()];
            IOUtils.readFully(is, bytes);
            return new String(bytes);
        } catch (java.io.IOException io) {
            log.error(Messages.getMessage("javaIOException00"), io);
            throw new SOAPException(io);
        }
    } else if (ds.getContentType().equals("text/xml")) {
        return new StreamSource(is);
    } else if (ds.getContentType().equals("image/gif") || ds.getContentType().equals("image/jpeg")) {
        try {
            return ImageIOFactory.getImageIO().loadImage(is);
        } catch (Exception ex) {
            log.error(Messages.getMessage("javaIOException00"), ex);
            throw new SOAPException(ex);
        }
    }
    return is;
}