Example usage for javax.xml.transform.stream StreamSource getInputStream

List of usage examples for javax.xml.transform.stream StreamSource getInputStream

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamSource getInputStream.

Prototype

public InputStream getInputStream() 

Source Link

Document

Get the byte stream that was set with setByteStream.

Usage

From source file:de.drv.dsrv.spoc.web.webservice.spring.SpocEndpoint.java

/**
 * Von Spring-WS aufgerufene Methode zur Verarbeitung von eXTra-Requests.
 * <p>//from  ww  w . j a v a2  s  .c o m
 * Identifiziert das zugeh&oumlrige Fachverfahren und leitet den
 * eXTra-Request dorthin weiter. Wenn aus dem Original-Request eine
 * Betriebsnummer extrahiert werden kann, wird diese als Request-Parameter
 * an das Fachverfahren weiter gegeben.
 * 
 * @param version
 *            Wert des version-Attributs im Transport-Element
 * @param profile
 *            Wert des profile-Attributs im Transport-Element
 * @param procedure
 *            Wert des Procedure-Elements im TransportHeader
 * @param dataType
 *            Wert des DataType-Elements im TransportHeader
 * @param payload
 *            der eXTra-Request mit dem Transport-Element als Wurzel
 * 
 * @return die vom Fachverfahren erhaltene Antwort
 * 
 * @throws IOException
 *             wenn w&auml;rend der Verarbeitung des Requests ein Fehler
 *             auftritt
 * @throws UnidentifiedFachverfahrenException
 *             wenn f&uumlr den Request kein Fachverfahren identifiziert
 *             werden kann
 */
@Namespaces({ @Namespace(prefix = "req", uri = "http://www.extra-standard.de/namespace/request/1"),
        @Namespace(prefix = "cmp", uri = "http://www.extra-standard.de/namespace/components/1") })
@PayloadRoot(localPart = "Transport", namespace = "http://www.extra-standard.de/namespace/request/1")
@ResponsePayload
public Source handleExtraRequest(@XPathParam("/req:Transport/@version") final String version,
        @XPathParam("/req:Transport/@profile") final String profile,
        @XPathParam("/req:Transport/req:TransportHeader/cmp:RequestDetails/cmp:Procedure") final String procedure,
        @XPathParam("/req:Transport/req:TransportHeader/cmp:RequestDetails/cmp:DataType") final String dataType,
        @RequestPayload final StreamSource payload) throws IOException {

    // Ermittle Fachverfahren-URL
    URI fachverfahrenUrl = this.spocRoutingService.getFachverfahrenUrl(version, profile, procedure, dataType);

    if (fachverfahrenUrl == null) {

        throw new UnidentifiedFachverfahrenException(profile, version, procedure, dataType);

    } else {

        // Versucht, die Betriebsnummer aus dem Request zu lesen und sie als
        // Parameter an den weiter geleiteten Request anzuhaengen
        fachverfahrenUrl = this.betriebsnummerService.addBetriebsnummerFromRequestToUrl(fachverfahrenUrl);

        // Leitet den Request an das Fachverfahren weiter
        if (LOG.isInfoEnabled()) {
            LOG.info("Weiterleiten des Requests an Fachverfahren >" + fachverfahrenUrl + "<.");
        }
        final Source responseSource = this.fachverfahrenRequestService
                .executeFachverfahrenRequest(fachverfahrenUrl, payload.getInputStream());
        if (LOG.isInfoEnabled()) {
            LOG.info("Antwort erhalten von Fachverfahren >" + fachverfahrenUrl + "<.");
        }

        return responseSource;
    }
}

From source file:com.jaeksoft.searchlib.Client.java

public int updateTextDocuments(StreamSource streamSource, String charset, Integer bufferSize,
        String capturePattern, Integer langPosition, List<String> fieldList, InfoCallback infoCallBack)
        throws SearchLibException, IOException, NoSuchAlgorithmException, URISyntaxException,
        InstantiationException, IllegalAccessException, ClassNotFoundException {
    if (capturePattern == null)
        throw new SearchLibException("No capture pattern");
    if (fieldList == null || fieldList.size() == 0)
        throw new SearchLibException("empty field list");
    String[] fields = fieldList.toArray(new String[fieldList.size()]);
    Matcher matcher = Pattern.compile(capturePattern).matcher("");
    BufferedReader br = null;/* w ww  .  java  2 s.c o  m*/
    Reader reader = null;
    SchemaField uniqueSchemaField = getSchema().getFieldList().getUniqueField();
    String uniqueField = uniqueSchemaField != null ? uniqueSchemaField.getName() : null;
    if (charset == null)
        charset = "UTF-8";
    if (bufferSize == null)
        bufferSize = 50;
    try {
        Collection<IndexDocument> docList = new ArrayList<IndexDocument>(bufferSize);
        reader = streamSource.getReader();
        if (reader == null)
            reader = new InputStreamReader(streamSource.getInputStream(), charset);
        br = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
        String line;
        int docCount = 0;
        IndexDocument lastDocument = null;
        String lastUniqueValue = null;
        while ((line = br.readLine()) != null) {
            matcher.reset(line);
            if (!matcher.matches())
                continue;
            LanguageEnum lang = LanguageEnum.UNDEFINED;
            int matcherGroupCount = matcher.groupCount();
            if (langPosition != null && matcherGroupCount >= langPosition)
                lang = LanguageEnum.findByNameOrCode(matcher.group(langPosition));
            IndexDocument document = new IndexDocument(lang);
            int i = matcherGroupCount < fields.length ? matcherGroupCount : fields.length;
            String uniqueValue = null;
            while (i > 0) {
                String value = matcher.group(i--);
                String f = fields[i];
                document.add(f, value, 1.0F);
                if (f.equals(uniqueField))
                    uniqueValue = value;
            }
            // Consecutive documents with same uniqueKey value are merged
            // (multivalued)
            if (uniqueField != null && lastDocument != null && uniqueValue != null
                    && uniqueValue.equals(lastUniqueValue)) {
                lastDocument.addIfNotAlreadyHere(document);
                continue;
            }
            docList.add(document);
            if (docList.size() == bufferSize)
                docCount = updateDocList(0, docCount, docList, infoCallBack);
            lastUniqueValue = uniqueValue;
            lastDocument = document;
        }
        if (docList.size() > 0)
            docCount = updateDocList(0, docCount, docList, infoCallBack);
        return docCount;
    } finally {
        if (br != null)
            if (br != reader)
                IOUtils.close(br);
    }
}

From source file:com.twinsoft.convertigo.engine.requesters.PdfServletRequester.java

protected Object performXSLT(Document document) throws Exception {
    String t1 = context.statistics.start(EngineStatistics.XSLT);

    try {/*from ww w . j  a v a 2  s  . c  om*/
        Engine.logEngine.debug("XSL/FO process is beginning");

        Object result = null;

        Engine.logEngine.debug("Sheet absolute URL: " + context.absoluteSheetUrl);
        if (context.absoluteSheetUrl == null)
            throw new EngineException(
                    "You have required an XSL/FO process, but Convertigo has been unable to find a stylesheet for your request. Verify your project's settings.");

        // XSL/FO engine
        StreamSource streamSource = null;
        try {
            // Configure foUserAgent as desired
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            foUserAgent.setBaseURL(
                    new File(Engine.PROJECTS_PATH + "/" + context.projectName).toURI().toASCIIString());
            foUserAgent.setAuthor("Convertigo EMS");

            // Setup output
            org.apache.commons.io.output.ByteArrayOutputStream out = new org.apache.commons.io.output.ByteArrayOutputStream();

            // Construct fop with desired output format
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

            // Setup XSLT
            streamSource = new StreamSource(new File(context.absoluteSheetUrl).toURI().toASCIIString());
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(streamSource);

            // Setup input for XSLT transformation
            Element element = document.getDocumentElement();
            DOMSource src = new DOMSource(element);

            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Start XSLT transformation and FOP processing
            transformer.transform(src, res);

            result = out.toByteArray();
        } finally {
            if (streamSource != null) {
                InputStream inputStream = streamSource.getInputStream();
                if (inputStream != null)
                    inputStream.close();
            }
        }

        Engine.logEngine.trace("XSLT result:\n" + result);

        return result;
    } finally {
        Engine.logEngine.debug("XSLT process has finished");
        context.statistics.stop(t1);
    }
}

From source file:com.twinsoft.convertigo.engine.requesters.JavelinServletRequester.java

protected Object performXSLT(Document document) throws Exception {
    String t1 = context.statistics.start(EngineStatistics.XSLT);

    try {//from w  w w  .  j  ava  2s.  c o  m
        Engine.logEngine.debug("XSL/FO process is beginning");

        Object result = null;

        Engine.logEngine.debug("Sheet absolute URL: " + context.absoluteSheetUrl);
        if (context.absoluteSheetUrl == null)
            throw new EngineException(
                    "You have required an XSL/FO process, but Convertigo has been unable to find a stylesheet for your request. Verify your project's settings.");

        // XSL/FO engine
        StreamSource streamSource = null;
        try {
            // Construct/Configure a FopFactory
            FopFactory fopFactory = FopFactory.newInstance();
            fopFactory.setBaseURL(Engine.TEMPLATES_PATH);

            // Configure foUserAgent as desired
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            foUserAgent.setBaseURL(Engine.PROJECTS_PATH + "/" + context.projectName);
            foUserAgent.setAuthor("Convertigo EMS");

            // Setup output
            org.apache.commons.io.output.ByteArrayOutputStream out = new org.apache.commons.io.output.ByteArrayOutputStream();

            // Construct fop with desired output format
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

            // Setup XSLT
            streamSource = new StreamSource(new File(context.absoluteSheetUrl).toURI().toASCIIString());
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(streamSource);

            // Setup input for XSLT transformation
            Element element = document.getDocumentElement();
            DOMSource src = new DOMSource(element);

            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Start XSLT transformation and FOP processing
            transformer.transform(src, res);

            result = out.toByteArray();
        } finally {
            if (streamSource != null) {
                InputStream inputStream = streamSource.getInputStream();
                if (inputStream != null)
                    inputStream.close();
            }
        }

        Engine.logEngine.trace("XSLT result:\n" + result);

        return result;
    } finally {
        Engine.logEngine.debug("XSLT process has finished");
        context.statistics.stop(t1);
    }
}

From source file:nl.nn.adapterframework.validation.xerces_2_11.XMLSchemaFactory.java

public Schema newSchema(Source[] schemas) throws SAXException {

    // this will let the loader store parsed Grammars into the pool.
    XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
    fXMLGrammarPoolWrapper.setGrammarPool(pool);

    XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
    InputStream inputStream;/*from www  .ja v  a2 s . c om*/
    Reader reader;
    for (int i = 0; i < schemas.length; ++i) {
        Source source = schemas[i];
        if (source instanceof StreamSource) {
            StreamSource streamSource = (StreamSource) source;
            String publicId = streamSource.getPublicId();
            String systemId = streamSource.getSystemId();
            inputStream = streamSource.getInputStream();
            reader = streamSource.getReader();
            XMLInputSource xmlInputSource = new XMLInputSource(publicId, systemId, null);
            xmlInputSource.setByteStream(inputStream);
            xmlInputSource.setCharacterStream(reader);
            xmlInputSources[i] = xmlInputSource;
        } else if (source instanceof SAXSource) {
            SAXSource saxSource = (SAXSource) source;
            InputSource inputSource = saxSource.getInputSource();
            if (inputSource == null) {
                throw new SAXException(JAXPValidationMessageFormatter
                        .formatMessage(fXMLSchemaLoader.getLocale(), "SAXSourceNullInputSource", null));
            }
            xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
        } else if (source instanceof DOMSource) {
            DOMSource domSource = (DOMSource) source;
            Node node = domSource.getNode();
            String systemID = domSource.getSystemId();
            xmlInputSources[i] = new DOMInputSource(node, systemID);
        }
        //            else if (source instanceof StAXSource) {
        //                StAXSource staxSource = (StAXSource) source;
        //                XMLEventReader eventReader = staxSource.getXMLEventReader();
        //                if (eventReader != null) {
        //                    xmlInputSources[i] = new StAXInputSource(eventReader);
        //                }
        //                else {
        //                    xmlInputSources[i] = new StAXInputSource(staxSource.getXMLStreamReader());
        //                }
        //            }
        else if (source == null) {
            throw new NullPointerException(JAXPValidationMessageFormatter
                    .formatMessage(fXMLSchemaLoader.getLocale(), "SchemaSourceArrayMemberNull", null));
        } else {
            throw new IllegalArgumentException(
                    JAXPValidationMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                            "SchemaFactorySourceUnrecognized", new Object[] { source.getClass().getName() }));
        }
    }

    try {
        fXMLSchemaLoader.loadGrammar(xmlInputSources);
    } catch (XNIException e) {
        // this should have been reported to users already.
        throw Util.toSAXException(e);
    } catch (IOException e) {
        // this hasn't been reported, so do so now.
        SAXParseException se = new SAXParseException(e.getMessage(), null, e);
        if (fErrorHandler != null) {
            fErrorHandler.error(se);
        }
        throw se; // and we must throw it.
    }

    // Clear reference to grammar pool.
    fXMLGrammarPoolWrapper.setGrammarPool(null);

    // Select Schema implementation based on grammar count.
    final int grammarCount = pool.getGrammarCount();
    AbstractXMLSchema schema = null;
    if (fUseGrammarPoolOnly) {
        throw new NotImplementedException("fUseGrammarPoolOnly");
        //            if (grammarCount > 1) {
        //                schema = new XMLSchemaHack(new ReadOnlyGrammarPool(pool));
        //            }
        //            else if (grammarCount == 1) {
        //                Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
        //                schema = new XMLSchemaHack(grammars[0]);
        //            }
        //            else {
        //                schema = new XMLSchemaHack();
        //            }
    } else {
        schema = new XMLSchema(new ReadOnlyGrammarPool(pool), false);
    }
    propagateFeatures(schema);
    return schema;
}

From source file:org.apache.fop.afp.util.DefaultFOPResourceAccessor.java

/** {@inheritDoc} */
public InputStream createInputStream(URI uri) throws IOException {
    //Step 1: resolve against local base URI --> URI
    URI resolved = resolveAgainstBase(uri);

    //Step 2: resolve against the user agent --> stream
    String base = (this.categoryBaseURI != null ? this.categoryBaseURI : this.userAgent.getBaseURL());
    Source src = userAgent.resolveURI(resolved.toASCIIString(), base);

    if (src == null) {
        throw new FileNotFoundException("Resource not found: " + uri.toASCIIString());
    } else if (src instanceof StreamSource) {
        StreamSource ss = (StreamSource) src;
        InputStream in = ss.getInputStream();
        if (in != null) {
            return in;
        }//from w  w  w  .j a  v a 2s . co  m
        if (ss.getReader() != null) {
            //Don't support reader, retry using system ID below
            IOUtils.closeQuietly(ss.getReader());
        }
    }
    URL url = new URL(src.getSystemId());
    return url.openStream();
}

From source file:org.apache.fop.fonts.FontInfoConfigurator.java

private static void closeSource(Source src) {
    if (src instanceof StreamSource) {
        StreamSource streamSource = (StreamSource) src;
        IOUtils.closeQuietly(streamSource.getInputStream());
        IOUtils.closeQuietly(streamSource.getReader());
    }/*from   w w  w .  j  a  v a2 s. c om*/
}

From source file:org.apache.fop.tools.EventProducerCollectorTask.java

/**
 * Updates the translation file with new entries for newly found event producer methods.
 * @param modelFile the model file to use
 * @throws IOException if an I/O error occurs
 *///  w ww.j  a v  a  2s .  c  o  m
protected void updateTranslationFile(File modelFile) throws IOException {
    try {
        boolean resultExists = getTranslationFile().exists();
        SAXTransformerFactory tFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

        //Generate fresh generated translation file as template
        Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm());
        StreamSource xslt1 = new StreamSource(getClass().getResourceAsStream(MODEL2TRANSLATION));
        if (xslt1.getInputStream() == null) {
            throw new FileNotFoundException(MODEL2TRANSLATION + " not found");
        }
        DOMResult domres = new DOMResult();
        Transformer transformer = tFactory.newTransformer(xslt1);
        transformer.transform(src, domres);
        final Node generated = domres.getNode();

        Node sourceDocument;
        if (resultExists) {
            //Load existing translation file into memory (because we overwrite it later)
            src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm());
            domres = new DOMResult();
            transformer = tFactory.newTransformer();
            transformer.transform(src, domres);
            sourceDocument = domres.getNode();
        } else {
            //Simply use generated as source document
            sourceDocument = generated;
        }

        //Generate translation file (with potentially new translations)
        src = new DOMSource(sourceDocument);

        //The following triggers a bug in older Xalan versions
        //Result res = new StreamResult(getTranslationFile());
        OutputStream out = new java.io.FileOutputStream(getTranslationFile());
        out = new java.io.BufferedOutputStream(out);
        Result res = new StreamResult(out);
        try {
            StreamSource xslt2 = new StreamSource(getClass().getResourceAsStream(MERGETRANSLATION));
            if (xslt2.getInputStream() == null) {
                throw new FileNotFoundException(MERGETRANSLATION + " not found");
            }
            transformer = tFactory.newTransformer(xslt2);
            transformer.setURIResolver(new URIResolver() {
                public Source resolve(String href, String base) throws TransformerException {
                    if ("my:dom".equals(href)) {
                        return new DOMSource(generated);
                    }
                    return null;
                }
            });
            if (resultExists) {
                transformer.setParameter("generated-url", "my:dom");
            }
            transformer.transform(src, res);
            if (resultExists) {
                log("Translation file updated: " + getTranslationFile());
            } else {
                log("Translation file generated: " + getTranslationFile());
            }
        } finally {
            IOUtils.closeQuietly(out);
        }
    } catch (TransformerException te) {
        throw new IOException(te.getMessage());
    }
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Parse an XML document located using an {@link InputSource} using the
 * pooled document builder.//from  w w w .j  ava  2s  . c  om
 */
public static Document sourceToDOM(Source inputSource) throws IOException {
    try {
        /*
        // Requires JDK 1.6+
        if (inputSource instanceof StAXSource) {
        StAXSource stax = (StAXSource) inputSource;
        //if (stax.getXMLEventReader() != null || sax.getXMLStreamReader() != null) {
        if (sax.getXMLStreamReader() != null) {
            return parse(stax.getXMLStreamReader());
        }
        }
        */
        if (inputSource instanceof SAXSource) {
            InputSource sax = ((SAXSource) inputSource).getInputSource();
            if (sax.getCharacterStream() != null || sax.getByteStream() != null) {
                return parse(((SAXSource) inputSource).getInputSource());
            }
        }
        if (inputSource instanceof DOMSource) {
            Node node = ((DOMSource) inputSource).getNode();
            if (node != null) {
                return toDOMDocument(node);
            }
        }
        if (inputSource instanceof StreamSource) {
            StreamSource stream = (StreamSource) inputSource;
            if (stream.getReader() != null || stream.getInputStream() != null) {
                return toDocumentFromStream((StreamSource) inputSource);
            }
        }
        DOMResult domresult = new DOMResult(newDocument());
        Transformer txer = getTransformer();
        txer.transform(inputSource, domresult);
        return (Document) domresult.getNode();
    } catch (SAXException e) {
        throwIOException(e);
    } catch (TransformerException e) {
        throwIOException(e);
    }
    throw new IllegalArgumentException("Cannot parse XML source: " + inputSource.getClass());
}