Search in sources :

Example 96 with SAXSource

use of javax.xml.transform.sax.SAXSource in project geode by apache.

the class CacheXmlGenerator method generate.

/**
   * Writes the generator's state to pw
   */
private void generate(PrintWriter pw) {
    // XML text
    try {
        Source src = new SAXSource(this, new InputSource());
        Result res = new StreamResult(pw);
        TransformerFactory xFactory = TransformerFactory.newInstance();
        Transformer xform = xFactory.newTransformer();
        xform.setOutputProperty(OutputKeys.METHOD, "xml");
        xform.setOutputProperty(OutputKeys.INDENT, "yes");
        if (!useSchema) {
            // set the doctype system and public ids from version for older DTDs.
            xform.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, version.getSystemId());
            xform.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, version.getPublicId());
        }
        xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        xform.transform(src, res);
        pw.flush();
    } catch (Exception ex) {
        RuntimeException ex2 = new RuntimeException(LocalizedStrings.CacheXmlGenerator_AN_EXCEPTION_WAS_THROWN_WHILE_GENERATING_XML.toLocalizedString());
        ex2.initCause(ex);
        throw ex2;
    }
}
Also used : InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) InternalGemFireException(org.apache.geode.InternalGemFireException) IOException(java.io.IOException) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) SAXException(org.xml.sax.SAXException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result)

Example 97 with SAXSource

use of javax.xml.transform.sax.SAXSource in project jmeter by apache.

the class XPathUtil method formatXml.

/**
     * Formats XML
     * @param xml string to format
     * @return String formatted XML
     */
public static String formatXml(String xml) {
    try {
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Source xmlSource = new SAXSource(new InputSource(new StringReader(xml)));
        StringWriter stringWriter = new StringWriter();
        StreamResult res = new StreamResult(stringWriter);
        serializer.transform(xmlSource, res);
        return stringWriter.toString();
    } catch (Exception e) {
        return xml;
    }
}
Also used : InputSource(org.xml.sax.InputSource) Transformer(javax.xml.transform.Transformer) SAXSource(javax.xml.transform.sax.SAXSource) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) StringReader(java.io.StringReader) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 98 with SAXSource

use of javax.xml.transform.sax.SAXSource in project lucene-solr by apache.

the class XMLLoader method load.

@Override
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream, UpdateRequestProcessor processor) throws Exception {
    final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());
    InputStream is = null;
    XMLStreamReader parser = null;
    String tr = req.getParams().get(CommonParams.TR, null);
    if (tr != null) {
        if (req.getCore().getCoreDescriptor().isConfigSetTrusted() == false) {
            throw new SolrException(ErrorCode.UNAUTHORIZED, "The configset for this collection was uploaded without any authentication in place," + " and this operation is not available for collections with untrusted configsets. To use this feature, re-upload the configset" + " after enabling authentication and authorization.");
        }
        final Transformer t = getTransformer(tr, req);
        final DOMResult result = new DOMResult();
        // an internal result DOM tree, we just access it directly as input for StAX):
        try {
            is = stream.getStream();
            final InputSource isrc = new InputSource(is);
            isrc.setEncoding(charset);
            final XMLReader xmlr = saxFactory.newSAXParser().getXMLReader();
            xmlr.setErrorHandler(xmllog);
            xmlr.setEntityResolver(EmptyEntityResolver.SAX_INSTANCE);
            final SAXSource source = new SAXSource(xmlr, isrc);
            t.transform(source, result);
        } catch (TransformerException te) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te);
        } finally {
            IOUtils.closeQuietly(is);
        }
        // second step: feed the intermediate DOM tree into StAX parser:
        try {
            parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode()));
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
        }
    } else // Normal XML Loader
    {
        try {
            is = stream.getStream();
            if (log.isTraceEnabled()) {
                final byte[] body = IOUtils.toByteArray(is);
                // TODO: The charset may be wrong, as the real charset is later
                // determined by the XML parser, the content-type is only used as a hint!
                log.trace("body", new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset));
                IOUtils.closeQuietly(is);
                is = new ByteArrayInputStream(body);
            }
            parser = (charset == null) ? inputFactory.createXMLStreamReader(is) : inputFactory.createXMLStreamReader(is, charset);
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
            IOUtils.closeQuietly(is);
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) Transformer(javax.xml.transform.Transformer) DOMResult(javax.xml.transform.dom.DOMResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SAXSource(javax.xml.transform.sax.SAXSource) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) SolrException(org.apache.solr.common.SolrException) XMLReader(org.xml.sax.XMLReader) TransformerException(javax.xml.transform.TransformerException)

Example 99 with SAXSource

use of javax.xml.transform.sax.SAXSource in project tomee by apache.

the class JaxbJavaee method unmarshalTaglib.

/**
     * Convert the namespaceURI in the input to the taglib URI, do not validate the xml, and read in a T.
     *
     * @param type Class of object to be read in
     * @param in   input stream to read
     * @param <T>  class of object to be returned
     * @return a T read from the input stream
     * @throws ParserConfigurationException is the SAX parser can not be configured
     * @throws SAXException                 if there is an xml problem
     * @throws JAXBException                if the xml cannot be marshalled into a T.
     */
public static <T> Object unmarshalTaglib(final Class<T> type, final InputStream in) throws ParserConfigurationException, SAXException, JAXBException {
    final InputSource inputSource = new InputSource(in);
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    final SAXParser parser = factory.newSAXParser();
    final JAXBContext ctx = JaxbJavaee.getContext(type);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {

        public boolean handleEvent(final ValidationEvent validationEvent) {
            System.out.println(validationEvent);
            return false;
        }
    });
    final JaxbJavaee.TaglibNamespaceFilter xmlFilter = new JaxbJavaee.TaglibNamespaceFilter(parser.getXMLReader());
    xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
    final SAXSource source = new SAXSource(xmlFilter, inputSource);
    currentPublicId.set(new TreeSet<String>());
    try {
        return unmarshaller.unmarshal(source);
    } finally {
        currentPublicId.set(null);
    }
}
Also used : InputSource(org.xml.sax.InputSource) ValidationEventHandler(javax.xml.bind.ValidationEventHandler) JAXBContext(javax.xml.bind.JAXBContext) SAXSource(javax.xml.transform.sax.SAXSource) ValidationEvent(javax.xml.bind.ValidationEvent) SAXParser(javax.xml.parsers.SAXParser) Unmarshaller(javax.xml.bind.Unmarshaller) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 100 with SAXSource

use of javax.xml.transform.sax.SAXSource in project tomee by apache.

the class JaxbJavaee method unmarshalJavaee.

/**
     * Convert the namespaceURI in the input to the javaee URI, do not validate the xml, and read in a T.
     *
     * @param type Class of object to be read in
     * @param in   input stream to read
     * @param <T>  class of object to be returned
     * @return a T read from the input stream
     * @throws ParserConfigurationException is the SAX parser can not be configured
     * @throws SAXException                 if there is an xml problem
     * @throws JAXBException                if the xml cannot be marshalled into a T.
     */
public static <T> Object unmarshalJavaee(final Class<T> type, final InputStream in) throws ParserConfigurationException, SAXException, JAXBException {
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    final SAXParser parser = factory.newSAXParser();
    final JAXBContext ctx = JaxbJavaee.getContext(type);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {

        public boolean handleEvent(final ValidationEvent validationEvent) {
            final String verbose = System.getProperty("openejb.validation.output.level");
            if (verbose != null && "VERBOSE".equals(verbose.toUpperCase(Locale.ENGLISH))) {
                System.err.println(validationEvent);
            }
            return false;
        }
    });
    final JavaeeNamespaceFilter xmlFilter = new JavaeeNamespaceFilter(parser.getXMLReader());
    xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
    // unmarshall
    final SAXSource source = new SAXSource(xmlFilter, new InputSource(in));
    currentPublicId.set(new TreeSet<String>());
    try {
        final JAXBElement<T> element = unmarshaller.unmarshal(source, type);
        return element.getValue();
    } finally {
        currentPublicId.set(null);
    }
}
Also used : ValidationEventHandler(javax.xml.bind.ValidationEventHandler) InputSource(org.xml.sax.InputSource) JAXBContext(javax.xml.bind.JAXBContext) SAXSource(javax.xml.transform.sax.SAXSource) ValidationEvent(javax.xml.bind.ValidationEvent) SAXParser(javax.xml.parsers.SAXParser) Unmarshaller(javax.xml.bind.Unmarshaller) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

SAXSource (javax.xml.transform.sax.SAXSource)111 InputSource (org.xml.sax.InputSource)81 XMLReader (org.xml.sax.XMLReader)38 Source (javax.xml.transform.Source)28 StreamSource (javax.xml.transform.stream.StreamSource)28 DOMSource (javax.xml.transform.dom.DOMSource)27 SAXException (org.xml.sax.SAXException)26 TransformerException (javax.xml.transform.TransformerException)24 SAXParserFactory (javax.xml.parsers.SAXParserFactory)20 Unmarshaller (javax.xml.bind.Unmarshaller)17 SAXParser (javax.xml.parsers.SAXParser)17 Transformer (javax.xml.transform.Transformer)17 StreamResult (javax.xml.transform.stream.StreamResult)16 Test (org.junit.Test)16 StringReader (java.io.StringReader)15 IOException (java.io.IOException)14 JAXBContext (javax.xml.bind.JAXBContext)14 ByteArrayInputStream (java.io.ByteArrayInputStream)12 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)11 ValidationEvent (javax.xml.bind.ValidationEvent)10