Example usage for org.w3c.dom Document createElement

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

Introduction

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

Prototype

public Element createElement(String tagName) throws DOMException;

Source Link

Document

Creates an element of the type specified.

Usage

From source file:Main.java

public static Element createElement(final Document document, final String qName,
        final Optional<String> namespaceURI) {
    if (namespaceURI.isPresent()) {
        final Element element = document.createElementNS(namespaceURI.get(), qName);
        String name = XMLNS_ATTRIBUTE_KEY;
        if (element.getPrefix() != null) {
            name += ":" + element.getPrefix();
        }//from www . j a v  a  2  s.co  m
        element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
        return element;
    }
    return document.createElement(qName);
}

From source file:Main.java

/**
 * Creates (only if necessary) and returns the element which is at the end of the specified
 * path.//from   w  ww. j  a v a 2s . c om
 * @param doc the target document where the specified path should be created
 * @param path a dot separated string indicating the path to be created
 * @return the component at the end of the newly created path.
 */
public static Element createLastPathComponent(Document doc, String[] path) {
    Element parent = (Element) doc.getFirstChild();
    if (path == null || parent == null || doc == null)
        throw new IllegalArgumentException("Document parent and path must not be null");

    Element e = parent;
    for (int i = 0; i < path.length; i++) {
        Element newEl = getChildElementByTagName(e, path[i]);
        if (newEl == null) {
            newEl = doc.createElement(path[i]);
            e.appendChild(newEl);
        }
        e = newEl;
    }
    return e;
}

From source file:be.fedict.eid.dss.ws.DSSUtil.java

/**
 * Adds a DSS Verification Report to specified optional output element from
 * the specified list of {@link SignatureInfo}'s
 * //from  w w w. j a va  2  s  .  c  om
 * @param optionalOutput
 *            optional output to add verification report to
 * @param signatureInfos
 *            signature infos to use in verification report.
 */
public static void addVerificationReport(AnyType optionalOutput, List<SignatureInfo> signatureInfos) {

    LOG.debug("return verification report");
    VerificationReportType verificationReport = vrObjectFactory.createVerificationReportType();
    List<IndividualReportType> individualReports = verificationReport.getIndividualReport();
    for (SignatureInfo signatureInfo : signatureInfos) {
        X509Certificate signerCertificate = signatureInfo.getSigner();
        IndividualReportType individualReport = vrObjectFactory.createIndividualReportType();
        individualReports.add(individualReport);

        SignedObjectIdentifierType signedObjectIdentifier = vrObjectFactory.createSignedObjectIdentifierType();
        individualReport.setSignedObjectIdentifier(signedObjectIdentifier);
        SignedPropertiesType signedProperties = vrObjectFactory.createSignedPropertiesType();
        signedObjectIdentifier.setSignedProperties(signedProperties);
        SignedSignaturePropertiesType signedSignatureProperties = vrObjectFactory
                .createSignedSignaturePropertiesType();
        signedProperties.setSignedSignatureProperties(signedSignatureProperties);
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(signatureInfo.getSigningTime());
        signedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar));

        be.fedict.eid.dss.ws.profile.vr.jaxb.dss.Result individualResult = vrDssObjectFactory.createResult();
        individualReport.setResult(individualResult);
        individualResult.setResultMajor(DSSConstants.RESULT_MAJOR_SUCCESS);
        individualResult.setResultMinor(DSSConstants.RESULT_MINOR_VALID_SIGNATURE);

        be.fedict.eid.dss.ws.profile.vr.jaxb.dss.AnyType details = vrDssObjectFactory.createAnyType();
        individualReport.setDetails(details);

        DetailedSignatureReportType detailedSignatureReport = vrObjectFactory
                .createDetailedSignatureReportType();
        details.getAny().add(vrObjectFactory.createDetailedSignatureReport(detailedSignatureReport));
        VerificationResultType formatOKVerificationResult = vrObjectFactory.createVerificationResultType();
        formatOKVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);
        detailedSignatureReport.setFormatOK(formatOKVerificationResult);

        SignatureValidityType signatureOkSignatureValidity = vrObjectFactory.createSignatureValidityType();
        detailedSignatureReport.setSignatureOK(signatureOkSignatureValidity);
        VerificationResultType sigMathOkVerificationResult = vrObjectFactory.createVerificationResultType();
        signatureOkSignatureValidity.setSigMathOK(sigMathOkVerificationResult);
        sigMathOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        if (null != signatureInfo.getRole()) {
            PropertiesType properties = vrObjectFactory.createPropertiesType();
            detailedSignatureReport.setProperties(properties);
            SignedPropertiesType vrSignedProperties = vrObjectFactory.createSignedPropertiesType();
            properties.setSignedProperties(vrSignedProperties);
            SignedSignaturePropertiesType vrSignedSignatureProperties = vrObjectFactory
                    .createSignedSignaturePropertiesType();
            vrSignedProperties.setSignedSignatureProperties(vrSignedSignatureProperties);
            vrSignedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar));
            SignerRoleType signerRole = vrObjectFactory.createSignerRoleType();
            vrSignedSignatureProperties.setSignerRole(signerRole);
            ClaimedRolesListType claimedRolesList = vrXadesObjectFactory.createClaimedRolesListType();
            signerRole.setClaimedRoles(claimedRolesList);
            be.fedict.eid.dss.ws.profile.vr.jaxb.xades.AnyType claimedRoleAny = vrXadesObjectFactory
                    .createAnyType();
            claimedRolesList.getClaimedRole().add(claimedRoleAny);
            claimedRoleAny.getContent().add(signatureInfo.getRole());
        }

        CertificatePathValidityType certificatePathValidity = vrObjectFactory
                .createCertificatePathValidityType();
        detailedSignatureReport.setCertificatePathValidity(certificatePathValidity);

        VerificationResultType certPathVerificationResult = vrObjectFactory.createVerificationResultType();
        certPathVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);
        certificatePathValidity.setPathValiditySummary(certPathVerificationResult);

        X509IssuerSerialType certificateIdentifier = vrXmldsigObjectFactory.createX509IssuerSerialType();
        certificatePathValidity.setCertificateIdentifier(certificateIdentifier);
        certificateIdentifier.setX509IssuerName(signerCertificate.getIssuerX500Principal().toString());
        certificateIdentifier.setX509SerialNumber(signerCertificate.getSerialNumber());

        CertificatePathValidityVerificationDetailType certificatePathValidityVerificationDetail = vrObjectFactory
                .createCertificatePathValidityVerificationDetailType();
        certificatePathValidity.setPathValidityDetail(certificatePathValidityVerificationDetail);
        CertificateValidityType certificateValidity = vrObjectFactory.createCertificateValidityType();
        certificatePathValidityVerificationDetail.getCertificateValidity().add(certificateValidity);
        certificateValidity.setCertificateIdentifier(certificateIdentifier);
        certificateValidity.setSubject(signerCertificate.getSubjectX500Principal().toString());

        VerificationResultType chainingOkVerificationResult = vrObjectFactory.createVerificationResultType();
        certificateValidity.setChainingOK(chainingOkVerificationResult);
        chainingOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        VerificationResultType validityPeriodOkVerificationResult = vrObjectFactory
                .createVerificationResultType();
        certificateValidity.setValidityPeriodOK(validityPeriodOkVerificationResult);
        validityPeriodOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        VerificationResultType extensionsOkVerificationResult = vrObjectFactory.createVerificationResultType();
        certificateValidity.setExtensionsOK(extensionsOkVerificationResult);
        extensionsOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        try {
            certificateValidity.setCertificateValue(signerCertificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("X509 encoding error: " + e.getMessage(), e);
        }

        certificateValidity.setSignatureOK(signatureOkSignatureValidity);

        CertificateStatusType certificateStatus = vrObjectFactory.createCertificateStatusType();
        certificateValidity.setCertificateStatus(certificateStatus);
        VerificationResultType certStatusOkVerificationResult = vrObjectFactory.createVerificationResultType();
        certificateStatus.setCertStatusOK(certStatusOkVerificationResult);
        certStatusOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);
    }

    Document newDocument = documentBuilder.newDocument();
    Element newElement = newDocument.createElement("newNode");
    try {
        vrMarshaller.marshal(vrObjectFactory.createVerificationReport(verificationReport), newElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
    Element verificationReportElement = (Element) newElement.getFirstChild();
    optionalOutput.getAny().add(verificationReportElement);
}

From source file:Main.java

private static void makeNamelist(Document doc) {
    String names = null;/*from  w  ww. j  a  va 2  s  .  c  om*/
    Element root = doc.getDocumentElement();
    NodeList nameElements = root.getElementsByTagName("name");
    for (int i = 0; i < nameElements.getLength(); i++) {
        Element name = (Element) nameElements.item(i);
        Text nametext = (Text) name.getFirstChild();
        if (names == null) {
            names = nametext.getData();
        } else {
            names += ", " + nametext.getData();
        }
    }
    Element namelist = doc.createElement("names");
    Text namelisttext = doc.createTextNode(names);
    namelist.appendChild(namelisttext);
    root.insertBefore(namelist, root.getFirstChild());
}

From source file:com.hpe.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java

private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException {
    /*<Mtbx>//  www  .  j  a  v a2  s  .co m
    <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1">
     <Parameter name="A" value="abc" type="string"/>
     <DataTable path="${WORKSPACE}\aa\bbb.xslx"/>
      .
     </Test>
     <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2">
    <Parameter name="p1" value="123" type="int"/>
    <Parameter name="p4" value="123.4" type="float"/>
     .
     </Test>
    </Mtbx>*/

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Mtbx");
        doc.appendChild(rootElement);

        for (TestExecutionInfo test : tests) {
            Element testElement = doc.createElement("Test");
            String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName())
                    ? test.getPackageName() + "\\"
                    : "") + test.getTestName();
            testElement.setAttribute("name", packageAndTestName);
            String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                    + (StringUtils.isEmpty(test.getPackageName()) ? ""
                            : OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getPackageName())
                    + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getTestName();
            testElement.setAttribute("path", path);

            if (StringUtils.isNotEmpty(test.getDataTable())) {
                Element dataTableElement = doc.createElement("DataTable");
                dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                        + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getDataTable());
                testElement.appendChild(dataTableElement);
            }

            rootElement.appendChild(testElement);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));

        return writer.toString();
    } catch (Exception e) {
        throw new IOException("Failed to build MTBX content : " + e.getMessage());
    }

}

From source file:com.google.visualization.datasource.render.HtmlRenderer.java

/**
 * Generates an HTML string representation of a data table.
 * /*from   www .j a  va  2  s. c o  m*/
 * @param dataTable The data table to render.
 * @param locale The locale. If null, uses the default from
 *     {@code LocaleUtil#getDefaultLocale}.
 *
 * @return The char sequence with the html string.
 */
public static CharSequence renderDataTable(DataTable dataTable, ULocale locale) {
    // Create an xml document with head and an empty body.
    Document document = createDocument();
    Element bodyElement = appendHeadAndBody(document);

    // Populate the xml document.
    Element tableElement = document.createElement("table");
    bodyElement.appendChild(tableElement);
    tableElement.setAttribute("border", "1");
    tableElement.setAttribute("cellpadding", "2");
    tableElement.setAttribute("cellspacing", "0");

    // Labels tr element.
    List<ColumnDescription> columnDescriptions = dataTable.getColumnDescriptions();
    Element trElement = document.createElement("tr");
    trElement.setAttribute("style", "font-weight: bold; background-color: #aaa;");
    for (ColumnDescription columnDescription : columnDescriptions) {
        Element tdElement = document.createElement("td");
        tdElement.setTextContent(columnDescription.getLabel());
        trElement.appendChild(tdElement);
    }
    tableElement.appendChild(trElement);

    Map<ValueType, ValueFormatter> formatters = ValueFormatter.createDefaultFormatters(locale);
    // Table tr elements.
    int rowCount = 0;
    for (TableRow row : dataTable.getRows()) {
        rowCount++;
        trElement = document.createElement("tr");
        String backgroundColor = (rowCount % 2 != 0) ? "#f0f0f0" : "#ffffff";
        trElement.setAttribute("style", "background-color: " + backgroundColor);

        List<TableCell> cells = row.getCells();
        for (int c = 0; c < cells.size(); c++) {
            ValueType valueType = columnDescriptions.get(c).getType();
            TableCell cell = cells.get(c);
            String cellFormattedText = cell.getFormattedValue();
            if (cellFormattedText == null) {
                cellFormattedText = formatters.get(cell.getType()).format(cell.getValue());
            }

            Element tdElement = document.createElement("td");
            if (cell.isNull()) {
                tdElement.setTextContent("\u00a0");
            } else {
                switch (valueType) {
                case NUMBER:
                    tdElement.setAttribute("align", "right");
                    tdElement.setTextContent(cellFormattedText);
                    break;
                case BOOLEAN:
                    BooleanValue booleanValue = (BooleanValue) cell.getValue();
                    tdElement.setAttribute("align", "center");
                    if (booleanValue.getValue()) {
                        tdElement.setTextContent("\u2714"); // Check mark.
                    } else {
                        tdElement.setTextContent("\u2717"); // X mark.
                    }
                    break;
                default:
                    if (StringUtils.isEmpty(cellFormattedText)) {
                        tdElement.setTextContent("\u00a0"); // nbsp.
                    } else {
                        tdElement.setTextContent(cellFormattedText);
                    }
                }
            }
            trElement.appendChild(tdElement);
        }
        tableElement.appendChild(trElement);
    }
    bodyElement.appendChild(tableElement);

    // Warnings:
    for (Warning warning : dataTable.getWarnings()) {
        bodyElement.appendChild(document.createElement("br"));
        bodyElement.appendChild(document.createElement("br"));
        Element messageElement = document.createElement("div");
        messageElement.setTextContent(
                warning.getReasonType().getMessageForReasonType() + ". " + warning.getMessage());
        bodyElement.appendChild(messageElement);
    }

    return transformDocumentToHtmlString(document);
}

From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java

/**
 * query to xml/*from   w w w. j  a  v a  2  s  .c om*/
 * 
 * @param userDB
 * @param strQuery
 * @param listParam
 */
@SuppressWarnings("deprecation")
public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam)
        throws Exception {
    final StringWriter stWriter = new StringWriter();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();
    final Element results = doc.createElement("Results");
    doc.appendChild(results);

    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    QueryRunner qr = new QueryRunner(client.getDataSource());
    qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() {

        @Override
        public Object handle(ResultSet rs) throws SQLException {
            ResultSetMetaData metaData = rs.getMetaData();

            while (rs.next()) {
                Element row = doc.createElement("Row");
                results.appendChild(row);
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i) == null ? "" : rs.getObject(i);
                    Element node = doc.createElement(columnName);
                    node.appendChild(doc.createTextNode(value.toString()));
                    row.appendChild(node);
                }
            }

            return stWriter.toString();
        }
    });

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setAttribute("indent-number", 4);

    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1");
    StreamResult sr = new StreamResult(stWriter);
    transformer.transform(domSource, sr);

    return stWriter.toString();
}

From source file:com.moviejukebox.tools.DOMHelper.java

/**
 * Append a child element to a parent element with a single attribute/value pair
 *
 * @param doc//from w ww . j  a  v  a  2s.  c o  m
 * @param parentElement
 * @param elementName
 * @param elementValue
 * @param attribName
 * @param attribValue
 */
public static void appendChild(Document doc, Element parentElement, String elementName, String elementValue,
        String attribName, String attribValue) {
    Element child = doc.createElement(elementName);
    Text text = doc.createTextNode(elementValue);
    child.appendChild(text);
    child.setAttribute(attribName, attribValue);
    parentElement.appendChild(child);
}

From source file:com.nridge.core.base.std.XMLUtl.java

public static void makeElemBoolValue(Document aDocument, Element anElement, String aName, boolean aFlag) {
    String aValue;//from  w ww .  j a v a 2 s .  c  om
    Element subElement;

    if (StringUtils.isNotEmpty(aName)) {
        if (aFlag)
            aValue = XML_UPPER_YES;
        else
            aValue = XML_UPPER_NO;
        subElement = aDocument.createElement(aName);
        subElement.appendChild(aDocument.createTextNode(aValue));
        anElement.appendChild(subElement);
    }
}

From source file:com.moviejukebox.tools.DOMHelper.java

/**
 * Add a child element to a parent element with a set of attributes
 *
 * @param doc//w w  w. j  av  a2  s.  c  o m
 * @param parentElement
 * @param elementName
 * @param elementValue
 * @param childAttributes
 */
public static void appendChild(Document doc, Element parentElement, String elementName, String elementValue,
        Map<String, String> childAttributes) {
    Element child = doc.createElement(elementName);
    Text text = doc.createTextNode(elementValue);
    child.appendChild(text);

    if (childAttributes != null && !childAttributes.isEmpty()) {
        for (Map.Entry<String, String> attrib : childAttributes.entrySet()) {
            child.setAttribute(attrib.getKey(), attrib.getValue());
        }
    }

    parentElement.appendChild(child);
}