Package org.exist.util.io

Examples of org.exist.util.io.FilterInputStreamCache


    @Override
    protected Sequence extractRequestBody(final HttpRequest request) throws RestXqServiceException {
       
        //TODO dont use close shield input stream and move parsing of form parameters from HttpServletRequestAdapter into RequestBodyParser
        InputStream is = null;
        FilterInputStreamCache cache = null;

        try {
           
            //first, get the content of the request
            is = new CloseShieldInputStream(request.getInputStream());

            if(is.available() <= 0) {
                return null;
            }
           
            //if marking is not supported, we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
            if(!is.markSupported()) {
                cache = FilterInputStreamCacheFactory.getCacheInstance(new FilterInputStreamCacheFactory.FilterInputStreamCacheConfiguration(){
                    @Override
                    public String getCacheClass() {
                        final Configuration configuration = getBrokerPool().getConfiguration();
                        return (String)configuration.getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
                    }
                });
               
                is = new CachingFilterInputStream(cache, is);
            }
           
            is.mark(Integer.MAX_VALUE);
        } catch(final IOException ioe) {
            throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, ioe);
        }

        Sequence result = null;
        try {

            //was there any POST content?
            if(is != null && is.available() > 0) {
                String contentType = request.getContentType();
                // 1) determine if exists mime database considers this binary data
                if(contentType != null) {
                    //strip off any charset encoding info
                    if(contentType.indexOf(";") > -1) {
                        contentType = contentType.substring(0, contentType.indexOf(";"));
                    }

                    MimeType mimeType = MimeTable.getInstance().getContentType(contentType);
                    if(mimeType != null && !mimeType.isXMLType()) {

                        //binary data
                        try {
                           
                            final BinaryValue binaryValue = BinaryValueFromInputStream.getInstance(binaryValueManager, new Base64BinaryValueType(), is);
                            if(binaryValue != null) {
                                result = new SequenceImpl<BinaryValue>(new BinaryTypedValue(binaryValue));
                            }
                        } catch(final XPathException xpe) {
                            throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, xpe);
                        }
                    }
                }

                if(result == null) {
                    //2) not binary, try and parse as an XML documemnt
                    final DocumentImpl doc = parseAsXml(is);
                    if(doc != null) {
                        result = new SequenceImpl<Document>(new DocumentTypedValue(doc));
                    }
                }

                if(result == null) {

                    String encoding = request.getCharacterEncoding();
                    // 3) not a valid XML document, return a string representation of the document
                    if(encoding == null) {
                        encoding = "UTF-8";
                    }

                    try {
                        //reset the stream, as we need to reuse for string parsing
                        is.reset();

                        final StringValue str = parseAsString(is, encoding);
                        if(str != null) {
                            result = new SequenceImpl<StringValue>(new StringTypedValue(str));
                        }
                    } catch(final IOException ioe) {
                        throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, ioe);
                    }
                }
            }
        } catch (IOException e) {
            throw new RestXqServiceException(e.getMessage());
        } finally {

            if(cache != null) {
                try {
                    cache.invalidate();
                } catch(final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }
View Full Code Here


        // check if there is a response body
        if(bodyAsStream != null) {

            CachingFilterInputStream cfis = null;
            FilterInputStreamCache cache = null;
            try {
                   
                //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
                cache = FilterInputStreamCacheFactory.getCacheInstance(new FilterInputStreamCacheFactory.FilterInputStreamCacheConfiguration(){
                    @Override
                    public String getCacheClass() {
                        return (String) context.getBroker().getConfiguration().getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
                    }
                });

                cfis = new CachingFilterInputStream(cache, bodyAsStream);

                //mark the start of the stream
                cfis.mark(Integer.MAX_VALUE);


                // determine the type of the response document
                final Header responseContentType = method.getResponseHeader("Content-Type");

                final MimeType responseMimeType = getResponseMimeType(responseContentType);
                if(responseContentType != null) {
                    builder.addAttribute(new QName("mimetype", null, null), responseContentType.getValue());
                }

                //try and parse the response as XML
                try {
                    //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                    final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);
                    responseNode = (NodeImpl)ModuleUtils.streamToXML(context, shieldedInputStream);
                    builder.addAttribute(new QName("type", null, null ), "xml");
                    responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
                } catch(final SAXException se) {
                    // could not parse to xml
                    // not an error in itself, it will be treated either as HTML,
                    // text or binary here below
                    final String msg = "Request for URI '"
                        + method.getURI().toString()
                        + "' Could not parse http response content as XML (will try html, text or fallback to binary): "
                        + se.getMessage();
                    if(logger.isDebugEnabled()) {
                        logger.debug(msg, se);
                    } else {
                        logger.info(msg);
                    }
                } catch(final IOException ioe) {
                    final String msg = "Request for URI '" + method.getURI().toString() + "' Could not read http response content: " + ioe.getMessage();
                    logger.error(msg, ioe);
                    throw new XPathException(msg, ioe);
                }

                if(responseNode == null) {
                    //response is NOT parseable as XML

                    //is it a html document?
                    if(responseMimeType.getName().equals(MimeType.HTML_TYPE.getName())) {

                        //html document
                        try {

                            //reset the stream to the start, as we need to reuse since attempting to parse to XML
                            cfis.reset();

                            //parse html to xml(html)
                           
                            //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                            final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);
                           
                            responseNode = (NodeImpl)ModuleUtils.htmlToXHtml(context, method.getURI().toString(), new InputSource(shieldedInputStream), parserFeatures, parserProperties).getDocumentElement();
                            builder.addAttribute(new QName("type", null, null), "xhtml" );
                            responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
                        } catch(final URIException ue) {
                            throw new XPathException(this, ue.getMessage(), ue);
                        } catch(final SAXException se) {
                            //could not parse to xml(html)
                            logger.debug("Could not parse http response content from HTML to XML: " + se.getMessage(), se);
                        }
                    }
                }

                if(responseNode == null) {

                    //reset the stream to the start, as we need to reuse since attempting to parse to HTML->XML
                    cfis.reset();

                    if(responseMimeType.getName().startsWith("text/")) {

                        // Assume it's a text body and URL encode it
                        builder.addAttribute(new QName("type", null, null), "text");
                        builder.addAttribute(new QName("encoding", null, null), "URLEncoded");
                       
                        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        final byte buf[] = new byte[4096];
                        int read = -1;
                        while((read = cfis.read(buf)) > -1) {
                            baos.write(buf);
                        }
                       
                        builder.characters(URLEncoder.encode(EncodingUtil.getString(baos.toByteArray(), ((HttpMethodBase)method).getResponseCharSet()), "UTF-8"));
                        baos.close();
                    } else {

                        // Assume it's a binary body and Base64 encode it
                        builder.addAttribute( new QName( "type", null, null ), "binary" );
                        builder.addAttribute( new QName( "encoding", null, null ), "Base64Encoded" );

                        BinaryValue binary = null;
                        try {
                            binary = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), cfis);
                            builder.characters(binary.getStringValue());
                        } finally {
                            // free resources
                            if (binary != null) {
                                binary.destroy(context, null);
                            }
                        }
                    }
                }
            } finally {
                if(cache != null) {
                    try {
                        cache.invalidate();
                    } catch(final IOException ioe) {
                        LOG.error(ioe.getMessage(), ioe);
                    }
                }
View Full Code Here

                if(result == Sequence.EMPTY_SEQUENCE) {
                    //2) not binary, try and parse as an XML documemnt, otherwise 3) return a string representation
                   
                    //parsing will consume the stream so we must cache!
                    InputStream is = null;
                    FilterInputStreamCache cache = null;
                    try {
                        //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
                        cache = FilterInputStreamCacheFactory.getCacheInstance(new FilterInputStreamCacheConfiguration(){

                            @Override
                            public String getCacheClass() {
                                return (String) context.getBroker().getConfiguration().getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
                            }
                        });
                        is = new CachingFilterInputStream(cache, isRequest);
                       
                        //mark the start of the stream
                        is.mark(Integer.MAX_VALUE);
                       
                        //2) try and  parse as XML
                        result = parseAsXml(is);
                       
                       
                        if(result == Sequence.EMPTY_SEQUENCE) {
                            // 3) not a valid XML document, return a string representation of the document
                            String encoding = request.getCharacterEncoding();
                            if(encoding == null) {
                                encoding = "UTF-8";
                            }

                            try {
                                //reset the stream, as we need to reuse for string parsing after the XML parsing happened
                                is.reset();

                                result = parseAsString(is, encoding);
                            } catch(final IOException ioe) {
                                throw new XPathException(this, "An IO exception occurred: " + ioe.getMessage(), ioe);
                            }
                        }
                       
                    } finally {
                        if(cache != null) {
                            try {
                                cache.invalidate();
                            } catch(final IOException ioe) {
                                LOG.error(ioe.getMessage(), ioe);
                            }
                        }
                       
View Full Code Here

TOP

Related Classes of org.exist.util.io.FilterInputStreamCache

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.