Search in sources :

Example 61 with TransformerConfigurationException

use of javax.xml.transform.TransformerConfigurationException in project robovm by robovm.

the class TransformerFactoryImpl method getAssociatedStylesheet.

/**
   * Get InputSource specification(s) that are associated with the
   * given document specified in the source param,
   * via the xml-stylesheet processing instruction
   * (see http://www.w3.org/TR/xml-stylesheet/), and that matches
   * the given criteria.  Note that it is possible to return several stylesheets
   * that match the criteria, in which case they are applied as if they were
   * a list of imports or cascades.
   *
   * <p>Note that DOM2 has it's own mechanism for discovering stylesheets.
   * Therefore, there isn't a DOM version of this method.</p>
   *
   *
   * @param source The XML source that is to be searched.
   * @param media The media attribute to be matched.  May be null, in which
   *              case the prefered templates will be used (i.e. alternate = no).
   * @param title The value of the title attribute to match.  May be null.
   * @param charset The value of the charset attribute to match.  May be null.
   *
   * @return A Source object capable of being used to create a Templates object.
   *
   * @throws TransformerConfigurationException
   */
public Source getAssociatedStylesheet(Source source, String media, String title, String charset) throws TransformerConfigurationException {
    String baseID;
    InputSource isource = null;
    Node node = null;
    XMLReader reader = null;
    if (source instanceof DOMSource) {
        DOMSource dsource = (DOMSource) source;
        node = dsource.getNode();
        baseID = dsource.getSystemId();
    } else {
        isource = SAXSource.sourceToInputSource(source);
        baseID = isource.getSystemId();
    }
    // What I try to do here is parse until the first startElement
    // is found, then throw a special exception in order to terminate 
    // the parse.
    StylesheetPIHandler handler = new StylesheetPIHandler(baseID, media, title, charset);
    // Use URIResolver. Patch from Dmitri Ilyin 
    if (m_uriResolver != null) {
        handler.setURIResolver(m_uriResolver);
    }
    try {
        if (null != node) {
            TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), baseID);
            walker.traverse(node);
        } else {
            // Use JAXP1.1 ( if possible )
            try {
                javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
                factory.setNamespaceAware(true);
                if (m_isSecureProcessing) {
                    try {
                        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (org.xml.sax.SAXException e) {
                    }
                }
                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();
            }
            // Need to set options!
            reader.setContentHandler(handler);
            reader.parse(isource);
        }
    } catch (StopParseException spe) {
    // OK, good.
    } catch (org.xml.sax.SAXException se) {
        throw new TransformerConfigurationException("getAssociatedStylesheets failed", se);
    } catch (IOException ioe) {
        throw new TransformerConfigurationException("getAssociatedStylesheets failed", ioe);
    }
    return handler.getAssociatedStylesheet();
}
Also used : InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Node(org.w3c.dom.Node) TreeWalker(org.apache.xml.utils.TreeWalker) IOException(java.io.IOException) StylesheetPIHandler(org.apache.xml.utils.StylesheetPIHandler) StopParseException(org.apache.xml.utils.StopParseException) XMLReader(org.xml.sax.XMLReader)

Example 62 with TransformerConfigurationException

use of javax.xml.transform.TransformerConfigurationException in project robovm by robovm.

the class TransformerFactoryImpl method processFromNode.

public javax.xml.transform.Templates processFromNode(Node node) throws TransformerConfigurationException {
    try {
        TemplatesHandler builder = newTemplatesHandler();
        TreeWalker walker = new TreeWalker(builder, new org.apache.xml.utils.DOM2Helper(), builder.getSystemId());
        walker.traverse(node);
        return builder.getTemplates();
    } catch (org.xml.sax.SAXException se) {
        if (m_errorListener != null) {
            try {
                m_errorListener.fatalError(new TransformerException(se));
            } catch (TransformerConfigurationException ex) {
                throw ex;
            } catch (TransformerException ex) {
                throw new TransformerConfigurationException(ex);
            }
            return null;
        } else {
            // se.printStackTrace();
            throw new TransformerConfigurationException(XSLMessages.createMessage(XSLTErrorResources.ER_PROCESSFROMNODE_FAILED, null), se);
        //"processFromNode failed", se);
        }
    } catch (TransformerConfigurationException tce) {
        // Assume it's already been reported to the error listener.
        throw tce;
    }/* catch (TransformerException tce)
    {
      // Assume it's already been reported to the error listener.
      throw new TransformerConfigurationException(tce.getMessage(), tce);
    }*/
     catch (Exception e) {
        if (m_errorListener != null) {
            try {
                m_errorListener.fatalError(new TransformerException(e));
            } catch (TransformerConfigurationException ex) {
                throw ex;
            } catch (TransformerException ex) {
                throw new TransformerConfigurationException(ex);
            }
            return null;
        } else {
            //"processFromNode failed",
            throw new TransformerConfigurationException(XSLMessages.createMessage(XSLTErrorResources.ER_PROCESSFROMNODE_FAILED, null), e);
        //e);
        }
    }
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) TreeWalker(org.apache.xml.utils.TreeWalker) TemplatesHandler(javax.xml.transform.sax.TemplatesHandler) TransformerException(javax.xml.transform.TransformerException) TransformerException(javax.xml.transform.TransformerException) StopParseException(org.apache.xml.utils.StopParseException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException)

Example 63 with TransformerConfigurationException

use of javax.xml.transform.TransformerConfigurationException in project robovm by robovm.

the class TransformerFactoryImpl method newTransformer.

/**
   * Process the source into a Transformer object.  Care must
   * be given to know that this object can not be used concurrently
   * in multiple threads.
   *
   * @param source An object that holds a URL, input stream, etc.
   *
   * @return A Transformer object capable of
   * being used for transformation purposes in a single thread.
   *
   * @throws TransformerConfigurationException May throw this during the parse when it
   *            is constructing the Templates object and fails.
   */
public Transformer newTransformer(Source source) throws TransformerConfigurationException {
    try {
        Templates tmpl = newTemplates(source);
        /* this can happen if an ErrorListener is present and it doesn't
         throw any exception in fatalError. 
         The spec says: "a Transformer must use this interface
         instead of throwing an exception" - the newTemplates() does
         that, and returns null.
      */
        if (tmpl == null)
            return null;
        Transformer transformer = tmpl.newTransformer();
        transformer.setURIResolver(m_uriResolver);
        return transformer;
    } catch (TransformerConfigurationException ex) {
        if (m_errorListener != null) {
            try {
                m_errorListener.fatalError(ex);
                // TODO: but the API promises to never return null...
                return null;
            } catch (TransformerConfigurationException ex1) {
                throw ex1;
            } catch (TransformerException ex1) {
                throw new TransformerConfigurationException(ex1);
            }
        }
        throw ex;
    }
}
Also used : Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Templates(javax.xml.transform.Templates) TransformerException(javax.xml.transform.TransformerException)

Example 64 with TransformerConfigurationException

use of javax.xml.transform.TransformerConfigurationException in project robovm by robovm.

the class TransformerFactoryImpl method newTransformerHandler.

/**
   * Get a TransformerHandler object that can process SAX
   * ContentHandler events into a Result, based on the Templates argument.
   *
   * @param templates The source of the transformation instructions.
   *
   * @return TransformerHandler ready to transform SAX events.
   * @throws TransformerConfigurationException
   */
public TransformerHandler newTransformerHandler(Templates templates) throws TransformerConfigurationException {
    try {
        TransformerImpl transformer = (TransformerImpl) templates.newTransformer();
        transformer.setURIResolver(m_uriResolver);
        TransformerHandler th = (TransformerHandler) transformer.getInputContentHandler(true);
        return th;
    } catch (TransformerConfigurationException ex) {
        if (m_errorListener != null) {
            try {
                m_errorListener.fatalError(ex);
                return null;
            } catch (TransformerConfigurationException ex1) {
                throw ex1;
            } catch (TransformerException ex1) {
                throw new TransformerConfigurationException(ex1);
            }
        }
        throw ex;
    }
}
Also used : TransformerImpl(org.apache.xalan.transformer.TransformerImpl) TransformerHandler(javax.xml.transform.sax.TransformerHandler) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 65 with TransformerConfigurationException

use of javax.xml.transform.TransformerConfigurationException in project robovm by robovm.

the class ProcessorLRE method startElement.

/**
   * Receive notification of the start of an element.
   *
   * @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
   * @param uri The Namespace URI, or an empty string.
   * @param localName The local name (without prefix), or empty string if not namespace processing.
   * @param rawName The qualified name (with prefix).
   * @param attributes The specified or defaulted attributes.
   */
public void startElement(StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes) throws org.xml.sax.SAXException {
    try {
        ElemTemplateElement p = handler.getElemTemplateElement();
        boolean excludeXSLDecl = false;
        boolean isLREAsStyleSheet = false;
        if (null == p) {
            // Literal Result Template as stylesheet.
            XSLTElementProcessor lreProcessor = handler.popProcessor();
            XSLTElementProcessor stylesheetProcessor = handler.getProcessorFor(Constants.S_XSLNAMESPACEURL, "stylesheet", "xsl:stylesheet");
            handler.pushProcessor(lreProcessor);
            Stylesheet stylesheet;
            try {
                stylesheet = getStylesheetRoot(handler);
            } catch (TransformerConfigurationException tfe) {
                throw new TransformerException(tfe);
            }
            // stylesheet.setDOMBackPointer(handler.getOriginatingNode());
            // ***** Note that we're assigning an empty locator. Is this necessary?
            SAXSourceLocator slocator = new SAXSourceLocator();
            Locator locator = handler.getLocator();
            if (null != locator) {
                slocator.setLineNumber(locator.getLineNumber());
                slocator.setColumnNumber(locator.getColumnNumber());
                slocator.setPublicId(locator.getPublicId());
                slocator.setSystemId(locator.getSystemId());
            }
            stylesheet.setLocaterInfo(slocator);
            stylesheet.setPrefixes(handler.getNamespaceSupport());
            handler.pushStylesheet(stylesheet);
            isLREAsStyleSheet = true;
            AttributesImpl stylesheetAttrs = new AttributesImpl();
            AttributesImpl lreAttrs = new AttributesImpl();
            int n = attributes.getLength();
            for (int i = 0; i < n; i++) {
                String attrLocalName = attributes.getLocalName(i);
                String attrUri = attributes.getURI(i);
                String value = attributes.getValue(i);
                if ((null != attrUri) && attrUri.equals(Constants.S_XSLNAMESPACEURL)) {
                    stylesheetAttrs.addAttribute(null, attrLocalName, attrLocalName, attributes.getType(i), attributes.getValue(i));
                } else if ((attrLocalName.startsWith("xmlns:") || attrLocalName.equals("xmlns")) && value.equals(Constants.S_XSLNAMESPACEURL)) {
                // ignore
                } else {
                    lreAttrs.addAttribute(attrUri, attrLocalName, attributes.getQName(i), attributes.getType(i), attributes.getValue(i));
                }
            }
            attributes = lreAttrs;
            // allowed on a stylesheet.
            try {
                stylesheetProcessor.setPropertiesFromAttributes(handler, "stylesheet", stylesheetAttrs, stylesheet);
            } catch (Exception e) {
                if (stylesheet.getDeclaredPrefixes() == null || !declaredXSLNS(stylesheet)) {
                    throw new org.xml.sax.SAXException(XSLMessages.createWarning(XSLTErrorResources.WG_OLD_XSLT_NS, null));
                } else {
                    throw new org.xml.sax.SAXException(e);
                }
            }
            handler.pushElemTemplateElement(stylesheet);
            ElemTemplate template = new ElemTemplate();
            if (slocator != null)
                template.setLocaterInfo(slocator);
            appendAndPush(handler, template);
            XPath rootMatch = new XPath("/", stylesheet, stylesheet, XPath.MATCH, handler.getStylesheetProcessor().getErrorListener());
            template.setMatch(rootMatch);
            // template.setDOMBackPointer(handler.getOriginatingNode());
            stylesheet.setTemplate(template);
            p = handler.getElemTemplateElement();
            excludeXSLDecl = true;
        }
        XSLTElementDef def = getElemDef();
        Class classObject = def.getClassObject();
        boolean isExtension = false;
        boolean isComponentDecl = false;
        boolean isUnknownTopLevel = false;
        while (null != p) {
            // System.out.println("Checking: "+p);
            if (p instanceof ElemLiteralResult) {
                ElemLiteralResult parentElem = (ElemLiteralResult) p;
                isExtension = parentElem.containsExtensionElementURI(uri);
            } else if (p instanceof Stylesheet) {
                Stylesheet parentElem = (Stylesheet) p;
                isExtension = parentElem.containsExtensionElementURI(uri);
                if ((false == isExtension) && (null != uri) && (uri.equals(Constants.S_BUILTIN_EXTENSIONS_URL) || uri.equals(Constants.S_BUILTIN_OLD_EXTENSIONS_URL))) {
                    isComponentDecl = true;
                } else {
                    isUnknownTopLevel = true;
                }
            }
            if (isExtension)
                break;
            p = p.getParentElem();
        }
        ElemTemplateElement elem = null;
        try {
            if (isExtension) {
                // System.out.println("Creating extension(1): "+uri);
                elem = new ElemExtensionCall();
            } else if (isComponentDecl) {
                elem = (ElemTemplateElement) classObject.newInstance();
            } else if (isUnknownTopLevel) {
                // TBD: Investigate, not sure about this.  -sb
                elem = (ElemTemplateElement) classObject.newInstance();
            } else {
                elem = (ElemTemplateElement) classObject.newInstance();
            }
            elem.setDOMBackPointer(handler.getOriginatingNode());
            elem.setLocaterInfo(handler.getLocator());
            elem.setPrefixes(handler.getNamespaceSupport(), excludeXSLDecl);
            if (elem instanceof ElemLiteralResult) {
                ((ElemLiteralResult) elem).setNamespace(uri);
                ((ElemLiteralResult) elem).setLocalName(localName);
                ((ElemLiteralResult) elem).setRawName(rawName);
                ((ElemLiteralResult) elem).setIsLiteralResultAsStylesheet(isLREAsStyleSheet);
            }
        } catch (InstantiationException ie) {
            //"Failed creating ElemLiteralResult instance!", ie);
            handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT, null, ie);
        } catch (IllegalAccessException iae) {
            //"Failed creating ElemLiteralResult instance!", iae);
            handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT, null, iae);
        }
        setPropertiesFromAttributes(handler, rawName, attributes, elem);
        // bit of a hack here...
        if (!isExtension && (elem instanceof ElemLiteralResult)) {
            isExtension = ((ElemLiteralResult) elem).containsExtensionElementURI(uri);
            if (isExtension) {
                // System.out.println("Creating extension(2): "+uri);
                elem = new ElemExtensionCall();
                elem.setLocaterInfo(handler.getLocator());
                elem.setPrefixes(handler.getNamespaceSupport());
                ((ElemLiteralResult) elem).setNamespace(uri);
                ((ElemLiteralResult) elem).setLocalName(localName);
                ((ElemLiteralResult) elem).setRawName(rawName);
                setPropertiesFromAttributes(handler, rawName, attributes, elem);
            }
        }
        appendAndPush(handler, elem);
    } catch (TransformerException te) {
        throw new org.xml.sax.SAXException(te);
    }
}
Also used : XPath(org.apache.xpath.XPath) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ElemTemplate(org.apache.xalan.templates.ElemTemplate) ElemTemplateElement(org.apache.xalan.templates.ElemTemplateElement) Stylesheet(org.apache.xalan.templates.Stylesheet) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Locator(org.xml.sax.Locator) SAXSourceLocator(org.apache.xml.utils.SAXSourceLocator) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ElemLiteralResult(org.apache.xalan.templates.ElemLiteralResult) ElemExtensionCall(org.apache.xalan.templates.ElemExtensionCall) SAXSourceLocator(org.apache.xml.utils.SAXSourceLocator) TransformerException(javax.xml.transform.TransformerException)

Aggregations

TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)93 TransformerException (javax.xml.transform.TransformerException)62 Transformer (javax.xml.transform.Transformer)52 StreamResult (javax.xml.transform.stream.StreamResult)49 DOMSource (javax.xml.transform.dom.DOMSource)42 IOException (java.io.IOException)35 TransformerFactory (javax.xml.transform.TransformerFactory)33 StreamSource (javax.xml.transform.stream.StreamSource)23 SAXException (org.xml.sax.SAXException)21 StringWriter (java.io.StringWriter)17 Source (javax.xml.transform.Source)16 TransformerHandler (javax.xml.transform.sax.TransformerHandler)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)12 Document (org.w3c.dom.Document)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 InputStream (java.io.InputStream)10 Node (org.w3c.dom.Node)10 File (java.io.File)9 Result (javax.xml.transform.Result)9