javatips.net counter

Java Examples for javax.xml.transform.dom.DOMResult

The following java examples will help you to understand the usage of javax.xml.transform.dom.DOMResult. These source code samples are taken from different open source projects.

Example 1
Project: eclipselink.runtime-master  File: XMLMarshaller.java View source code
/**
     * PUBLIC:
     * Convert the given object to XML and update the given result with that XML Document
     * @param object the object to marshal
     * @param result the result to marshal the object to
     * @throws XMLMarshalException if an error occurred during marshalling
     */
public void marshal(Object object, Result result) throws XMLMarshalException {
    if ((object == null) || (result == null)) {
        throw XMLMarshalException.nullArgumentException();
    }
    DESCRIPTOR xmlDescriptor = null;
    ABSTRACT_SESSION session = null;
    boolean isXMLRoot = (object instanceof Root);
    if (isXMLRoot) {
        try {
            session = context.getSession(((Root) object).getObject());
            if (session != null) {
                xmlDescriptor = getDescriptor(((Root) object).getObject(), session);
            }
        } catch (XMLMarshalException marshalException) {
            if (!isSimpleXMLRoot((Root) object)) {
                throw marshalException;
            }
        }
    } else {
        Class objectClass = object.getClass();
        session = context.getSession(objectClass);
        xmlDescriptor = getDescriptor(objectClass, session);
    }
    //if this is a simple xml root, the session and descriptor will be null
    if (result instanceof StreamResult) {
        StreamResult streamResult = (StreamResult) result;
        Writer writer = streamResult.getWriter();
        if (writer != null) {
            marshal(object, writer, session, xmlDescriptor);
        } else if (streamResult.getOutputStream() != null) {
            marshal(object, streamResult.getOutputStream(), session, xmlDescriptor);
        } else {
            try {
                File f;
                try {
                    f = new File(new URL(streamResult.getSystemId()).toURI());
                } catch (MalformedURLException malformedURLException) {
                    try {
                        f = new File(streamResult.getSystemId());
                    } catch (Exception e) {
                        throw malformedURLException;
                    }
                }
                writer = new FileWriter(f);
                try {
                    marshal(object, writer, session, xmlDescriptor);
                } finally {
                    writer.close();
                }
            } catch (Exception e) {
                throw XMLMarshalException.marshalException(e);
            }
        }
    } else if (result instanceof DOMResult) {
        DOMResult domResult = (DOMResult) result;
        // handle case where the node is null
        if (domResult.getNode() == null) {
            domResult.setNode(this.objectToXML(object));
        } else {
            marshal(object, domResult.getNode());
        }
    } else if (result instanceof SAXResult) {
        SAXResult saxResult = (SAXResult) result;
        marshal(object, saxResult.getHandler());
    } else if (result instanceof ExtendedResult) {
        marshal(object, ((ExtendedResult) result).createRecord(), session, xmlDescriptor, isXMLRoot);
    } else {
        if (result.getClass().equals(staxResultClass)) {
            try {
                Object xmlStreamWriter = PrivilegedAccessHelper.invokeMethod(staxResultGetStreamWriterMethod, result);
                if (xmlStreamWriter != null) {
                    MarshalRecord record = (MarshalRecord) PrivilegedAccessHelper.invokeConstructor(xmlStreamWriterRecordConstructor, new Object[] { xmlStreamWriter });
                    record.setMarshaller(this);
                    marshal(object, record, session, xmlDescriptor, isXMLRoot);
                    return;
                } else {
                    Object xmlEventWriter = PrivilegedAccessHelper.invokeMethod(staxResultGetEventWriterMethod, result);
                    if (xmlEventWriter != null) {
                        MarshalRecord record = (MarshalRecord) PrivilegedAccessHelper.invokeConstructor(xmlEventWriterRecordConstructor, new Object[] { xmlEventWriter });
                        record.setMarshaller(this);
                        marshal(object, record, session, xmlDescriptor, isXMLRoot);
                        return;
                    }
                }
            } catch (EclipseLinkException e) {
                throw e;
            } catch (Exception e) {
                throw XMLMarshalException.marshalException(e);
            }
        }
        java.io.StringWriter writer = new java.io.StringWriter();
        marshal(object, writer);
        javax.xml.transform.stream.StreamSource source = new javax.xml.transform.stream.StreamSource(new java.io.StringReader(writer.toString()));
        getTransformer().transform(source, result);
    }
    return;
}
Example 2
Project: openjdk-master  File: WSDLGenerator.java View source code
/**
     * Generates the types section of the WSDL
     */
protected void generateTypes() {
    types = portDefinitions.types();
    if (model.getBindingContext() != null) {
        if (inlineSchemas && model.getBindingContext().getClass().getName().indexOf("glassfish") == -1) {
            resolver.nonGlassfishSchemas = new ArrayList<DOMResult>();
        }
        try {
            model.getBindingContext().generateSchema(resolver);
        } catch (IOException e) {
            throw new WebServiceException(e.getMessage());
        }
    }
    if (resolver.nonGlassfishSchemas != null) {
        TransformerFactory tf = XmlUtil.newTransformerFactory(!disableXmlSecurity);
        try {
            Transformer t = tf.newTransformer();
            for (DOMResult xsd : resolver.nonGlassfishSchemas) {
                Document doc = (Document) xsd.getNode();
                if (inlineSchemas) {
                    NodeList importList = doc.getDocumentElement().getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "import");
                    for (int i = 0; i < importList.getLength(); i++) {
                        org.w3c.dom.Element impElem = (org.w3c.dom.Element) importList.item(i);
                        impElem.removeAttribute("schemaLocation");
                    }
                }
                SAXResult sax = new SAXResult(new TXWContentHandler(types));
                t.transform(new DOMSource(doc.getDocumentElement()), sax);
            }
        } catch (TransformerConfigurationException e) {
            throw new WebServiceException(e.getMessage(), e);
        } catch (TransformerException e) {
            throw new WebServiceException(e.getMessage(), e);
        }
    }
}
Example 3
Project: jlibs-master  File: XSInliner.java View source code
public Document inline(InputSource input, String outputSystemID) throws IOException, SAXException, ParserConfigurationException, TransformerConfigurationException {
    DOMResult result = new DOMResult();
    TransformerHandler handler = TransformerUtil.newTransformerHandler(null, true, 4, null);
    setHandler(handler);
    handler.setResult(result);
    this.outputSystemID = outputSystemID == null ? input.getSystemId() : outputSystemID;
    if (this.outputSystemID != null)
        this.outputSystemID = URLUtil.toURL(this.outputSystemID).toString();
    parse(input);
    Document doc = (Document) result.getNode();
    Element root = doc.getDocumentElement();
    // get children xs:import, xs:redefine and xs:annotation
    NodeList children = root.getChildNodes();
    List<Node> list = new ArrayList<Node>();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (Namespaces.URI_XSD.equals(child.getNamespaceURI()) && TOP_ELEMS.contains(child.getLocalName()))
            list.add(child);
    }
    // delete the children found
    for (Node node : list) node.getParentNode().removeChild(node);
    // add the children in the beginning of root children
    for (int i = list.size() - 1; i >= 0; i--) {
        Node node = list.get(i);
        if (root.getFirstChild() == null)
            root.appendChild(node);
        else
            root.insertBefore(node, root.getFirstChild());
    }
    return doc;
}
Example 4
Project: JBossAS51-master  File: XSLSubDeployer.java View source code
public void init(DeploymentInfo di) throws DeploymentException {
    if (di.document == null)
        findDd(di);
    try {
        Transformer trans = templates.newTransformer();
        String urlStr = di.url.toString();
        String shortURL = ServerConfigUtil.shortUrlFromServerHome(urlStr);
        trans.setErrorListener(new JBossErrorHandler(shortURL, null));
        Source s = new DOMSource(di.document);
        DOMResult r = new DOMResult();
        setParameters(trans);
        trans.transform(s, r);
        di.document = (Document) r.getNode();
        if (log.isDebugEnabled()) {
            log.debug("transformed into doc: " + di.document);
            String docStr = DOMWriter.printNode(di.document, true);
            int index = docStr.toLowerCase().indexOf("password");
            if (index != -1) {
                docStr = maskPasswords(docStr, index);
            }
            log.debug("transformed into doc: " + docStr);
        }
    } catch (TransformerException ce) {
        throw new DeploymentException("Problem with xsl transformation", ce);
    }
    delegate.init(di);
}
Example 5
Project: jaxws-master  File: HandlerClient.java View source code
private int getIntFromResponse(Source source) throws Exception {
    Transformer xFormer = TransformerFactory.newInstance().newTransformer();
    xFormer.setOutputProperty("omit-xml-declaration", "yes");
    DOMResult dResult = new DOMResult();
    xFormer.transform(source, dResult);
    Node documentNode = dResult.getNode();
    Node envelopeNode = documentNode.getFirstChild();
    Node bodyNode = envelopeNode.getLastChild();
    Node requestResponseNode = bodyNode.getFirstChild();
    Node textNode = requestResponseNode.getFirstChild().getFirstChild();
    int responseInt = Integer.parseInt(textNode.getNodeValue());
    return responseInt;
}
Example 6
Project: classlib6-master  File: Process.java View source code
/**
   * Command line interface to transform an XML document according to
   * the instructions found in an XSL stylesheet.  
   * <p>The Process class provides basic functionality for 
   * performing transformations from the command line.  To see a 
   * list of arguments supported, call with zero arguments.</p>
   * <p>To set stylesheet parameters from the command line, use 
   * <code>-PARAM name expression</code>. If you want to set the 
   * parameter to a string value, simply pass the string value 
   * as-is, and it will be interpreted as a string.  (Note: if 
   * the value has spaces in it, you may need to quote it depending 
   * on your shell environment).</p>
   *
   * @param argv Input parameters from command line
   */
// J2SE does not support Xalan interpretive
// main -> _main
public static void _main(String argv[]) {
    // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
    boolean doStackDumpOnError = false;
    boolean setQuietMode = false;
    boolean doDiag = false;
    String msg = null;
    boolean isSecureProcessing = false;
    // Runtime.getRuntime().traceMethodCalls(false);
    // Runtime.getRuntime().traceInstructions(false);
    /**
     * The default diagnostic writer...
     */
    java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true);
    java.io.PrintWriter dumpWriter = diagnosticsWriter;
    ResourceBundle resbundle = (XSLMessages.loadResourceBundle(com.sun.org.apache.xml.internal.utils.res.XResourceBundle.ERROR_RESOURCES));
    String flavor = "s2s";
    if (argv.length < 1) {
        printArgOptions(resbundle);
    } else {
        // J2SE does not support Xalan interpretive
        // false -> true
        boolean useXSLTC = true;
        for (int i = 0; i < argv.length; i++) {
            if ("-XSLTC".equalsIgnoreCase(argv[i])) {
                useXSLTC = true;
            }
        }
        TransformerFactory tfactory;
        if (useXSLTC) {
            String key = "javax.xml.transform.TransformerFactory";
            String value = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
            Properties props = System.getProperties();
            props.put(key, value);
            System.setProperties(props);
        }
        try {
            tfactory = TransformerFactory.newInstance();
            tfactory.setErrorListener(new DefaultErrorHandler());
        } catch (TransformerFactoryConfigurationError pfe) {
            pfe.printStackTrace(dumpWriter);
            msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
            diagnosticsWriter.println(msg);
            tfactory = null;
            doExit(msg);
        }
        boolean formatOutput = false;
        boolean useSourceLocation = false;
        String inFileName = null;
        String outFileName = null;
        String dumpFileName = null;
        String xslFileName = null;
        String treedumpFileName = null;
        // J2SE does not support Xalan interpretive
        /*
      PrintTraceListener tracer = null;
      */
        String outputType = null;
        String media = null;
        Vector params = new Vector();
        boolean quietConflictWarnings = false;
        URIResolver uriResolver = null;
        EntityResolver entityResolver = null;
        ContentHandler contentHandler = null;
        int recursionLimit = -1;
        for (int i = 0; i < argv.length; i++) {
            if ("-XSLTC".equalsIgnoreCase(argv[i])) {
            // The -XSLTC option has been processed.
            } else /*
        else if ("-TT".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceTemplates = true;
          }
          else
            printInvalidXSLTCOption("-TT");

          // tfactory.setTraceTemplates(true);
        }
        else if ("-TG".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceGeneration = true;
          }
          else
            printInvalidXSLTCOption("-TG");

          // tfactory.setTraceSelect(true);
        }
        else if ("-TS".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceSelection = true;
          }
          else
            printInvalidXSLTCOption("-TS");

          // tfactory.setTraceTemplates(true);
        }
        else if ("-TTC".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceElements = true;
          }
          else
            printInvalidXSLTCOption("-TTC");

          // tfactory.setTraceTemplateChildren(true);
        }
        */
            if ("-INDENT".equalsIgnoreCase(argv[i])) {
                int indentAmount;
                if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) {
                    indentAmount = Integer.parseInt(argv[++i]);
                } else {
                    indentAmount = 0;
                }
            // TBD:
            // xmlProcessorLiaison.setIndent(indentAmount);
            } else if ("-IN".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                    inFileName = argv[++i];
                else
                    System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                    new Object[] { "-IN" }));
            } else if ("-MEDIA".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length)
                    media = argv[++i];
                else
                    System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                    new Object[] { "-MEDIA" }));
            } else if ("-OUT".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                    outFileName = argv[++i];
                else
                    System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                    new Object[] { "-OUT" }));
            } else if ("-XSL".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                    xslFileName = argv[++i];
                else
                    System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                    new Object[] { "-XSL" }));
            } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length) {
                    flavor = argv[++i];
                } else
                    System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                    new Object[] { "-FLAVOR" }));
            } else if ("-PARAM".equalsIgnoreCase(argv[i])) {
                if (i + 2 < argv.length) {
                    String name = argv[++i];
                    params.addElement(name);
                    String expression = argv[++i];
                    params.addElement(expression);
                } else
                    System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                    new Object[] { "-PARAM" }));
            } else if ("-E".equalsIgnoreCase(argv[i])) {
            // TBD:
            // xmlProcessorLiaison.setShouldExpandEntityRefs(false);
            } else if ("-V".equalsIgnoreCase(argv[i])) {
                diagnosticsWriter.println(//">>>>>>> Xalan Version "
                resbundle.getString("version") + Version.getVersion() + ", " + /* xmlProcessorLiaison.getParserDescription()+ */
                resbundle.getString(// "<<<<<<<");
                "version2"));
            } else /*
        else if ("-QC".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
            quietConflictWarnings = true;
          else
            printInvalidXSLTCOption("-QC");
        }
        */
            if ("-Q".equalsIgnoreCase(argv[i])) {
                setQuietMode = true;
            } else if ("-DIAG".equalsIgnoreCase(argv[i])) {
                doDiag = true;
            } else if ("-XML".equalsIgnoreCase(argv[i])) {
                outputType = "xml";
            } else if ("-TEXT".equalsIgnoreCase(argv[i])) {
                outputType = "text";
            } else if ("-HTML".equalsIgnoreCase(argv[i])) {
                outputType = "html";
            } else if ("-EDUMP".equalsIgnoreCase(argv[i])) {
                doStackDumpOnError = true;
                if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) {
                    dumpFileName = argv[++i];
                }
            } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length) {
                    try {
                        uriResolver = (URIResolver) ObjectFactory.newInstance(argv[++i], ObjectFactory.findClassLoader(), true);
                        tfactory.setURIResolver(uriResolver);
                    } catch (ObjectFactory.ConfigurationError cnfe) {
                        msg = XSLMessages.createMessage(XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] { "-URIResolver" });
                        System.err.println(msg);
                        doExit(msg);
                    }
                } else {
                    msg = XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                    new Object[] { "-URIResolver" });
                    System.err.println(msg);
                    doExit(msg);
                }
            } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length) {
                    try {
                        entityResolver = (EntityResolver) ObjectFactory.newInstance(argv[++i], ObjectFactory.findClassLoader(), true);
                    } catch (ObjectFactory.ConfigurationError cnfe) {
                        msg = XSLMessages.createMessage(XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] { "-EntityResolver" });
                        System.err.println(msg);
                        doExit(msg);
                    }
                } else {
                    //            "Missing argument for);
                    msg = XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] { "-EntityResolver" });
                    System.err.println(msg);
                    doExit(msg);
                }
            } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) {
                if (i + 1 < argv.length) {
                    try {
                        contentHandler = (ContentHandler) ObjectFactory.newInstance(argv[++i], ObjectFactory.findClassLoader(), true);
                    } catch (ObjectFactory.ConfigurationError cnfe) {
                        msg = XSLMessages.createMessage(XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] { "-ContentHandler" });
                        System.err.println(msg);
                        doExit(msg);
                    }
                } else {
                    //            "Missing argument for);
                    msg = XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] { "-ContentHandler" });
                    System.err.println(msg);
                    doExit(msg);
                }
            } else // of the translet class.
            if ("-XO".equalsIgnoreCase(argv[i])) {
                if (useXSLTC) {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') {
                        tfactory.setAttribute("generate-translet", "true");
                        tfactory.setAttribute("translet-name", argv[++i]);
                    } else
                        tfactory.setAttribute("generate-translet", "true");
                } else {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                        i++;
                    printInvalidXalanOption("-XO");
                }
            } else // Specify the destination directory for the translet classes.
            if ("-XD".equalsIgnoreCase(argv[i])) {
                if (useXSLTC) {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                        tfactory.setAttribute("destination-directory", argv[++i]);
                    else
                        System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                        new Object[] { "-XD" }));
                } else {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                        i++;
                    printInvalidXalanOption("-XD");
                }
            } else // Specify the jar file name which the translet classes are packaged into.
            if ("-XJ".equalsIgnoreCase(argv[i])) {
                if (useXSLTC) {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') {
                        tfactory.setAttribute("generate-translet", "true");
                        tfactory.setAttribute("jar-name", argv[++i]);
                    } else
                        System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                        new Object[] { "-XJ" }));
                } else {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                        i++;
                    printInvalidXalanOption("-XJ");
                }
            } else // Specify the package name prefix for the generated translet classes.
            if ("-XP".equalsIgnoreCase(argv[i])) {
                if (useXSLTC) {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                        tfactory.setAttribute("package-name", argv[++i]);
                    else
                        System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, //"Missing argument for);
                        new Object[] { "-XP" }));
                } else {
                    if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
                        i++;
                    printInvalidXalanOption("-XP");
                }
            } else // Enable template inlining.
            if ("-XN".equalsIgnoreCase(argv[i])) {
                if (useXSLTC) {
                    tfactory.setAttribute("enable-inlining", "true");
                } else
                    printInvalidXalanOption("-XN");
            } else // Turns on additional debugging message output
            if ("-XX".equalsIgnoreCase(argv[i])) {
                if (useXSLTC) {
                    tfactory.setAttribute("debug", "true");
                } else
                    printInvalidXalanOption("-XX");
            } else // than the stylesheet.
            if ("-XT".equalsIgnoreCase(argv[i])) {
                if (useXSLTC) {
                    tfactory.setAttribute("auto-translet", "true");
                } else
                    printInvalidXalanOption("-XT");
            } else if ("-SECURE".equalsIgnoreCase(argv[i])) {
                isSecureProcessing = true;
                try {
                    tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                } catch (TransformerConfigurationException e) {
                }
            } else
                System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_OPTION, //"Invalid argument:);
                new Object[] { argv[i] }));
        }
        // Print usage instructions if no xml and xsl file is specified in the command line
        if (inFileName == null && xslFileName == null) {
            msg = resbundle.getString("xslProc_no_input");
            System.err.println(msg);
            doExit(msg);
        }
        // The main XSL transformation occurs here!
        try {
            long start = System.currentTimeMillis();
            if (null != dumpFileName) {
                dumpWriter = new PrintWriter(new FileWriter(dumpFileName));
            }
            Templates stylesheet = null;
            if (null != xslFileName) {
                if (flavor.equals("d2d")) {
                    // Parse in the xml data into a DOM
                    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
                    dfactory.setNamespaceAware(true);
                    if (isSecureProcessing) {
                        try {
                            dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                        } catch (ParserConfigurationException pce) {
                        }
                    }
                    DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
                    Node xslDOM = docBuilder.parse(new InputSource(xslFileName));
                    stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName));
                } else {
                    // System.out.println("Calling newTemplates: "+xslFileName);
                    stylesheet = tfactory.newTemplates(new StreamSource(xslFileName));
                // System.out.println("Done calling newTemplates: "+xslFileName);
                }
            }
            PrintWriter resultWriter;
            StreamResult strResult;
            if (null != outFileName) {
                strResult = new StreamResult(new FileOutputStream(outFileName));
                // One possible improvement might be to ensure this is 
                //  a valid URI before setting the systemId, but that 
                //  might have subtle changes that pre-existing users 
                //  might notice; we can think about that later -sc r1.46
                strResult.setSystemId(outFileName);
            } else {
                strResult = new StreamResult(System.out);
            // We used to default to incremental mode in this case.
            // We've since decided that since the -INCREMENTAL switch is
            // available, that default is probably not necessary nor
            // necessarily a good idea.
            }
            SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
            // document?
            if (null == stylesheet) {
                Source source = stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null);
                if (null != source)
                    stylesheet = tfactory.newTemplates(source);
                else {
                    if (null != media)
                        //"No stylesheet found in: "
                        throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[] { inFileName, media }));
                    else
                        //"No xml-stylesheet PI found in: "
                        throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[] { inFileName }));
                //+ inFileName);
                }
            }
            if (null != stylesheet) {
                Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
                transformer.setErrorListener(new DefaultErrorHandler());
                // Override the output format?
                if (null != outputType) {
                    transformer.setOutputProperty(OutputKeys.METHOD, outputType);
                }
                // J2SE does not support Xalan interpretive
                /*
          if (transformer instanceof com.sun.org.apache.xalan.internal.transformer.TransformerImpl)
          {
            com.sun.org.apache.xalan.internal.transformer.TransformerImpl impl = (com.sun.org.apache.xalan.internal.transformer.TransformerImpl)transformer;
            TraceManager tm = impl.getTraceManager();

            if (null != tracer)
              tm.addTraceListener(tracer);

            impl.setQuietConflictWarnings(quietConflictWarnings);

			// This is currently controlled via TransformerFactoryImpl.
            if (useSourceLocation)
              impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);

	    if(recursionLimit>0)
	      impl.setRecursionLimit(recursionLimit);

            // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions
            // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter );
          }
          */
                int nParams = params.size();
                for (int i = 0; i < nParams; i += 2) {
                    transformer.setParameter((String) params.elementAt(i), (String) params.elementAt(i + 1));
                }
                if (uriResolver != null)
                    transformer.setURIResolver(uriResolver);
                if (null != inFileName) {
                    if (flavor.equals("d2d")) {
                        // Parse in the xml data into a DOM
                        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
                        dfactory.setCoalescing(true);
                        dfactory.setNamespaceAware(true);
                        if (isSecureProcessing) {
                            try {
                                dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                            } catch (ParserConfigurationException pce) {
                            }
                        }
                        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
                        if (entityResolver != null)
                            docBuilder.setEntityResolver(entityResolver);
                        Node xmlDoc = docBuilder.parse(new InputSource(inFileName));
                        Document doc = docBuilder.newDocument();
                        org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment();
                        transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode));
                        // Now serialize output to disk with identity transformer
                        Transformer serializer = stf.newTransformer();
                        serializer.setErrorListener(new DefaultErrorHandler());
                        Properties serializationProps = stylesheet.getOutputProperties();
                        serializer.setOutputProperties(serializationProps);
                        if (contentHandler != null) {
                            SAXResult result = new SAXResult(contentHandler);
                            serializer.transform(new DOMSource(outNode), result);
                        } else
                            serializer.transform(new DOMSource(outNode), strResult);
                    } else if (flavor.equals("th")) {
                        for (// Loop for diagnosing bugs with inconsistent behavior
                        int i = 0; // Loop for diagnosing bugs with inconsistent behavior
                        i < 1; // Loop for diagnosing bugs with inconsistent behavior
                        i++) {
                            // System.out.println("Testing the TransformerHandler...");
                            XMLReader reader = null;
                            // Use JAXP1.1 ( if possible )      
                            try {
                                javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
                                factory.setNamespaceAware(true);
                                if (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();
                            }
                            // J2SE does not support Xalan interpretive
                            /*              
              if (!useXSLTC)
                stf.setAttribute(com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL, 
                   Boolean.TRUE);
              */
                            TransformerHandler th = stf.newTransformerHandler(stylesheet);
                            reader.setContentHandler(th);
                            reader.setDTDHandler(th);
                            if (th instanceof org.xml.sax.ErrorHandler)
                                reader.setErrorHandler((org.xml.sax.ErrorHandler) th);
                            try {
                                reader.setProperty("http://xml.org/sax/properties/lexical-handler", th);
                            } catch (org.xml.sax.SAXNotRecognizedException e) {
                            } catch (org.xml.sax.SAXNotSupportedException e) {
                            }
                            try {
                                reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
                            } catch (org.xml.sax.SAXException se) {
                            }
                            th.setResult(strResult);
                            reader.parse(new InputSource(inFileName));
                        }
                    } else {
                        if (entityResolver != null) {
                            XMLReader reader = null;
                            // Use JAXP1.1 ( if possible )      
                            try {
                                javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
                                factory.setNamespaceAware(true);
                                if (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();
                            }
                            reader.setEntityResolver(entityResolver);
                            if (contentHandler != null) {
                                SAXResult result = new SAXResult(contentHandler);
                                transformer.transform(new SAXSource(reader, new InputSource(inFileName)), result);
                            } else {
                                transformer.transform(new SAXSource(reader, new InputSource(inFileName)), strResult);
                            }
                        } else if (contentHandler != null) {
                            SAXResult result = new SAXResult(contentHandler);
                            transformer.transform(new StreamSource(inFileName), result);
                        } else {
                            // System.out.println("Starting transform");
                            transformer.transform(new StreamSource(inFileName), strResult);
                        // System.out.println("Done with transform");
                        }
                    }
                } else {
                    StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>");
                    transformer.transform(new StreamSource(reader), strResult);
                }
            } else {
                //          "XSL Process was not successful.");
                msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
                diagnosticsWriter.println(msg);
                doExit(msg);
            }
            // close output streams
            if (null != outFileName && strResult != null) {
                java.io.OutputStream out = strResult.getOutputStream();
                java.io.Writer writer = strResult.getWriter();
                try {
                    if (out != null)
                        out.close();
                    if (writer != null)
                        writer.close();
                } catch (java.io.IOException ie) {
                }
            }
            long stop = System.currentTimeMillis();
            long millisecondsDuration = stop - start;
            if (doDiag) {
                Object[] msgArgs = new Object[] { inFileName, xslFileName, new Long(millisecondsDuration) };
                msg = XSLMessages.createMessage("diagTiming", msgArgs);
                diagnosticsWriter.println('\n');
                diagnosticsWriter.println(msg);
            }
        } catch (Throwable throwable) {
            while (throwable instanceof com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) {
                throwable = ((com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) throwable).getException();
            }
            if ((throwable instanceof NullPointerException) || (throwable instanceof ClassCastException))
                doStackDumpOnError = true;
            diagnosticsWriter.println();
            if (doStackDumpOnError)
                throwable.printStackTrace(dumpWriter);
            else {
                DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
                diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null) + " (" + throwable.getClass().getName() + "): " + throwable.getMessage());
            }
            if (null != dumpFileName) {
                dumpWriter.close();
            }
            doExit(throwable.getMessage());
        }
        if (null != dumpFileName) {
            dumpWriter.close();
        }
        if (null != diagnosticsWriter) {
        // diagnosticsWriter.close();
        }
    // if(!setQuietMode)
    //  diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done");
    // else
    // diagnosticsWriter.println("");  //"Xalan: done");
    }
}
Example 7
Project: geotoolkit-master  File: StaxStreamWriterTest.java View source code
@Test
public void testWritingToDom() throws Exception {
    //this test requiere and advanced Stax library, here we use WoodStox stream reader.
    final DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
    final DocumentBuilder constructeur = fabrique.newDocumentBuilder();
    final Document document = constructeur.newDocument();
    final File file = new File("src/test/resources/org/geotoolkit/xml/sampleOutput.xml");
    if (file.exists())
        file.delete();
    final Result res = new DOMResult(document);
    final MockWriter instance = new MockWriter();
    instance.setOutput(res);
    instance.write();
    instance.dispose();
    //check by reading it back
    final Source src = new DOMSource(document);
    final XMLInputFactory XMLfactory = new WstxInputFactory();
    final XMLStreamReader reader = XMLfactory.createXMLStreamReader(src);
    final MockReader mr = new MockReader();
    mr.setInput(reader);
    StaxStreamReaderTest.validate(mr.read());
    mr.dispose();
}
Example 8
Project: resin-master  File: AbstractAction.java View source code
/**
   * Client-side invocation.
   */
public Object invoke(String url, Object[] args, HandlerChainInvoker handlerChain) throws IOException, XMLStreamException, MalformedURLException, JAXBException, Throwable {
    XMLStreamReader in = null;
    URL urlObject = new URL(url);
    URLConnection connection = urlObject.openConnection();
    // XXX HTTPS
    if (!(connection instanceof HttpURLConnection))
        return null;
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    try {
        //
        // Send the request
        //
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        // XXX: Does this change for multipart/attachments?
        httpConnection.setRequestProperty("Content-type", "text/xml");
        OutputStream httpOut = null;
        XMLStreamWriter out = null;
        DOMResult dom = null;
        UUID uuid = UUID.randomUUID();
        if (_attachmentInputs > 0) {
            // note that we have to add the request property (header) before
            // we get the output stream
            httpConnection.addRequestProperty("Content-Type", "multipart/related; " + "type=\"text/xml\"; " + "boundary=\"uuid:" + uuid + "\"");
            httpOut = httpConnection.getOutputStream();
            PrintWriter writer = new PrintWriter(httpOut);
            writer.print("--uuid:" + uuid + "\r\n");
            writer.print("Content-Type: text/xml\r\n");
            writer.print("\r\n");
            writer.flush();
        } else
            httpOut = httpConnection.getOutputStream();
        if (handlerChain != null) {
            dom = new DOMResult();
            out = getXMLOutputFactory().createXMLStreamWriter(dom);
        } else {
            out = getXMLOutputFactory().createXMLStreamWriter(httpOut);
        }
        writeRequest(out, args);
        out.flush();
        if (_attachmentInputs > 0) {
            httpOut.write("\r\n".getBytes());
            writeAttachments(httpOut, uuid, args);
        }
        if (handlerChain != null) {
            Source source = new DOMSource(dom.getNode());
            if (!handlerChain.invokeClientOutbound(source, httpOut)) {
                source = handlerChain.getSource();
                in = _xmlInputFactory.createXMLStreamReader(source);
                return readResponse(in, args);
            }
        }
        //
        // Parse the response
        // 
        httpConnection.getResponseCode();
        InputStream is = httpConnection.getInputStream();
        if (handlerChain != null)
            is = handlerChain.invokeClientInbound(httpConnection);
        String contentType = httpConnection.getHeaderField("Content-Type");
        if (contentType != null && contentType.startsWith("multipart/related")) {
            String[] tokens = contentType.split(";");
            String boundary = null;
            for (int i = 0; i < tokens.length; i++) {
                int start = tokens[i].indexOf("boundary=");
                if (start >= 0) {
                    boundary = tokens[i].substring(start + "boundary=".length() + 1, tokens[i].lastIndexOf('"'));
                    break;
                }
            }
            if (boundary == null)
                // XXX throw something about malformed response
                return null;
        }
        in = _xmlInputFactory.createXMLStreamReader(is);
        if (httpConnection.getResponseCode() != 200)
            // XXX more meaningful error
            return null;
        if (_isOneway)
            return null;
        return readResponse(in, args);
    } finally {
        if (httpConnection != null)
            httpConnection.disconnect();
    }
}
Example 9
Project: FireflowEngine20-master  File: WebserviceStartProcessTest.java View source code
@Test
public void testCallbackService() {
    final WorkflowSession session = WorkflowSessionFactory.createWorkflowSession(fireflowRuntimeContext, FireWorkflowSystem.getInstance());
    final WorkflowStatement stmt = session.createWorkflowStatement(FpdlConstants.PROCESS_TYPE_FPDL20);
    //0、构建流程定义
    final WorkflowProcess process = getWorkflowProcess();
    //1、首先发布流程
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus arg0) {
            //发布
            try {
                ProcessDescriptor descriptor = stmt.uploadProcessObject(process, 0);
                ((ProcessDescriptorImpl) descriptor).setPublishState(true);
                stmt.updateProcessDescriptor(descriptor);
            } catch (InvalidModelException e) {
                e.printStackTrace();
            }
            return null;
        }
    });
    //2、调用CallbackManager的init方法发布Webservice
    //TODO 通过WorkflowServer发布webservice
    //		WebServiceManager callbackManager = this.runtimeContext.getEngineModule(WebServiceManager.class, FpdlConstants.PROCESS_TYPE_FPDL20);
    //		try {
    //			callbackManager.publishAllCallbackServices();
    //		} catch (WebservicePublishException e1) {
    //			// TODO Auto-generated catch block
    //			e1.printStackTrace();
    //		}
    //用Jaxws客户端调用Webservice		
    Environment env = fireflowRuntimeContext.getEngineModule(Environment.class, FpdlConstants.PROCESS_TYPE_FPDL20);
    URL url = null;
    try {
        String contextPath = env.getWebserviceContextPath();
        if (!contextPath.startsWith("/")) {
            contextPath = "/" + contextPath;
        }
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
        String address = "http://" + env.getWebserviceIP() + ":" + Integer.toString(env.getWebservicePort()) + contextPath;
        url = new URL(address + serviceQName.getLocalPart() + "?wsdl");
    } catch (Exception e) {
        e.printStackTrace();
    }
    javax.xml.ws.Service jawsService = javax.xml.ws.Service.create(url, serviceQName);
    Dispatch<Source> dispatch = jawsService.createDispatch(portQName, Source.class, javax.xml.ws.Service.Mode.PAYLOAD);
    String messageStr = "<cal:acceptRequest  xmlns:cal=\"" + targetNsUri + "\">" + "<cal:id>" + bizId + "</cal:id>" + "<cal:approveResult>" + approveResult + "</cal:approveResult>" + "</cal:acceptRequest>";
    java.io.ByteArrayInputStream byteInStream = new java.io.ByteArrayInputStream(messageStr.getBytes());
    StreamSource source = new StreamSource(byteInStream);
    Source response = dispatch.invoke(source);
    DOMResult result = new DOMResult();
    //		StreamResult result = new StreamResult(System.out);
    Transformer transformer = null;
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformer = transformerFactory.newTransformer();
        transformer.transform(response, result);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    } catch (TransformerException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    }
    Document theResponsePayload = (Document) result.getNode();
    Assert.assertNotNull(theResponsePayload);
    JXPathContext jxpathContext = JXPathContext.newContext(theResponsePayload);
    jxpathContext.registerNamespace("ns0", targetNsUri);
    String response2 = (String) jxpathContext.getValue("ns0:acceptResponse/ns0:response2");
    String response1 = (String) jxpathContext.getValue("ns0:acceptResponse/ns0:response1");
    Assert.assertEquals(responseResult, response2);
    Assert.assertNotNull(response1);
    this.processInstanceId = response1;
    this.assertResult(session);
}
Example 10
Project: openjdk8-jdk-master  File: BooleanAttributes.java View source code
public static void test(String mimeType, boolean useStreamMeta, String metaXml, String... boolXpaths) throws Exception {
    BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document) dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();
    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);
    meta.mergeTree(metaFormat, node);
    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta)
        meta = ir.getStreamMetadata();
    else
        meta = ir.getImageMetadata(0);
    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}
Example 11
Project: proarc-master  File: JhoveUtility.java View source code
/**
     * Merges the mix from the device and from the image
     *
     * @param source
     * @param deviceMix
     */
public static void mergeMix(Mix source, MixType deviceMix) {
    if (deviceMix != null) {
        if (deviceMix.getImageCaptureMetadata() != null) {
            DOMResult domResult = new DOMResult();
            MixUtils.marshal(domResult, new JAXBElement<ImageCaptureMetadataType>(new QName("uri", "local"), ImageCaptureMetadataType.class, deviceMix.getImageCaptureMetadata()), true);
            ImageCaptureMetadataType imageCaptureMtd = MixUtils.unmarshal(new DOMSource(domResult.getNode()), ImageCaptureMetadataType.class);
            source.setImageCaptureMetadata(imageCaptureMtd);
        }
    }
}
Example 12
Project: metafacture-core-master  File: DomLoader.java View source code
public static Document parse(String schemaFile, InputSource input) {
    final Document document = createEmptyDocument();
    final XMLReader pipeline = createXmlFilterPipeline(schemaFile, document);
    process(new SAXSource(pipeline, input), new DOMResult(document));
    // Xerces does not use the XSD schema for deciding whether
    // whitespace is ignorable (it requires a DTD for this).
    // Since we do not use a DTD we have to use a different
    // method to remove ignorable whitespace.
    //
    // Note that this method does not only remove ignorable
    // whitespace but all text nodes containing only whitespace.
    removeEmptyTextNodes(document);
    return document;
}
Example 13
Project: kabeja-master  File: AbstractSAXSerializer.java View source code
/*
     * (non-Javadoc)
     *
     * @see org.xml.sax.ContentHandler#startDocument()
     */
public void startDocument() throws SAXException {
    try {
        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler f = factory.newTransformerHandler();
        this.document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        // put the the transformer in the chain
        f.setResult(new DOMResult(document));
        super.setContentHandler(f);
    } catch (TransformerConfigurationException e) {
        throw new SAXException(e);
    } catch (IllegalArgumentException e) {
        throw new SAXException(e);
    } catch (TransformerFactoryConfigurationError e) {
        throw new SAXException(e.getException());
    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    }
    super.startDocument();
}
Example 14
Project: Payara-master  File: MarshallerImpl.java View source code
public void marshal(Object obj, Result result) throws JAXBException {
    //XMLSerializable so = Util.toXMLSerializable(obj);
    XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj);
    if (so == null)
        throw new MarshalException(Messages.format(Messages.NOT_MARSHALLABLE));
    if (result instanceof SAXResult) {
        write(so, ((SAXResult) result).getHandler());
        return;
    }
    if (result instanceof DOMResult) {
        Node node = ((DOMResult) result).getNode();
        if (node == null) {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.newDocument();
                ((DOMResult) result).setNode(doc);
                write(so, new SAX2DOMEx(doc));
            } catch (ParserConfigurationException pce) {
                throw new JAXBAssertionError(pce);
            }
        } else {
            write(so, new SAX2DOMEx(node));
        }
        return;
    }
    if (result instanceof StreamResult) {
        StreamResult sr = (StreamResult) result;
        XMLWriter w = null;
        if (sr.getWriter() != null)
            w = createWriter(sr.getWriter());
        else if (sr.getOutputStream() != null)
            w = createWriter(sr.getOutputStream());
        else if (sr.getSystemId() != null) {
            String fileURL = sr.getSystemId();
            if (fileURL.startsWith("file:///")) {
                if (fileURL.substring(8).indexOf(":") > 0)
                    fileURL = fileURL.substring(8);
                else
                    fileURL = fileURL.substring(7);
            }
            try {
                w = createWriter(new FileOutputStream(fileURL));
            } catch (IOException e) {
                throw new MarshalException(e);
            }
        }
        if (w == null)
            throw new IllegalArgumentException();
        write(so, w);
        return;
    }
    // unsupported parameter type
    throw new MarshalException(Messages.format(Messages.UNSUPPORTED_RESULT));
}
Example 15
Project: xchain-master  File: ResultCommand.java View source code
/**
   * <p>Returns the result for the select attribute.</p>
   * @param context the JXPathContext to evaluate against.
   * @return the correct result object for the type of object selected from the context.
   */
public Result createResultForSelect(JXPathContext context) throws Exception {
    Object object = getSelect(context);
    if (object == null) {
        throw new IllegalArgumentException("The selected object cannot be null.");
    } else // if the object is a result, then use it.
    if (object instanceof Result) {
        return (Result) object;
    } else // if the object is a stream, then create a stream source.
    if (object instanceof OutputStream) {
        return new StreamResult((OutputStream) object);
    } else if (object instanceof Writer) {
        return new StreamResult((Writer) object);
    } else if (object instanceof File) {
        return new StreamResult((File) object);
    } else // if the object is a content handler, then create a sax result.
    if (object instanceof ContentHandler) {
        return new SAXResult((ContentHandler) object);
    } else // if the result is a node, then create a dom result.
    if (object instanceof Node) {
        return new DOMResult((Node) object);
    } else // we do not how to make a result for this object, so bail out.
    {
        throw new IllegalArgumentException("The selected result object (" + object.getClass().getName() + ") is not a result object nor is it an output stream.");
    }
}
Example 16
Project: JFugue-for-Android-master  File: TransformerIdentityImpl.java View source code
/**
   * Create a result ContentHandler from a Result object, based
   * on the current OutputProperties.
   *
   * @param outputTarget Where the transform result should go,
   * should not be null.
   *
   * @return A valid ContentHandler that will create the
   * result tree when it is fed SAX events.
   *
   * @throws javax.xml.transform.TransformerException
   */
private void createResultContentHandler(Result outputTarget) throws TransformerException {
    if (outputTarget instanceof SAXResult) {
        SAXResult saxResult = (SAXResult) outputTarget;
        m_resultContentHandler = saxResult.getHandler();
        m_resultLexicalHandler = saxResult.getLexicalHandler();
        if (m_resultContentHandler instanceof Serializer) {
            // Dubious but needed, I think.
            m_serializer = (Serializer) m_resultContentHandler;
        }
    } else if (outputTarget instanceof DOMResult) {
        DOMResult domResult = (DOMResult) outputTarget;
        Node outputNode = domResult.getNode();
        Node nextSibling = domResult.getNextSibling();
        Document doc;
        short type;
        if (null != outputNode) {
            type = outputNode.getNodeType();
            doc = (Node.DOCUMENT_NODE == type) ? (Document) outputNode : outputNode.getOwnerDocument();
        } else {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                if (m_isSecureProcessing) {
                    try {
                        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (ParserConfigurationException pce) {
                    }
                }
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.newDocument();
            } catch (ParserConfigurationException pce) {
                throw new TransformerException(pce);
            }
            outputNode = doc;
            type = outputNode.getNodeType();
            ((DOMResult) outputTarget).setNode(outputNode);
        }
        DOMBuilder domBuilder = (Node.DOCUMENT_FRAGMENT_NODE == type) ? new DOMBuilder(doc, (DocumentFragment) outputNode) : new DOMBuilder(doc, outputNode);
        if (nextSibling != null)
            domBuilder.setNextSibling(nextSibling);
        m_resultContentHandler = domBuilder;
        m_resultLexicalHandler = domBuilder;
    } else if (outputTarget instanceof StreamResult) {
        StreamResult sresult = (StreamResult) outputTarget;
        String method = m_outputFormat.getProperty(OutputKeys.METHOD);
        try {
            Serializer serializer = SerializerFactory.getSerializer(m_outputFormat.getProperties());
            m_serializer = serializer;
            if (null != sresult.getWriter())
                serializer.setWriter(sresult.getWriter());
            else if (null != sresult.getOutputStream())
                serializer.setOutputStream(sresult.getOutputStream());
            else if (null != sresult.getSystemId()) {
                String fileURL = sresult.getSystemId();
                if (fileURL.startsWith("file:///")) {
                    if (fileURL.substring(8).indexOf(":") > 0) {
                        fileURL = fileURL.substring(8);
                    } else {
                        fileURL = fileURL.substring(7);
                    }
                } else if (fileURL.startsWith("file:/")) {
                    if (fileURL.substring(6).indexOf(":") > 0) {
                        fileURL = fileURL.substring(6);
                    } else {
                        fileURL = fileURL.substring(5);
                    }
                }
                m_outputStream = new java.io.FileOutputStream(fileURL);
                serializer.setOutputStream(m_outputStream);
            } else
                //"No output specified!");
                throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_OUTPUT_SPECIFIED, null));
            m_resultContentHandler = serializer.asContentHandler();
        } catch (IOException ioe) {
            throw new TransformerException(ioe);
        }
    } else {
        //"Can't transform to a Result of type "
        throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_TO_RESULT_TYPE, new Object[] { outputTarget.getClass().getName() }));
    // + outputTarget.getClass().getName()
    // + "!");
    }
    if (m_resultContentHandler instanceof DTDHandler)
        m_resultDTDHandler = (DTDHandler) m_resultContentHandler;
    if (m_resultContentHandler instanceof DeclHandler)
        m_resultDeclHandler = (DeclHandler) m_resultContentHandler;
    if (m_resultContentHandler instanceof LexicalHandler)
        m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
}
Example 17
Project: keycloak-master  File: StaxParserUtil.java View source code
/**
     * Given that the [email protected] XMLEventReader} is in [email protected] XMLStreamConstants.START_ELEMENT} mode, we parse into a DOM
     * Element
     *
     * @param xmlEventReader
     *
     * @return
     *
     * @throws ParsingException
     */
public static Element getDOMElement(XMLEventReader xmlEventReader) throws ParsingException {
    Transformer transformer = null;
    final String JDK_TRANSFORMER_PROPERTY = "picketlink.jdk.transformer";
    boolean useJDKTransformer = Boolean.parseBoolean(SecurityActions.getSystemProperty(JDK_TRANSFORMER_PROPERTY, "false"));
    try {
        if (useJDKTransformer) {
            transformer = TransformerUtil.getTransformer();
        } else {
            transformer = TransformerUtil.getStaxSourceToDomResultTransformer();
        }
        Document resultDocument = DocumentUtil.createDocument();
        DOMResult domResult = new DOMResult(resultDocument);
        Source source = new StAXSource(xmlEventReader);
        TransformerUtil.transform(transformer, source, domResult);
        Document doc = (Document) domResult.getNode();
        return doc.getDocumentElement();
    } catch (ConfigurationException e) {
        throw logger.parserException(e);
    } catch (XMLStreamException e) {
        throw logger.parserException(e);
    }
}
Example 18
Project: Netuno-master  File: JDBC4MysqlSQLXML.java View source code
/**
	 * Returns a Result for setting the XML value designated by this SQLXML
	 * instance.
	 * <p>
	 * The systemID of the Result is implementation dependent.
	 * <p>
	 * The SQL XML object becomes not writeable when this method is called and
	 * may also become not readable depending on implementation.
	 * <p>
	 * Note that SAX is a callback architecture and the returned SAXResult has a
	 * content handler assigned that will receive the SAX events based on the
	 * contents of the XML. Call the content handler with the contents of the
	 * XML document to assign the values.
	 * 
	 * <pre>
	 * SAXResult saxResult = sqlxml.setResult(SAXResult.class);
	 * ContentHandler contentHandler = saxResult.getXMLReader().getContentHandler();
	 * contentHandler.startDocument();
	 * // set the XML elements and attributes into the result
	 * contentHandler.endDocument();
	 * </pre>
	 * 
	 * @param resultClass
	 *            The class of the result, or null. If resultClass is null, a
	 *            vendor specific Result implementation will be returned. The
	 *            following classes are supported at a minimum:
	 * 
	 * <pre>
	 *    javax.xml.transform.dom.DOMResult - returns a DOMResult
	 *    javax.xml.transform.sax.SAXResult - returns a SAXResult
	 *    javax.xml.transform.stax.StAXResult - returns a StAXResult
	 *    javax.xml.transform.stream.StreamResult - returns a StreamResult
	 * </pre>
	 * 
	 * @return Returns a Result for setting the XML value.
	 * @throws SQLException
	 *             if there is an error processing the XML value or if this
	 *             feature is not supported. The getCause() method of the
	 *             exception may provide a more detailed exception, for example,
	 *             if an XML parser exception occurs. An exception is thrown if
	 *             the state is not writable.
	 * @exception SQLFeatureNotSupportedException
	 *                if the JDBC driver does not support this method
	 * @since 1.6
	 */
public synchronized Result setResult(Class clazz) throws SQLException {
    checkClosed();
    checkWorkingWithResult();
    this.workingWithResult = true;
    this.asDOMResult = null;
    this.asSAXResult = null;
    this.saxToReaderConverter = null;
    this.stringRep = null;
    this.asStringWriter = null;
    this.asByteArrayOutputStream = null;
    if (clazz == null || clazz.equals(SAXResult.class)) {
        this.saxToReaderConverter = new SimpleSaxToReader();
        this.asSAXResult = new SAXResult(this.saxToReaderConverter);
        return this.asSAXResult;
    } else if (clazz.equals(DOMResult.class)) {
        this.asDOMResult = new DOMResult();
        return this.asDOMResult;
    } else if (clazz.equals(StreamResult.class)) {
        return new StreamResult(setCharacterStreamInternal());
    } else if (clazz.equals(StAXResult.class)) {
        try {
            if (this.outputFactory == null) {
                this.outputFactory = XMLOutputFactory.newInstance();
            }
            return new StAXResult(this.outputFactory.createXMLEventWriter(setCharacterStreamInternal()));
        } catch (XMLStreamException ex) {
            SQLException sqlEx = SQLError.createSQLException(ex.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
            sqlEx.initCause(ex);
            throw sqlEx;
        }
    } else {
        throw SQLError.createSQLException("XML Result of type \"" + clazz.toString() + "\" Not supported.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
    }
}
Example 19
Project: lucene-solr-master  File: XMLLoader.java View source code
@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) {
        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);
        }
    }
}
Example 20
Project: android_platform_libcore-master  File: XsltXPathConformanceTestSuite.java View source code
public void test() throws Exception {
    if (purpose != null) {
        System.out.println("Purpose: " + purpose);
    }
    if (spec != null) {
        System.out.println("Spec: " + spec);
    }
    Result result;
    if ("XML".equals(compareAs)) {
        DOMResult domResult = new DOMResult();
        domResult.setNode(documentBuilder.newDocument().createElementNS("", "result"));
        result = domResult;
    } else {
        result = new StreamResult(new StringWriter());
    }
    ErrorRecorder errorRecorder = new ErrorRecorder();
    transformerFactory.setErrorListener(errorRecorder);
    Transformer transformer;
    try {
        Source xslt = new StreamSource(principalStylesheet);
        transformer = transformerFactory.newTransformer(xslt);
        if (errorRecorder.error == null) {
            transformer.setErrorListener(errorRecorder);
            transformer.transform(new StreamSource(principalData), result);
        }
    } catch (TransformerConfigurationException e) {
        errorRecorder.fatalError(e);
    }
    if (operation.equals("standard")) {
        if (errorRecorder.error != null) {
            throw errorRecorder.error;
        }
    } else if (operation.equals("execution-error")) {
        if (errorRecorder.error != null) {
            return;
        }
        fail("Expected " + operation + ", but transform completed normally." + " (Warning=" + errorRecorder.warning + ")");
    } else {
        throw new UnsupportedOperationException("Unexpected operation: " + operation);
    }
    if ("XML".equals(compareAs)) {
        assertNodesAreEquivalent(principal, ((DOMResult) result).getNode());
    } else {
        // TODO: implement support for comparing HTML etc.
        throw new UnsupportedOperationException("Cannot compare as " + compareAs);
    }
}
Example 21
Project: glassfish-main-master  File: UnWrappedMessage.java View source code
public void setPayLoad(Source s) throws Exception {
    if (s instanceof DOMSource) {
        setPayLoad(((DOMSource) s).getNode());
    } else if (s instanceof StreamSource) {
        XMLStreamReader reader = XIF.createXMLStreamReader(((StreamSource) s).getInputStream());
        setPayLoad(reader);
    } else if (s instanceof SAXSource) {
        InputSource source = ((SAXSource) s).getInputSource();
        XMLStreamReader reader = (source.getCharacterStream() != null) ? XIF.createXMLStreamReader(source.getCharacterStream()) : XIF.createXMLStreamReader(source.getByteStream());
        setPayLoad(reader);
    } else {
        logger.log(Level.WARNING, "UnWrappedMessage :: Transforming the input message to DOM");
        Transformer t = TF.newTransformer();
        DOMResult result = new DOMResult();
        t.transform(s, result);
        setPayLoad(result.getNode());
    }
}
Example 22
Project: iaf-master  File: Parameter.java View source code
private Object transform(Source xmlSource, ParameterResolutionContext prc) throws ParameterException, TransformerException, IOException {
    TransformerPool pool = getTransformerPool();
    if (TYPE_NODE.equals(getType()) || TYPE_DOMDOC.equals(getType())) {
        DOMResult transformResult = new DOMResult();
        pool.transform(xmlSource, transformResult, prc.getValueMap(paramList));
        Node result = transformResult.getNode();
        if (result != null && TYPE_NODE.equals(getType())) {
            result = result.getFirstChild();
        }
        if (log.isDebugEnabled()) {
            if (result != null)
                log.debug("Returning Node result [" + result.getClass().getName() + "][" + result + "]: " + ToStringBuilder.reflectionToString(result));
        }
        return result;
    } else {
        return pool.transform(xmlSource, prc.getValueMap(paramList));
    }
}