Search in sources :

Example 76 with TransformerException

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

the class ToStream method setProp.

void setProp(String name, String val, boolean defaultVal) {
    if (val != null) {
        char first = getFirstCharLocName(name);
        switch(first) {
            case 'c':
                if (OutputKeys.CDATA_SECTION_ELEMENTS.equals(name)) {
                    String cdataSectionNames = val;
                    addCdataSectionElements(cdataSectionNames);
                }
                break;
            case 'd':
                if (OutputKeys.DOCTYPE_SYSTEM.equals(name)) {
                    this.m_doctypeSystem = val;
                } else if (OutputKeys.DOCTYPE_PUBLIC.equals(name)) {
                    this.m_doctypePublic = val;
                    if (val.startsWith("-//W3C//DTD XHTML"))
                        m_spaceBeforeClose = true;
                }
                break;
            case 'e':
                String newEncoding = val;
                if (OutputKeys.ENCODING.equals(name)) {
                    String possible_encoding = Encodings.getMimeEncoding(val);
                    if (possible_encoding != null) {
                        // if the encoding is being set, try to get the
                        // preferred
                        // mime-name and set it too.
                        super.setProp("mime-name", possible_encoding, defaultVal);
                    }
                    final String oldExplicitEncoding = getOutputPropertyNonDefault(OutputKeys.ENCODING);
                    final String oldDefaultEncoding = getOutputPropertyDefault(OutputKeys.ENCODING);
                    if ((defaultVal && (oldDefaultEncoding == null || !oldDefaultEncoding.equalsIgnoreCase(newEncoding))) || (!defaultVal && (oldExplicitEncoding == null || !oldExplicitEncoding.equalsIgnoreCase(newEncoding)))) {
                        // We are trying to change the default or the non-default setting of the encoding to a different value
                        // from what it was
                        EncodingInfo encodingInfo = Encodings.getEncodingInfo(newEncoding);
                        if (newEncoding != null && encodingInfo.name == null) {
                            // We tried to get an EncodingInfo for Object for the given
                            // encoding, but it came back with an internall null name
                            // so the encoding is not supported by the JDK, issue a message.
                            final String msg = Utils.messages.createMessage(MsgKey.ER_ENCODING_NOT_SUPPORTED, new Object[] { newEncoding });
                            final String msg2 = "Warning: encoding \"" + newEncoding + "\" not supported, using " + Encodings.DEFAULT_MIME_ENCODING;
                            try {
                                // Prepare to issue the warning message
                                final Transformer tran = super.getTransformer();
                                if (tran != null) {
                                    final ErrorListener errHandler = tran.getErrorListener();
                                    // Issue the warning message
                                    if (null != errHandler && m_sourceLocator != null) {
                                        errHandler.warning(new TransformerException(msg, m_sourceLocator));
                                        errHandler.warning(new TransformerException(msg2, m_sourceLocator));
                                    } else {
                                        System.out.println(msg);
                                        System.out.println(msg2);
                                    }
                                } else {
                                    System.out.println(msg);
                                    System.out.println(msg2);
                                }
                            } catch (Exception e) {
                            }
                            // We said we are using UTF-8, so use it
                            newEncoding = Encodings.DEFAULT_MIME_ENCODING;
                            // to store the modified value into the properties a little later
                            val = Encodings.DEFAULT_MIME_ENCODING;
                            encodingInfo = Encodings.getEncodingInfo(newEncoding);
                        }
                        // as the non-default value is already the one to use.
                        if (defaultVal == false || oldExplicitEncoding == null) {
                            m_encodingInfo = encodingInfo;
                            if (newEncoding != null)
                                m_isUTF8 = newEncoding.equals(Encodings.DEFAULT_MIME_ENCODING);
                            // if there was a previously set OutputStream
                            OutputStream os = getOutputStream();
                            if (os != null) {
                                Writer w = getWriter();
                                // If the writer was previously set, but
                                // set by the user, or if the new encoding is the same
                                // as the old encoding, skip this block
                                String oldEncoding = getOutputProperty(OutputKeys.ENCODING);
                                if ((w == null || !m_writer_set_by_user) && !newEncoding.equalsIgnoreCase(oldEncoding)) {
                                    // Make the change of encoding in our internal
                                    // table, then call setOutputStreamInternal
                                    // which will stomp on the old Writer (if any)
                                    // with a new Writer with the new encoding.
                                    super.setProp(name, val, defaultVal);
                                    setOutputStreamInternal(os, false);
                                }
                            }
                        }
                    }
                }
                break;
            case 'i':
                if (OutputPropertiesFactory.S_KEY_INDENT_AMOUNT.equals(name)) {
                    setIndentAmount(Integer.parseInt(val));
                } else if (OutputKeys.INDENT.equals(name)) {
                    boolean b = "yes".equals(val) ? true : false;
                    m_doIndent = b;
                }
                break;
            case 'l':
                if (OutputPropertiesFactory.S_KEY_LINE_SEPARATOR.equals(name)) {
                    m_lineSep = val.toCharArray();
                    m_lineSepLen = m_lineSep.length;
                }
                break;
            case 'm':
                if (OutputKeys.MEDIA_TYPE.equals(name)) {
                    m_mediatype = val;
                }
                break;
            case 'o':
                if (OutputKeys.OMIT_XML_DECLARATION.equals(name)) {
                    boolean b = "yes".equals(val) ? true : false;
                    this.m_shouldNotWriteXMLHeader = b;
                }
                break;
            case 's':
                // if standalone was explicitly specified
                if (OutputKeys.STANDALONE.equals(name)) {
                    if (defaultVal) {
                        setStandaloneInternal(val);
                    } else {
                        m_standaloneWasSpecified = true;
                        setStandaloneInternal(val);
                    }
                }
                break;
            case 'v':
                if (OutputKeys.VERSION.equals(name)) {
                    m_version = val;
                }
                break;
            default:
                break;
        }
        super.setProp(name, val, defaultVal);
    }
}
Also used : ErrorListener(javax.xml.transform.ErrorListener) Transformer(javax.xml.transform.Transformer) OutputStream(java.io.OutputStream) TransformerException(javax.xml.transform.TransformerException) EmptyStackException(java.util.EmptyStackException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) WrappedRuntimeException(org.apache.xml.serializer.utils.WrappedRuntimeException) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 77 with TransformerException

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

the class ClonerToResultTree method cloneToResultTree.

//  /**
//   * Clone an element with or without children.
//   * TODO: Fix or figure out node clone failure!
//   * the error condition is severe enough to halt processing.
//   *
//   * @param node The node to clone
//   * @param shouldCloneAttributes Flag indicating whether to 
//   * clone children attributes
//   * 
//   * @throws TransformerException
//   */
//  public void cloneToResultTree(int node, boolean shouldCloneAttributes)
//    throws TransformerException
//  {
//
//    try
//    {
//      XPathContext xctxt = m_transformer.getXPathContext();
//      DTM dtm = xctxt.getDTM(node);
//
//      int type = dtm.getNodeType(node);
//      switch (type)
//      {
//      case DTM.TEXT_NODE :
//        dtm.dispatchCharactersEvents(node, m_rth, false);
//        break;
//      case DTM.DOCUMENT_FRAGMENT_NODE :
//      case DTM.DOCUMENT_NODE :
//
//        // Can't clone a document, but refrain from throwing an error
//        // so that copy-of will work
//        break;
//      case DTM.ELEMENT_NODE :
//        {
//          Attributes atts;
//
//          if (shouldCloneAttributes)
//          {
//            m_rth.addAttributes(node);
//            m_rth.processNSDecls(node, type, dtm);
//          }
//
//          String ns = dtm.getNamespaceURI(node);
//          String localName = dtm.getLocalName(node);
//
//          m_rth.startElement(ns, localName, dtm.getNodeNameX(node), null);
//        }
//        break;
//      case DTM.CDATA_SECTION_NODE :
//        m_rth.startCDATA();          
//        dtm.dispatchCharactersEvents(node, m_rth, false);
//        m_rth.endCDATA();
//        break;
//      case DTM.ATTRIBUTE_NODE :
//        m_rth.addAttribute(node);
//        break;
//      case DTM.COMMENT_NODE :
//        XMLString xstr = dtm.getStringValue (node);
//        xstr.dispatchAsComment(m_rth);
//        break;
//      case DTM.ENTITY_REFERENCE_NODE :
//        m_rth.entityReference(dtm.getNodeNameX(node));
//        break;
//      case DTM.PROCESSING_INSTRUCTION_NODE :
//        {
//          // %REVIEW% Is the node name the same as the "target"?
//          m_rth.processingInstruction(dtm.getNodeNameX(node), 
//                                      dtm.getNodeValue(node));
//        }
//        break;
//      default :
//        //"Can not create item in result tree: "+node.getNodeName());
//        m_transformer.getMsgMgr().error(null, 
//                         XSLTErrorResources.ER_CANT_CREATE_ITEM,
//                         new Object[]{ dtm.getNodeName(node) });  
//      }
//    }
//    catch(org.xml.sax.SAXException se)
//    {
//      throw new TransformerException(se);
//    }
//  }  // end cloneToResultTree function
/**
   * Clone an element with or without children.
   * TODO: Fix or figure out node clone failure!
   * the error condition is severe enough to halt processing.
   *
   * @param node The node to clone
   * @param shouldCloneAttributes Flag indicating whether to 
   * clone children attributes
   * 
   * @throws TransformerException
   */
public static void cloneToResultTree(int node, int nodeType, DTM dtm, SerializationHandler rth, boolean shouldCloneAttributes) throws TransformerException {
    try {
        switch(nodeType) {
            case DTM.TEXT_NODE:
                dtm.dispatchCharactersEvents(node, rth, false);
                break;
            case DTM.DOCUMENT_FRAGMENT_NODE:
            case DTM.DOCUMENT_NODE:
                // so that copy-of will work
                break;
            case DTM.ELEMENT_NODE:
                {
                    // Note: SAX apparently expects "no namespace" to be
                    // represented as "" rather than null.
                    String ns = dtm.getNamespaceURI(node);
                    if (ns == null)
                        ns = "";
                    String localName = dtm.getLocalName(node);
                    //  rth.startElement(ns, localName, dtm.getNodeNameX(node), null);
                    //  don't call a real SAX startElement (as commented out above),
                    //  call a SAX-like startElement, to be able to add attributes after this call
                    rth.startElement(ns, localName, dtm.getNodeNameX(node));
                    // xsl:attribute directive.)
                    if (shouldCloneAttributes) {
                        SerializerUtils.addAttributes(rth, node);
                        SerializerUtils.processNSDecls(rth, node, nodeType, dtm);
                    }
                }
                break;
            case DTM.CDATA_SECTION_NODE:
                rth.startCDATA();
                dtm.dispatchCharactersEvents(node, rth, false);
                rth.endCDATA();
                break;
            case DTM.ATTRIBUTE_NODE:
                SerializerUtils.addAttribute(rth, node);
                break;
            case DTM.NAMESPACE_NODE:
                // %REVIEW% Normally, these should have been handled with element.
                // It's possible that someone may write a stylesheet that tries to
                // clone them explicitly. If so, we need the equivalent of
                // rth.addAttribute().
                SerializerUtils.processNSDecls(rth, node, DTM.NAMESPACE_NODE, dtm);
                break;
            case DTM.COMMENT_NODE:
                XMLString xstr = dtm.getStringValue(node);
                xstr.dispatchAsComment(rth);
                break;
            case DTM.ENTITY_REFERENCE_NODE:
                rth.entityReference(dtm.getNodeNameX(node));
                break;
            case DTM.PROCESSING_INSTRUCTION_NODE:
                {
                    // %REVIEW% Is the node name the same as the "target"?
                    rth.processingInstruction(dtm.getNodeNameX(node), dtm.getNodeValue(node));
                }
                break;
            default:
                //"Can not create item in result tree: "+node.getNodeName());
                throw new TransformerException("Can't clone node: " + dtm.getNodeName(node));
        }
    } catch (org.xml.sax.SAXException se) {
        throw new TransformerException(se);
    }
}
Also used : XMLString(org.apache.xml.utils.XMLString) XMLString(org.apache.xml.utils.XMLString) TransformerException(javax.xml.transform.TransformerException)

Example 78 with TransformerException

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

the class MsgMgr method error.

/**
   * Tell the user of an error, and probably throw an
   * exception.
   *
   * @param styleNode Stylesheet node
   * @param sourceNode Source tree node
   * @param msg Message text to issue
   * @param args Arguments to use in message
   * @throws XSLProcessorException thrown if the active ProblemListener and XPathContext decide
   * the error condition is severe enough to halt processing.
   *
   * @throws TransformerException
   * @xsl.usage internal
   */
public void error(SourceLocator srcLctr, Node styleNode, Node sourceNode, String msg, Object[] args) throws TransformerException {
    String formattedMsg = XSLMessages.createMessage(msg, args);
    // Locator locator = m_stylesheetLocatorStack.isEmpty()
    //                   ? null :
    //                    ((Locator)m_stylesheetLocatorStack.peek());
    // Locator locator = null;
    ErrorListener errHandler = m_transformer.getErrorListener();
    if (null != errHandler)
        errHandler.fatalError(new TransformerException(formattedMsg, srcLctr));
    else
        throw new TransformerException(formattedMsg, srcLctr);
}
Also used : ErrorListener(javax.xml.transform.ErrorListener) TransformerException(javax.xml.transform.TransformerException)

Example 79 with TransformerException

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

the class MsgMgr method warn.

/**
   * Warn the user of a problem.
   *
   * @param styleNode Stylesheet node
   * @param sourceNode Source tree node
   * @param msg Message text to issue
   * @param args Arguments to pass to the message
   * @throws XSLProcessorException thrown if the active ProblemListener and XPathContext decide
   * the error condition is severe enough to halt processing.
   *
   * @throws TransformerException
   * @xsl.usage internal
   */
public void warn(SourceLocator srcLctr, Node styleNode, Node sourceNode, String msg, Object[] args) throws TransformerException {
    String formattedMsg = XSLMessages.createWarning(msg, args);
    ErrorListener errHandler = m_transformer.getErrorListener();
    if (null != errHandler)
        errHandler.warning(new TransformerException(formattedMsg, srcLctr));
    else
        System.out.println(formattedMsg);
}
Also used : ErrorListener(javax.xml.transform.ErrorListener) TransformerException(javax.xml.transform.TransformerException)

Example 80 with TransformerException

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

the class ToXMLStream method addAttribute.

/**
     * Add an attribute to the current element.
     * @param uri the URI associated with the element name
     * @param localName local part of the attribute name
     * @param rawName   prefix:localName
     * @param type
     * @param value the value of the attribute
     * @param xslAttribute true if this attribute is from an xsl:attribute,
     * false if declared within the elements opening tag.
     * @throws SAXException
     */
public void addAttribute(String uri, String localName, String rawName, String type, String value, boolean xslAttribute) throws SAXException {
    if (m_elemContext.m_startTagOpen) {
        boolean was_added = addAttributeAlways(uri, localName, rawName, type, value, xslAttribute);
        /*
             * We don't run this block of code if:
             * 1. The attribute value was only replaced (was_added is false).
             * 2. The attribute is from an xsl:attribute element (that is handled
             *    in the addAttributeAlways() call just above.
             * 3. The name starts with "xmlns", i.e. it is a namespace declaration.
             */
        if (was_added && !xslAttribute && !rawName.startsWith("xmlns")) {
            String prefixUsed = ensureAttributesNamespaceIsDeclared(uri, localName, rawName);
            if (prefixUsed != null && rawName != null && !rawName.startsWith(prefixUsed)) {
                // use a different raw name, with the prefix used in the
                // generated namespace declaration
                rawName = prefixUsed + ":" + localName;
            }
        }
        addAttributeAlways(uri, localName, rawName, type, value, xslAttribute);
    } else {
        /*
             * The startTag is closed, yet we are adding an attribute?
             *
             * Section: 7.1.3 Creating Attributes Adding an attribute to an
             * element after a PI (for example) has been added to it is an
             * error. The attributes can be ignored. The spec doesn't explicitly
             * say this is disallowed, as it does for child elements, but it
             * makes sense to have the same treatment.
             *
             * We choose to ignore the attribute which is added too late.
             */
        // Generate a warning of the ignored attributes
        // Create the warning message
        String msg = Utils.messages.createMessage(MsgKey.ER_ILLEGAL_ATTRIBUTE_POSITION, new Object[] { localName });
        try {
            // Prepare to issue the warning message
            Transformer tran = super.getTransformer();
            ErrorListener errHandler = tran.getErrorListener();
            // Issue the warning message
            if (null != errHandler && m_sourceLocator != null)
                errHandler.warning(new TransformerException(msg, m_sourceLocator));
            else
                System.out.println(msg);
        } catch (TransformerException e) {
            // A user defined error handler, errHandler, may throw
            // a TransformerException if it chooses to, and if it does
            // we will wrap it with a SAXException and re-throw.
            // Of course if the handler throws another type of
            // exception, like a RuntimeException, then that is OK too.
            SAXException se = new SAXException(e);
            throw se;
        }
    }
}
Also used : ErrorListener(javax.xml.transform.ErrorListener) Transformer(javax.xml.transform.Transformer) TransformerException(javax.xml.transform.TransformerException) SAXException(org.xml.sax.SAXException)

Aggregations

TransformerException (javax.xml.transform.TransformerException)808 Transformer (javax.xml.transform.Transformer)364 StreamResult (javax.xml.transform.stream.StreamResult)362 DOMSource (javax.xml.transform.dom.DOMSource)311 IOException (java.io.IOException)277 TransformerFactory (javax.xml.transform.TransformerFactory)184 Document (org.w3c.dom.Document)161 StringWriter (java.io.StringWriter)159 SAXException (org.xml.sax.SAXException)157 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)156 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)131 Source (javax.xml.transform.Source)100 StreamSource (javax.xml.transform.stream.StreamSource)94 Element (org.w3c.dom.Element)91 DocumentBuilder (javax.xml.parsers.DocumentBuilder)83 File (java.io.File)74 Node (org.w3c.dom.Node)65 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)64 ByteArrayOutputStream (java.io.ByteArrayOutputStream)62 StringReader (java.io.StringReader)59