Example usage for javax.xml.transform.dom DOMResult DOMResult

List of usage examples for javax.xml.transform.dom DOMResult DOMResult

Introduction

In this page you can find the example usage for javax.xml.transform.dom DOMResult DOMResult.

Prototype

public DOMResult(Node node) 

Source Link

Document

Use a DOM node to create a new output target.

Usage

From source file:com.gargoylesoftware.htmlunit.libraries.Sarissa0993Test.java

/**
 * @throws Exception if the test fails// ww  w  . ja v  a  2 s.  c  om
 */
@Test
@Browsers(Browser.NONE)
public void xslt() throws Exception {
    final String input = "<root><element attribute=\"value\"/></root>";
    final String style = "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n"
            + "<xsl:output method=\"xml\" omit-xml-declaration=\"yes\"/>\n"
            + "<xsl:param select=\"'anonymous'\" name=\"user\"/>\n" + "<xsl:template match=\"/\">\n"
            + "<p id=\"user\">User: <xsl:value-of select=\"$user\"/>\n" + "</p>\n" + "<xsl:apply-templates/>\n"
            + "<hr/>\n" + "</xsl:template>\n" + "<xsl:template match=\"greeting\">\n" + "<p>\n"
            + "<xsl:apply-templates/>\n" + "</p>\n" + "</xsl:template>\n" + "</xsl:stylesheet>";

    final Source xmlSource = new StreamSource(new StringReader(input));
    final Source xsltSource = new StreamSource(new StringReader(style));

    final Document containerDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    final Element containerElement = containerDocument.createElement("container");
    containerDocument.appendChild(containerElement);

    final DOMResult result = new DOMResult(containerElement);

    final Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
    transformer.transform(xmlSource, result);
}

From source file:com.portfolio.data.utils.DomUtils.java

public static void processXSLT(Document xml, String xsltName, Document result, StringBuffer outTrace,
        boolean trace) throws Exception {
    //  =======================================
    outTrace.append("a.");
    processXSLT(new DOMSource(xml), xsltName, new DOMResult(result), outTrace, trace);
    outTrace.append("b.");
}

From source file:de.betterform.generator.XSLTGenerator.java

/**
 * Creates a JAXP Result from the specified input object.
 * <p/>/* w ww  .  j ava 2  s .  co  m*/
 * Follwoing object models are supported:
 * <ul>
 * <li><code>org.w3c.dom.Node</code></li>
 * <li><code>org.xml.sax.ContentHandler</code></li>
 * <li><code>java.io.OutputStream</code></li>
 * <li><code>java.io.Writer</code></li>
 * <li><code>java.io.File</code></li>
 * </ul>
 *
 * @param output the output object.
 * @return a JAXP Result.
 * @throws NullPointerException if the output object is <code>null</code>.
 * @throws IllegalArgumentException if the object model is not supported.
 */
protected Result createOutputResult(Object output) {
    if (output == null) {
        throw new NullPointerException("parameter 'output' must not be null");
    }
    if (output instanceof DOMResult) {
        return (Result) output;
    }
    // DOM
    if (output instanceof Node) {
        return new DOMResult((Node) output);
    }

    // SAX
    if (output instanceof ContentHandler) {
        return new SAXResult((ContentHandler) output);
    }

    // Stream
    if (output instanceof OutputStream) {
        return new StreamResult((OutputStream) output);
    }
    if (output instanceof Writer) {
        return new StreamResult((Writer) output);
    }
    if (output instanceof File) {
        return new StreamResult((File) output);
    }

    throw new IllegalArgumentException(output.getClass().getName() + " not supported as output");
}

From source file:org.n52.smartsensoreditor.controller.StartEditorControllerSML.java

/**
 * Starts editor with a service description
 *
 * @param pEditorBean//from  w  w w  . ja v  a 2 s .c o m
 * @param pResult
 * @return
 */
@RequestMapping(value = "/startServiceSOS", method = RequestMethod.POST)
public ModelAndView startServiceHandler(@ModelAttribute("startEditorBeanSML") StartEditorBeanSML pEditorBean,
        BindingResult pResult) {
    //Error handling
    ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceUrl", "errors.service.url.empty");
    ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceType", "errors.service.type.empty");

    if (pEditorBean.getServiceType().equalsIgnoreCase("ARCIMS")) {
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceName", "errors.service.name.empty");
    }

    if (pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)) {
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceTokenForSOS",
                "errors.service.tokenForSOS.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceProcedureIDForSOS",
                "errors.service.procedureIDForSOS.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceOperationForSOS",
                "errors.service.operationForSOS.empty");
    }

    if (pResult.hasErrors()) {
        LOG.debug("Form validation errors: " + pResult);
        // return form view
        return new ModelAndView(getFormView(), getModelMap());
    }
    //Set service URL
    String serviceUrl = pEditorBean.getServiceUrl();
    LOG.debug("ServiceUrl set to '" + serviceUrl + "'");
    //Create webservice
    if (pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)) {//serviceTypes are defined in codelist_enumeration.xml in identifier: CT_ServiceTypeExt.
        LOG.debug("Put SOS values into webserviceDescriptionDAO");
        StartEditorBeanSML editorBeanSML = (StartEditorBeanSML) pEditorBean;
        //Set procedureID
        String procId = editorBeanSML.getServiceProcedureIDForSOS();
        LOG.debug("Procedure ID set to '" + procId + "'");
        //Set token
        String token = editorBeanSML.getServiceTokenForSOS();
        LOG.debug("Token is set to '" + token + "'");

        //Set the token and the serviceUrl within the BackendBeanSml to insert them in the selectStates.jsp file.
        BackendBean backendBean = getBackendService().getBackend();
        if (backendBean instanceof BackendBeanSML) {
            BackendBeanSML backendBeanSML = ((BackendBeanSML) backendBean);
            backendBeanSML.setServiceURL(serviceUrl);
            LOG.debug("ServiceUrl is set in the BeackendBean '" + serviceUrl + "'");
            backendBeanSML.setServiceTokenSOS(token);
            LOG.debug("Token is set in the BackendBean '" + token + "'");
        }

        //For request
        Document catalogRequest = null;
        Document catalogResponse = null;
        Map parameterMap = new HashMap();
        parameterMap.put("procedureId", procId);

        SOSCatalogService sosService = getSOSCatalogServiceDAO();
        sosService.init(serviceUrl);
        sosService.addRequestHeader("Authorization", token);
        sosService.addRequestHeader("Content-Type", "application/soap+xml");

        //When a sensor should be edited
        if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DESCRIBE)) {
            //Create Request and do transaction
            catalogRequest = getRequestFactory().createRequest("get", parameterMap);

            catalogResponse = sosService.transaction(catalogRequest);//does it really throw an exception??

            if (catalogResponse == null) {
                Map<String, Object> lModel = getModelMap();
                lModel.put("response", new TransactionResponseSOS());
                lModel.put("serverError", "errors.service.connect.request");
                lModel.put("sourcePage", "startService");
                return new ModelAndView(getFinishView(), lModel);
            }
            //For Transformation
            Document sensorML = DOMUtil.newDocument(true);
            Source source = new DOMSource(catalogResponse);
            Result result = new DOMResult(sensorML);

            String transformerFilePath = getTransformerFiles().get(SOS_SERVICE_TYPE.toLowerCase());
            getXsltTransformer().setRulesetSystemID(transformerFilePath);
            // transform
            getXsltTransformer().transform(source, result);
            getBackendService().initBackend(sensorML);

            getBackendService().setUpdate(true);
            return new ModelAndView(getSuccessView());

        }
        //When a sensor should be deleted
        if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DELETE)) {
            catalogRequest = getRequestFactory().createRequest("delete", parameterMap);
            catalogResponse = sosService.transaction(catalogRequest);
            Map<String, Object> lModel = new HashMap<String, Object>();
            lModel.put("sourcePage", "startService");
            if (catalogResponse == null) {
                lModel.put("response", new TransactionResponseSOS());
                lModel.put("serverError", "errors.service.connect.request");
                return new ModelAndView(getFinishView(), lModel);
            }

            lModel.put("response", new TransactionResponseSOS(catalogResponse));
            return new ModelAndView(getFinishView(), lModel);
        }
    } else {
        WebServiceDescriptionDAO dao = getServiceFactory()
                .getDescriptionDAO(pEditorBean.getServiceType().toLowerCase());
        dao.setUrl(serviceUrl);
        LOG.trace("Current dao: " + dao);
        if (!"".equals(pEditorBean.getServiceName())) {
            dao.setServiceName(pEditorBean.getServiceName());
        }
        try {
            Document lDoc = dao.getDescription();
            if (LOG.isTraceEnabled()) {
                String docString = DOMUtil.convertToString(lDoc, true);
                LOG.trace("Retrieved document from DAO: " + docString);
            }
            if (lDoc != null) {
                getBackendService().setUpdate(true);

                getBackendService().initBackend(lDoc);
                return new ModelAndView(getSuccessView());
            }
        } catch (WebServiceDescriptionException e) {
            pResult.rejectValue("serviceUrl", "errors.service.connect", new Object[] { e.getMessage() },
                    "Capabilities error");
            return new ModelAndView(getFormView(), getModelMap());
        }

    }
    return new ModelAndView(getFormView());

}

From source file:com.kaikoda.cah.TestDeck.java

@Test
public void testDeckTransform_nullParamValue()
        throws SAXException, IOException, TransformerException, ParserConfigurationException {

    // Retrieve the control card data for Dutch English CAH (so can assume
    // all pre-processing complete).
    Document xml = this.getDocument("/data/control/cards/netherlands.xml");

    Deck customDeck = new Deck(xml);
    customDeck.setErrorListener(new ProgressReporter());

    // Create a container to hold the result of the transformation
    DocumentBuilder documentBuilder = Deck.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    DOMResult result = new DOMResult(document);

    // Build the parameter list
    TreeMap<String, String> params = new TreeMap<String, String>();
    params.put("path-to-dictionary", TestDeck.DICTIONARY_DATA_ENGLISH.getAbsolutePath());
    params.put("output-language", null);

    customDeck.transform(new DOMSource(xml), Deck.getXsl(Deck.PATH_TO_TRANSLATION_XSL), result, params);

    // Retrieve the control card data for American CAH.
    Document expected = xml;/*  w w  w . ja  v a  2 s  .c  o m*/

    // Check that the result is the same cards, translated into American
    // English (which is the default output language).
    assertXMLEqual(expected, document);

}

From source file:com.twinsoft.convertigo.engine.util.ProjectUtils.java

public static void getFullProjectDOM(Document document, String projectName, StreamSource xslFilter)
        throws TransformerFactoryConfigurationError, EngineException, TransformerException {
    Element root = document.getDocumentElement();
    getFullProjectDOM(document, projectName);

    // transformation du dom
    Transformer xslt = TransformerFactory.newInstance().newTransformer(xslFilter);
    Element xsl = document.createElement("xsl");
    xslt.transform(new DOMSource(document), new DOMResult(xsl));
    root.replaceChild(xsl.getFirstChild(), root.getFirstChild());
}

From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java

/**
 * @throws XtentisException//from  w w  w . ja  va2 s. c  o  m
 * 
 * @ejb.interface-method view-type = "local"
 * @ejb.facade-method
 */
public void execute(TransformerPluginContext context) throws XtentisException {
    try {
        // fetch data from context
        Transformer transformer = (Transformer) context.get(TRANSFORMER);
        String outputMethod = (String) context.get(OUTPUT_METHOD);
        TypedContent xmlTC = (TypedContent) context.get(INPUT_XML);

        // get the charset
        String charset = Util.extractCharset(xmlTC.getContentType());

        // get the xml String
        String xml = new String(xmlTC.getContentBytes(), charset);

        // get the xml parameters
        TypedContent parametersTC = (TypedContent) context.get(INPUT_PARAMETERS);
        if (parametersTC != null) {
            String parametersCharset = Util.extractCharset(parametersTC.getContentType());

            byte[] parametersBytes = parametersTC.getContentBytes();
            if (parametersBytes != null) {
                String parameters = new String(parametersBytes, parametersCharset);

                Document parametersDoc = Util.parse(parameters);
                NodeList paramList = Util.getNodeList(parametersDoc.getDocumentElement(), "//Parameter"); //$NON-NLS-1$
                for (int i = 0; i < paramList.getLength(); i++) {
                    String paramName = Util.getFirstTextNode(paramList.item(i), "Name"); //$NON-NLS-1$
                    String paramValue = Util.getFirstTextNode(paramList.item(i), "Value"); //$NON-NLS-1$
                    if (paramValue == null)
                        paramValue = ""; //$NON-NLS-1$

                    if (paramName != null) {
                        transformer.setParameter(paramName, paramValue);
                    }
                }
            }
        }

        // FIXME: ARRRRGHHHHHH - How do you prevent the Transformer to process doctype instructions?

        // Sets the current time
        transformer.setParameter("TIMESTAMP", getTimestamp()); //$NON-NLS-1$
        transformer.setErrorListener(new ErrorListener() {

            public void error(TransformerException exception) throws TransformerException {
                transformatioError = exception.getMessage();
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                transformatioError = exception.getMessage();
            }

            public void warning(TransformerException exception) throws TransformerException {
                transformationeWarning = exception.getMessage();

            }
        });
        transformatioError = null;
        transformationeWarning = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if ("xml".equals(outputMethod) || "xhtml".equals(outputMethod)) { //$NON-NLS-1$ //$NON-NLS-2$
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = builder.newDocument();
            DOMResult domResult = new DOMResult(document);

            transformer.transform(new StreamSource(new StringReader(xml)), domResult);

            if (transformationeWarning != null) {
                String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$
                LOG.warn(err);
            }
            if (transformatioError != null) {
                String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$
                LOG.error(err);
                throw new XtentisException(err);
            }
            Node rootNode = document.getDocumentElement();
            // process the cross-referencings
            NodeList xrefl = Util.getNodeList(rootNode.getOwnerDocument(), "//*[@xrefCluster]"); //$NON-NLS-1$
            int len = xrefl.getLength();
            for (int i = 0; i < len; i++) {
                Element xrefe = (Element) xrefl.item(i);
                xrefe = processMappings(xrefe);
            }
            TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl();
            Transformer serializer = transFactory.newTransformer();
            serializer.setOutputProperty(OutputKeys.METHOD, outputMethod);
            serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
            serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
            serializer.transform(new DOMSource(rootNode), new StreamResult(baos));
        } else {
            if (transformationeWarning != null) {
                String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$
                LOG.warn(err);
            }
            if (transformatioError != null) {
                String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$
                LOG.error(err);
                throw new XtentisException(err);
            }
            // transform the item
            transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(baos));
        }
        // Call Back
        byte[] bytes = baos.toByteArray();
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute() Inserting XSL Result in '" + OUTPUT_TEXT + "'\n" + new String(bytes, "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
        context.put(OUTPUT_TEXT,
                new TypedContent(bytes, ("xhtml".equals(outputMethod) ? "application/xhtml+xml" //$NON-NLS-1$//$NON-NLS-2$
                        : "text/" //$NON-NLS-1$
                                + outputMethod)
                        + "; charset=utf-8")); //$NON-NLS-1$
        context.getPluginCallBack().contentIsReady(context);
    } catch (Exception e) {
        String err = "Could not start the XSLT plugin"; //$NON-NLS-1$
        LOG.error(err, e);
        throw new XtentisException(err);
    }
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Tests the {@link CastorMarshaller#marshal(Object, javax.xml.transform.Result)} method. </p>
 *
 * @throws IllegalArgumentException is expected.
 * @throws Exception                if any error occurs during test
 *///w  ww . j  a v a  2  s.c om
@Test(expected = IllegalArgumentException.class)
public void testMarshallResultNull1() throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Node document = builder.newDocument();

    marshaller.marshal(null, new DOMResult(document));
}

From source file:Examples.java

/**
 * Show how to transform a DOM tree into another DOM tree.
 * This uses the javax.xml.parsers to parse an XML file into a
 * DOM, and create an output DOM./*from   w  w  w  .j av a 2 s  .  com*/
 */
public static Node exampleDOM2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    if (tfactory.getFeature(DOMSource.FEATURE)) {
        Templates templates;

        {
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            dfactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            org.w3c.dom.Document outNode = docBuilder.newDocument();
            Node doc = docBuilder.parse(new InputSource(xslID));

            DOMSource dsource = new DOMSource(doc);
            // If we don't do this, the transformer won't know how to 
            // resolve relative URLs in the stylesheet.
            dsource.setSystemId(xslID);

            templates = tfactory.newTemplates(dsource);
        }

        Transformer transformer = templates.newTransformer();
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        // Note you must always setNamespaceAware when building .xsl stylesheets
        dfactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();
        Node doc = docBuilder.parse(new InputSource(sourceID));

        transformer.transform(new DOMSource(doc), new DOMResult(outNode));

        Transformer serializer = tfactory.newTransformer();
        serializer.transform(new DOMSource(outNode), new StreamResult(new OutputStreamWriter(System.out)));

        return outNode;
    } else {
        throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!");
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger)
        throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }//w ww . j ava2  s  .  com
    String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08
                                                              // PwD
    BufferedImage image = reader.read(frame);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(formatName); // 2011-09-08 PwD was
                                                 // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try { // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) { // 2011-08-24
                                                                     // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch (transparency) {
                case Transparency.OPAQUE: {
                    transparencyName = "Opaque";
                    break;
                }
                case Transparency.BITMASK: {
                    transparencyName = "Bitmask";
                    break;
                }
                case Transparency.TRANSLUCENT: {
                    transparencyName = "Translucent";
                    break;
                }
                default: {
                    transparencyName = "Unknown";
                }
                }
                node.setTextContent(transparencyName);

            } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08
                                                                   // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}