Example usage for org.w3c.dom Document appendChild

List of usage examples for org.w3c.dom Document appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Document appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:fr.ortolang.diffusion.seo.SeoServiceBean.java

private Document generateSiteMapDocument() throws ParserConfigurationException, SeoServiceException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Element urlset = doc.createElement("urlset");
    urlset.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SITEMAP_NS_URI);

    String marketServerUrl = OrtolangConfig.getInstance()
            .getProperty(OrtolangConfig.Property.MARKET_SERVER_URL);

    generateMarketSectionEntries(urlset, doc, marketServerUrl);
    generateWorkspacesEntries(urlset, doc, marketServerUrl);

    doc.appendChild(urlset);

    return doc;//from ww w.ja  v a  2  s. co m
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????./*from   w w w  .j a  v  a  2 s  .co m*/
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

    // Dsig??
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return DcCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

private Node makeEntityResolutionConfigurationNode(String limit) throws Exception {
    try {/*from w w w.  j av  a  2 s  .c  o  m*/
        if (Integer.parseInt(limit) == Integer.MAX_VALUE) {
            return null;
        }
    } catch (NumberFormatException nfe) {
        return null;
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.newDocument();
    Element ret = d.createElementNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE,
            "EntityResolutionConfiguration");
    d.appendChild(ret);
    Element e = d.createElementNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "RecordLimit");
    ret.appendChild(e);
    e.setTextContent(limit);
    return ret;
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

/**
 * Create a new document with the given tag as the root element.
 *
 * @param rootTag the tag of the root element
 * @return the document element of a new document
 *///from   w  w w  .j a  va 2  s. c  o m

public Element newDocument(String rootTag) {
    DocumentBuilder builder;
    try {
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element root = doc.createElement(rootTag);
    doc.appendChild(root);
    String[] nvpairs = new String[] { "xmlns:xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,
            //                "xsi:noNamespaceSchemaLocation", INSTANCE_XSD,
            ATTR_VERSION, "1.0", };
    for (int i = 0; i < nvpairs.length; i += 2) {
        root.setAttribute(nvpairs[i], nvpairs[i + 1]);
    }
    return root;
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????./*from w ww .ja  v  a  2s  .co  m*/
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

    // Dsig??
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return PersoniumCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:com.castlemock.web.mock.rest.converter.swagger.SwaggerRestDefinitionConverter.java

/**
 * The method provides the functionality to generate an XML body based on a provided {@link Response}
 * and a list of {@link Model}s that might be required.
 * @param response The Swagger response which the XML body will be based on.
 * @param definitions Definitions of Swagger models
 * @return An XML response body.//from  w  w w .  j  a va2s  .  co m
 * @since 1.13
 */
private String generateXmlBody(final Response response, final Map<String, Model> definitions) {
    final Property schema = response.getSchema();
    if (schema == null) {
        return null;
    }

    final StringWriter stringWriter = new StringWriter();
    try {
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document document = docBuilder.newDocument();
        final Element root = getXmlElement(null, schema, definitions, document);
        document.appendChild(root);

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(document);

        final StreamResult result = new StreamResult(stringWriter);
        transformer.transform(source, result);
        return stringWriter.toString();
    } catch (Exception e) {
        LOGGER.error("Unable to generate a XML response body", e);
    }

    return stringWriter.toString();
}

From source file:com.redsqirl.workflow.server.action.AbstractDictionary.java

private void saveXml(File f) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("dictionary");
    doc.appendChild(rootElement);
    for (Entry<String, String[][]> e : functionsMap.entrySet()) {
        Element menu = doc.createElement("menu");
        menu.setAttribute("name", e.getKey());
        for (String[] function : e.getValue()) {
            try {
                Element functionEl = doc.createElement("function");
                {//from w  w w .  j  a v  a2  s .c o  m
                    Element name = doc.createElement("name");
                    name.appendChild(doc.createTextNode(function[0]));
                    functionEl.appendChild(name);
                }
                {
                    Element input = doc.createElement("input");
                    input.appendChild(doc.createTextNode(function[1]));
                    functionEl.appendChild(input);
                }
                {
                    Element output = doc.createElement("return");
                    output.appendChild(doc.createTextNode(function[2]));
                    functionEl.appendChild(output);
                }

                if (function.length >= 4) {
                    Element help = doc.createElement("help");
                    help.appendChild(doc.createTextNode(function[3]));
                    functionEl.appendChild(help);
                }

                for (int i = 4; i < function.length; ++i) {
                    Element other = doc.createElement("other" + (i - 3));
                    other.appendChild(doc.createTextNode(function[i]));
                    functionEl.appendChild(other);
                }

                menu.appendChild(functionEl);
            } catch (NullPointerException exc) {
            }
        }
        rootElement.appendChild(menu);
    }

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(f);
    transformer.transform(source, result);
}

From source file:com.rest4j.generator.Generator.java

public void generate() throws Exception {
    ApiFactory fac = new ApiFactory(apiXml, null, null);
    for (String className : preprocessors) {
        Preprocessor p = (Preprocessor) Class.forName(className).newInstance();
        fac.addPreprocessor(p);// w  w  w  . j av  a  2 s .co  m
    }
    Document xml = fac.getDocument();
    preprocess(xml);
    URL url = getStylesheet();

    String filename = "index.html";
    for (TemplateParam param : params) {
        if (param.getName().equals("filename")) {
            filename = param.getValue();
        }
    }

    Document doc = transform(xml, url);
    cleanupBeforePostprocess(doc.getDocumentElement());

    if (postprocessingXSLT != null) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document composed = documentBuilder.newDocument();
        org.w3c.dom.Element top = composed.createElementNS("http://rest4j.com/api-description", "top");

        composed.appendChild(top);
        top.appendChild(composed.adoptNode(xml.getDocumentElement()));
        top.appendChild(composed.adoptNode(doc.getDocumentElement()));

        xml = null;
        doc = null; // free some mem

        doc = transform(composed, postprocessingXSLT);
    }

    if ("files".equals(doc.getDocumentElement().getLocalName())) {
        // break the result into files
        for (Node child : Util.it(doc.getDocumentElement().getChildNodes())) {
            if ("file".equals(child.getLocalName())) {
                if (child.getAttributes().getNamedItem("name") == null) {
                    throw new IllegalArgumentException("Attribute name not found in <file>");
                }
                String name = child.getAttributes().getNamedItem("name").getTextContent();
                File file = new File(outputDir, name);
                file.getParentFile().mkdirs();
                System.out.println("Write " + file.getAbsolutePath());
                Attr copyFromAttr = (Attr) child.getAttributes().getNamedItem("copy-from");
                if (copyFromAttr == null) {
                    cleanupFinal((Element) child);
                    if (child.getAttributes().getNamedItem("text") != null) {
                        // plain-text output
                        FileOutputStream fos = new FileOutputStream(file);
                        try {
                            IOUtils.write(child.getTextContent(), fos, "UTF-8");
                        } finally {
                            IOUtils.closeQuietly(fos);
                        }
                    } else {
                        output(child, file);
                    }
                } else {
                    String copyFrom = copyFromAttr.getValue();
                    URL asset = getClass().getClassLoader().getResource(copyFrom);
                    if (asset == null) {
                        asset = getClass().getResource(copyFrom);
                    }
                    if (asset == null) {
                        File assetFile = new File(copyFrom);
                        if (!assetFile.canRead()) {
                            if (postprocessingXSLT != null) {
                                asset = new URL(postprocessingXSLT, copyFrom);
                                try {
                                    asset.openStream().close();
                                } catch (FileNotFoundException fnfe) {
                                    asset = null;
                                }
                            }
                            if (asset == null) {
                                asset = new URL(getStylesheet(), copyFrom);
                                try {
                                    asset.openStream().close();
                                } catch (FileNotFoundException fnfe) {
                                    asset = null;
                                }
                            }
                            if (asset == null)
                                throw new IllegalArgumentException("File '" + copyFrom
                                        + "' specified by @copy-from not found in the classpath or filesystem");
                        } else {
                            asset = assetFile.toURI().toURL();
                        }
                    }
                    InputStream is = asset.openStream();
                    OutputStream fos = new FileOutputStream(file);
                    try {
                        IOUtils.copy(is, fos);
                    } finally {
                        IOUtils.closeQuietly(is);
                        IOUtils.closeQuietly(fos);
                    }
                }
            } else if (child.getNodeType() == Node.ELEMENT_NODE) {
                throw new IllegalArgumentException("Something but <file> found inside <files>");
            }
        }
    } else {
        File file = new File(outputDir, filename);
        System.out.println("Write " + file.getAbsolutePath());
        cleanupFinal(doc.getDocumentElement());
        DOMSource source = new DOMSource(doc);
        FileOutputStream fos = new FileOutputStream(file);
        try {
            StreamResult result = new StreamResult(fos);
            Transformer trans = tFactory.newTransformer();
            trans.transform(source, result);
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:org.openmhealth.shim.healthvault.HealthvaultShim.java

@Override
public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException {
    final HealthVaultDataType healthVaultDataType;
    try {/*  ww  w . jav  a 2  s .  c  om*/
        healthVaultDataType = HealthVaultDataType
                .valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss");

    /***
     * Setup default date parameters
     */
    DateTime today = new DateTime();

    DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1)
            : shimDataRequest.getStartDate();
    String dateStart = startDate.toString(formatter);

    DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate();
    String dateEnd = endDate.toString(formatter);

    long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100
            : shimDataRequest.getNumToReturn();

    Request request = new Request();
    request.setMethodName("GetThings");
    request.setInfo("<info>" + "<group max=\"" + numToReturn + "\">" + "<filter>" + "<type-id>"
            + healthVaultDataType.getDataTypeId() + "</type-id>" + "<eff-date-min>" + dateStart
            + "</eff-date-min>" + "<eff-date-max>" + dateEnd + "</eff-date-max>" + "</filter>" + "<format>"
            + "<section>core</section>" + "<xml/>" + "</format>" + "</group>" + "</info>");

    RequestTemplate template = new RequestTemplate(connection);
    return template.makeRequest(shimDataRequest.getAccessParameters(), request,
            new Marshaller<ShimDataResponse>() {
                public ShimDataResponse marshal(InputStream istream) throws Exception {

                    /**
                     * XML Document mappings to JSON don't respect repeatable
                     * tags, they don't get properly serialized into collections.
                     * Thus, we pickup the 'things' via the 'group' root tag
                     * and create a new JSON document out of each 'thing' node.
                     */
                    XmlMapper xmlMapper = new XmlMapper();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(istream);
                    NodeList nodeList = doc.getElementsByTagName("thing");

                    /**
                     * Collect JsonNode from each 'thing' xml node.
                     */
                    List<JsonNode> thingList = new ArrayList<>();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        Document thingDoc = builder.newDocument();
                        Node newNode = thingDoc.importNode(node, true);
                        thingDoc.appendChild(newNode);
                        thingList.add(xmlMapper.readTree(convertDocumentToString(thingDoc)));
                    }

                    /**
                     * Rebuild JSON document structure to pass to deserializer.
                     */
                    String thingsJson = "{\"things\":[";
                    String thingsContent = "";
                    for (JsonNode thingNode : thingList) {
                        thingsContent += thingNode.toString() + ",";
                    }
                    thingsContent = "".equals(thingsContent) ? thingsContent
                            : thingsContent.substring(0, thingsContent.length() - 1);
                    thingsJson += thingsContent;
                    thingsJson += "]}";

                    /**
                     * Return raw re-built 'things' or a normalized JSON document.
                     */
                    ObjectMapper objectMapper = new ObjectMapper();
                    if (shimDataRequest.getNormalize()) {
                        SimpleModule module = new SimpleModule();
                        module.addDeserializer(ShimDataResponse.class, healthVaultDataType.getNormalizer());
                        objectMapper.registerModule(module);
                        return objectMapper.readValue(thingsJson, ShimDataResponse.class);
                    } else {
                        return ShimDataResponse.result(HealthvaultShim.SHIM_KEY,
                                objectMapper.readTree(thingsJson));
                    }
                }
            });
}

From source file:org.gvnix.web.report.roo.addon.addon.ReportJspMetadataListener.java

/**
 * Generates a JSPX with a form requesting the report. The form has as many
 * radio buttons as formats has set the report.
 * /*from w  ww.ja  v a2  s .  c om*/
 * @param reportName
 * @param formats
 * @param controllerPath
 * @return
 */
private Document getReportFormJsp(String reportName, String controllerPath) {
    DocumentBuilder builder = XmlUtils.getDocumentBuilder();
    Document document = builder.newDocument();

    Map<String, String> properties = new HashMap<String, String>();

    // Add document namespaces
    Element div = (Element) document.appendChild(
            new XmlElementBuilder("div", document).addAttribute("xmlns:c", "http://java.sun.com/jsp/jstl/core")
                    .addAttribute("xmlns:fn", "http://java.sun.com/jsp/jstl/functions")
                    .addAttribute("xmlns:spring", "http://www.springframework.org/tags")
                    .addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page")
                    .addAttribute("xmlns:form", "http://www.springframework.org/tags/form")
                    .addAttribute("version", "2.0")
                    .addChild(new XmlElementBuilder("jsp:directive.page", document)
                            .addAttribute("contentType", "text/html;charset=UTF-8").build())
                    .addChild(new XmlElementBuilder("jsp:output", document)
                            .addAttribute("omit-xml-declaration", "yes").build())
                    .build());

    // Add div panel
    Element divPanel = (Element) new XmlElementBuilder("div", document)
            .addAttribute("class", "panel panel-default").build();

    // Add div header
    Element divPanelHeader = (Element) new XmlElementBuilder("div", document)
            .addAttribute("class", "panel-heading").build();

    // Add h3 title with content
    Element h3PanelTitle = (Element) new XmlElementBuilder("h3", document).addAttribute("class", "panel-title")
            .addChild(new XmlElementBuilder("spring:message", document)
                    .addAttribute("code", "label_report_" + controllerPath + "_" + reportName)
                    .addAttribute("htmlEscape", "false").build())
            .build();

    // Adding title panel to panel header
    divPanelHeader.appendChild(h3PanelTitle);

    // Adding panel header to div panel
    divPanel.appendChild(divPanelHeader);

    // Add div panel body
    Element divPanelBody = (Element) new XmlElementBuilder("div", document).addAttribute("class", "panel-body")
            .build();

    // Add if not empty error
    Element ifNotEmptyError = (Element) new XmlElementBuilder("c:if", document)
            .addAttribute("test", "${not empty error}").build();

    // Add h3 title with error message
    Element h3ErrorMessage = (Element) new XmlElementBuilder("h3", document)
            .addAttribute("class", "panel-title").addChild(new XmlElementBuilder("spring:message", document)
                    .addAttribute("code", "${error}").addAttribute("htmlEscape", "false").build())
            .build();

    // Adding h3 message to if empty error
    ifNotEmptyError.appendChild(h3ErrorMessage);

    // Adding if not empty error to divPanelBody
    divPanelBody.appendChild(ifNotEmptyError);

    // Add form element
    Element formElement = (Element) new XmlElementBuilder("form:form", document)
            .addAttribute("class", "form-horizontal").addAttribute("role", "form")
            .addAttribute("action", reportName)
            .addAttribute("id", XmlUtils.convertId("fr_" + formbackingObject.getFullyQualifiedTypeName()))
            .addAttribute("method", "GET").build();

    // Add div control group
    Element divControlGroup = (Element) new XmlElementBuilder("div", document)
            .addAttribute("class", "control-group form-group").build();

    // Add div controls col
    Element divControlsCol = (Element) new XmlElementBuilder("div", document)
            .addAttribute("class", "controls col-xs-7 col-sm-8 col-md-12 col-lg-12").build();

    // Add a drop-down select
    Element cifSelectFormat = (Element) new XmlElementBuilder("c:if", document)
            .addAttribute("test", "${not empty report_formats}").build();
    Element selectFormat = (Element) new XmlElementBuilder("select", document)
            .addAttribute("class", "form-control input-sm").addAttribute("id", "_select_format")
            .addAttribute("name", "format").build();
    Element cforEach = (Element) new XmlElementBuilder("c:forEach", document)
            .addAttribute("items", "${report_formats}").addAttribute("var", "format").build();
    Element optionFormat = (Element) new XmlElementBuilder("option", document)
            .addAttribute("id", "option_format_${format}").addAttribute("value", "${format}").build();
    Element coutFormat = (Element) new XmlElementBuilder("c:out", document)
            .addAttribute("value", "${fn:toUpperCase(format)}").build();
    optionFormat.appendChild(coutFormat);
    cforEach.appendChild(optionFormat);
    selectFormat.appendChild(cforEach);
    cifSelectFormat.appendChild(selectFormat);

    // Add input element
    Element inputElement = (Element) new XmlElementBuilder("input", document)
            .addAttribute("class", "btn btn-primary btn-block").addAttribute("type", "submit").build();

    // Adding elements to divControlsCol
    divControlsCol.appendChild(cifSelectFormat);
    divControlsCol.appendChild(inputElement);

    // Adding controls col to div control group
    divControlGroup.appendChild(divControlsCol);

    // Adding control group to form
    formElement.appendChild(divControlGroup);

    // Adding form to Panel Body
    divPanelBody.appendChild(formElement);

    // Adding Panel Body to Main Panel
    divPanel.appendChild(divPanelBody);

    // Adding Main Panel to general div
    div.appendChild(divPanel);

    // Add the message error to the application.properties
    properties.put("label_report_" + controllerPath + "_" + reportName, "Report " + reportName);

    getPropFileOperations().addProperties(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "/WEB-INF/i18n/application.properties", properties, true, false);

    return document;
}