Search in sources :

Example 61 with SAXSource

use of javax.xml.transform.sax.SAXSource in project j2objc by google.

the class ProcessorInclude method parse.

/**
   * Set off a new parse for an included or imported stylesheet.  This will 
   * set the {@link StylesheetHandler} to a new state, and recurse in with 
   * a new set of parse events.  Once this function returns, the state of 
   * the StylesheetHandler should be restored.
   *
   * @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
   * @param uri The Namespace URI, which should be the XSLT namespace.
   * @param localName The local name (without prefix), which should be "include" or "import".
   * @param rawName The qualified name (with prefix).
   * @param attributes The list of attributes on the xsl:include or xsl:import element.
   *
   * @throws org.xml.sax.SAXException Any SAX exception, possibly
   *            wrapping another exception.
   */
protected void parse(StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes) throws org.xml.sax.SAXException {
    TransformerFactoryImpl processor = handler.getStylesheetProcessor();
    URIResolver uriresolver = processor.getURIResolver();
    try {
        Source source = null;
        if (null != uriresolver) {
            // There is a user provided URI resolver.
            // At the startElement() call we would
            // have tried to obtain a Source from it
            // which we now retrieve
            source = handler.peekSourceFromURIResolver();
            if (null != source && source instanceof DOMSource) {
                Node node = ((DOMSource) source).getNode();
                // There is a user provided URI resolver.
                // At the startElement() call we would
                // have already pushed the system ID, obtained
                // from either the source.getSystemId(), if non-null
                // or from SystemIDResolver.getAbsoluteURI() as a backup
                // which we now retrieve.
                String systemId = handler.peekImportURL();
                // stylesheet module onto the stack.
                if (systemId != null)
                    handler.pushBaseIndentifier(systemId);
                TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), systemId);
                try {
                    walker.traverse(node);
                } catch (org.xml.sax.SAXException se) {
                    throw new TransformerException(se);
                }
                if (systemId != null)
                    handler.popBaseIndentifier();
                return;
            }
        }
        if (null == source) {
            String absURL = SystemIDResolver.getAbsoluteURI(getHref(), handler.getBaseIdentifier());
            source = new StreamSource(absURL);
        }
        // possible callback to a class that over-rides this method.
        source = processSource(handler, source);
        XMLReader reader = null;
        if (source instanceof SAXSource) {
            SAXSource saxSource = (SAXSource) source;
            // may be null
            reader = saxSource.getXMLReader();
        }
        InputSource inputSource = SAXSource.sourceToInputSource(source);
        if (null == reader) {
            // Use JAXP1.1 ( if possible )
            try {
                javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
                factory.setNamespaceAware(true);
                if (handler.getStylesheetProcessor().isSecureProcessing()) {
                    try {
                        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (org.xml.sax.SAXException se) {
                    }
                }
                javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
                reader = jaxpParser.getXMLReader();
            } catch (javax.xml.parsers.ParserConfigurationException ex) {
                throw new org.xml.sax.SAXException(ex);
            } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
                throw new org.xml.sax.SAXException(ex1.toString());
            } catch (NoSuchMethodError ex2) {
            } catch (AbstractMethodError ame) {
            }
        }
        if (null == reader)
            reader = XMLReaderFactory.createXMLReader();
        if (null != reader) {
            reader.setContentHandler(handler);
            // Push the absolute URI of the included/imported
            // stylesheet module onto the stack.
            handler.pushBaseIndentifier(inputSource.getSystemId());
            try {
                reader.parse(inputSource);
            } finally {
                handler.popBaseIndentifier();
            }
        }
    } catch (IOException ioe) {
        handler.error(XSLTErrorResources.ER_IOEXCEPTION, new Object[] { getHref() }, ioe);
    } catch (TransformerException te) {
        handler.error(te.getMessage(), te);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) InputSource(org.xml.sax.InputSource) Node(org.w3c.dom.Node) URIResolver(javax.xml.transform.URIResolver) DOMSource(javax.xml.transform.dom.DOMSource) InputSource(org.xml.sax.InputSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SAXSource(javax.xml.transform.sax.SAXSource) TransformerException(javax.xml.transform.TransformerException) XMLReader(org.xml.sax.XMLReader) StreamSource(javax.xml.transform.stream.StreamSource) TreeWalker(org.apache.xml.utils.TreeWalker) IOException(java.io.IOException) SAXSource(javax.xml.transform.sax.SAXSource)

Example 62 with SAXSource

use of javax.xml.transform.sax.SAXSource in project j2objc by google.

the class TransformerImpl method transform.

/**
   * Process the source tree to SAX parse events.
   * @param source  The input for the source tree.
   * @param shouldRelease  Flag indicating whether to release DTMManager.
   *
   * @throws TransformerException
   */
public void transform(Source source, boolean shouldRelease) throws TransformerException {
    try {
        // here or in reset(). -is  
        if (getXPathContext().getNamespaceContext() == null) {
            getXPathContext().setNamespaceContext(getStylesheet());
        }
        String base = source.getSystemId();
        // If no systemID of the source, use the base of the stylesheet.
        if (null == base) {
            base = m_stylesheetRoot.getBaseIdentifier();
        }
        // As a last resort, use the current user dir.
        if (null == base) {
            String currentDir = "";
            try {
                currentDir = System.getProperty("user.dir");
            }// user.dir not accessible from applet
             catch (SecurityException se) {
            }
            if (currentDir.startsWith(java.io.File.separator))
                base = "file://" + currentDir;
            else
                base = "file:///" + currentDir;
            base = base + java.io.File.separatorChar + source.getClass().getName();
        }
        setBaseURLOfSource(base);
        DTMManager mgr = m_xcontext.getDTMManager();
        /*
       * According to JAXP1.2, new SAXSource()/StreamSource()
       * should create an empty input tree, with a default root node. 
       * new DOMSource()creates an empty document using DocumentBuilder.
       * newDocument(); Use DocumentBuilder.newDocument() for all 3 situations,
       * since there is no clear spec. how to create an empty tree when
       * both SAXSource() and StreamSource() are used.
       */
        if ((source instanceof StreamSource && source.getSystemId() == null && ((StreamSource) source).getInputStream() == null && ((StreamSource) source).getReader() == null) || (source instanceof SAXSource && ((SAXSource) source).getInputSource() == null && ((SAXSource) source).getXMLReader() == null) || (source instanceof DOMSource && ((DOMSource) source).getNode() == null)) {
            try {
                DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = builderF.newDocumentBuilder();
                String systemID = source.getSystemId();
                source = new DOMSource(builder.newDocument());
                // Copy system ID from original, empty Source to new Source
                if (systemID != null) {
                    source.setSystemId(systemID);
                }
            } catch (ParserConfigurationException e) {
                fatalError(e);
            }
        }
        DTM dtm = mgr.getDTM(source, false, this, true, true);
        dtm.setDocumentBaseURI(base);
        // %REVIEW% I have to think about this. -sb
        boolean hardDelete = true;
        try {
            // NOTE: This will work because this is _NOT_ a shared DTM, and thus has
            // only a single Document node. If it could ever be an RTF or other
            // shared DTM, look at dtm.getDocumentRoot(nodeHandle).
            this.transformNode(dtm.getDocument());
        } finally {
            if (shouldRelease)
                mgr.release(dtm, hardDelete);
        }
        // Kick off the parse.  When the ContentHandler gets 
        // the startDocument event, it will call transformNode( node ).
        // reader.parse( xmlSource );
        // This has to be done to catch exceptions thrown from 
        // the transform thread spawned by the STree handler.
        Exception e = getExceptionThrown();
        if (null != e) {
            if (e instanceof javax.xml.transform.TransformerException) {
                throw (javax.xml.transform.TransformerException) e;
            } else if (e instanceof org.apache.xml.utils.WrappedRuntimeException) {
                fatalError(((org.apache.xml.utils.WrappedRuntimeException) e).getException());
            } else {
                throw new javax.xml.transform.TransformerException(e);
            }
        } else if (null != m_serializationHandler) {
            m_serializationHandler.endDocument();
        }
    } catch (org.apache.xml.utils.WrappedRuntimeException wre) {
        Throwable throwable = wre.getException();
        while (throwable instanceof org.apache.xml.utils.WrappedRuntimeException) {
            throwable = ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
        }
        fatalError(throwable);
    }// Patch attributed to David Eisenberg <david@catcode.com>
     catch (org.xml.sax.SAXParseException spe) {
        fatalError(spe);
    } catch (org.xml.sax.SAXException se) {
        m_errorHandler.fatalError(new TransformerException(se));
    } finally {
        m_hasTransformThreadErrorCatcher = false;
        // This looks to be redundent to the one done in TransformNode.
        reset();
    }
}
Also used : DTMManager(org.apache.xml.dtm.DTMManager) DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerException(javax.xml.transform.TransformerException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException) StreamSource(javax.xml.transform.stream.StreamSource) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXSource(javax.xml.transform.sax.SAXSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXException(org.xml.sax.SAXException) DTM(org.apache.xml.dtm.DTM)

Example 63 with SAXSource

use of javax.xml.transform.sax.SAXSource in project translationstudio8 by heartsome.

the class XSLTransformationDialog method transform.

/**
	 * 转换文件
	 * @param strSourcePath
	 *            源文件路径
	 * @param strXSLPath
	 *            XSL 文件路径
	 * @param strTargetPath
	 *            转变文件路径
	 * @throws Exception
	 *             ;
	 */
private void transform(String strSourcePath, String strXSLPath, String strTargetPath) throws Exception {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    String catalogPath = PluginUtil.getCataloguePath();
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // Standard way of creating an XMLReader in JAXP 1.1.
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        // Very important!
        pfactory.setNamespaceAware(true);
        // Turn on validation.
        // pfactory.setValidating(true);
        // Get an XMLReader.
        XMLReader reader = pfactory.newSAXParser().getXMLReader();
        reader.setEntityResolver(new Catalogue(catalogPath));
        // Instantiate an error handler (see the Handler inner class below)
        // that will report any
        // errors or warnings that occur as the XMLReader is parsing the XML
        // input.
        reader.setErrorHandler(new HSErrorHandler());
        // Standard way of creating a transformer from a URL.
        Transformer t = tfactory.newTransformer(new StreamSource(strXSLPath));
        // Specify a SAXSource that takes both an XMLReader and a URL.
        SAXSource source = new SAXSource(reader, new InputSource(strSourcePath));
        // Transform to a file.
        t.transform(source, new StreamResult(strTargetPath));
    } else {
        //$NON-NLS-1$
        throw new Exception(Messages.getString("dialog.XSLTransformationDialog.msg6"));
    }
}
Also used : Catalogue(net.heartsome.xml.Catalogue) HSErrorHandler(net.heartsome.xml.HSErrorHandler) InputSource(org.xml.sax.InputSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) SAXSource(javax.xml.transform.sax.SAXSource) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) XMLReader(org.xml.sax.XMLReader) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 64 with SAXSource

use of javax.xml.transform.sax.SAXSource in project hazelcast by hazelcast.

the class AbstractXmlConfigHelper method schemaValidation.

protected void schemaValidation(Document doc) throws Exception {
    ArrayList<StreamSource> schemas = new ArrayList<StreamSource>();
    InputStream inputStream = null;
    String schemaLocation = doc.getDocumentElement().getAttribute("xsi:schemaLocation");
    schemaLocation = schemaLocation.replaceAll("^ +| +$| (?= )", "");
    // get every two pair. every pair includes namespace and uri
    String[] xsdLocations = schemaLocation.split("(?<!\\G\\S+)\\s");
    for (String xsdLocation : xsdLocations) {
        if (xsdLocation.isEmpty()) {
            continue;
        }
        String namespace = xsdLocation.split('[' + LINE_SEPARATOR + " ]+")[0];
        String uri = xsdLocation.split('[' + LINE_SEPARATOR + " ]+")[1];
        // if this is hazelcast namespace but location is different log only warning
        if (namespace.equals(xmlns) && !uri.endsWith(hazelcastSchemaLocation)) {
            LOGGER.warning("Name of the hazelcast schema location incorrect using default");
        }
        // if this is not hazelcast namespace then try to load from uri
        if (!namespace.equals(xmlns)) {
            inputStream = loadSchemaFile(uri);
            schemas.add(new StreamSource(inputStream));
        }
    }
    // include hazelcast schema
    schemas.add(new StreamSource(getClass().getClassLoader().getResourceAsStream(hazelcastSchemaLocation)));
    // document to InputStream conversion
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Source xmlSource = new DOMSource(doc);
    Result outputTarget = new StreamResult(outputStream);
    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
    InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
    // schema validation
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
    Validator validator = schema.newValidator();
    try {
        SAXSource source = new SAXSource(new InputSource(is));
        validator.validate(source);
    } catch (Exception e) {
        throw new InvalidConfigurationException(e.getMessage());
    } finally {
        for (StreamSource source : schemas) {
            closeResource(source.getInputStream());
        }
        closeResource(inputStream);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) DOMSource(javax.xml.transform.dom.DOMSource) InputSource(org.xml.sax.InputSource) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) Schema(javax.xml.validation.Schema) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) ParseException(java.text.ParseException) NoSuchElementException(java.util.NoSuchElementException) HazelcastException(com.hazelcast.core.HazelcastException) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) SAXSource(javax.xml.transform.sax.SAXSource) ByteArrayInputStream(java.io.ByteArrayInputStream) Validator(javax.xml.validation.Validator)

Example 65 with SAXSource

use of javax.xml.transform.sax.SAXSource in project jersey by jersey.

the class WadlUtils method unmarshall.

/**
     * Unmarshal a jaxb bean into a type of {@code resultClass} from the given {@code inputStream}.
     *
     * @param inputStream Input stream that contains input xml that should be processed.
     * @param saxParserFactory Sax parser factory for unmarshalling xml.
     * @param resultClass Class of the result bean into which the content of {@code inputStream} should be unmarshalled.
     * @param <T> Type of the result jaxb bean.
     * @return Unmarshalled jaxb bean.
     *
     * @throws JAXBException In case of jaxb problem.
     * @throws ParserConfigurationException In case of problem with parsing xml.
     * @throws SAXException In case of problem with parsing xml.
     */
public static <T> T unmarshall(InputStream inputStream, SAXParserFactory saxParserFactory, Class<T> resultClass) throws JAXBException, ParserConfigurationException, SAXException {
    JAXBContext jaxbContext = null;
    try {
        jaxbContext = JAXBContext.newInstance(resultClass);
    } catch (JAXBException ex) {
        throw new ProcessingException(LocalizationMessages.ERROR_WADL_JAXB_CONTEXT(), ex);
    }
    final SAXParser saxParser = saxParserFactory.newSAXParser();
    SAXSource source = new SAXSource(saxParser.getXMLReader(), new InputSource(inputStream));
    final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    final Object result = unmarshaller.unmarshal(source);
    return resultClass.cast(result);
}
Also used : InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) JAXBException(javax.xml.bind.JAXBException) SAXParser(javax.xml.parsers.SAXParser) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) ProcessingException(javax.ws.rs.ProcessingException)

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