Example usage for org.w3c.dom Element setTextContent

List of usage examples for org.w3c.dom Element setTextContent

Introduction

In this page you can find the example usage for org.w3c.dom Element setTextContent.

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:com.ibm.dbwkl.request.internal.LoggingHandler.java

/**
 * @return xml output/*from  w  w w.jav a  2  s .c om*/
 */
@Override
public Document getXML() {
    if (hasRequestOption(Options.LOG_LIST)) {
        try {
            List<LoggerEntry> logEntries = Logger.getLogEntries();

            int entriesToShow = Integer.parseInt(getRequestOption(Options.LOG_LIST));

            if (entriesToShow < logEntries.size())
                logEntries = logEntries.subList(logEntries.size() - entriesToShow, logEntries.size());
            // create the document
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();

            // create the document root node
            Element root = document.createElement("db2wklresult");
            document.appendChild(root);

            // create the result information
            Element rc = document.createElement("rc");
            rc.setTextContent(Integer.toString(this.getResult().rc));
            root.appendChild(rc);

            Element object = document.createElement("resultObject");
            object.setTextContent(
                    this.getResult().resultObj == null ? "" : this.getResult().resultObj.toString());

            Element entries = null;

            for (LoggerEntry logEntry : logEntries) {
                entries = document.createElement("logEntry");
                entries.setAttribute("formattedTime", logEntry.getFormatedTime());
                entries.setAttribute("requestName", logEntry.getRequestName());
                entries.setAttribute("loglevel", logEntry.getLevel());
                entries.setAttribute("message", logEntry.getMessage().replaceAll(String.valueOf('"'), "'"));
                entries.setAttribute("class", logEntry.getClasse());
                entries.setAttribute("method", logEntry.getMethod());
                entries.setAttribute("line", String.valueOf(logEntry.getLineNumber()));
                entries.setAttribute("thread", logEntry.getThread());
                entries.setAttribute("threadGroup", logEntry.getThreadGroup());
                object.appendChild(entries);
            }

            root.appendChild(object);

            // return the resulting document
            return document;
        } catch (ParserConfigurationException e) {
            Logger.log(e.getMessage(), LogLevel.Error);
        }
    }

    return null;
}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

@Override
public Document createJob(ZencoderJob job) throws ZencoderErrorResponseException {
    if (currentConnectionAttempt > MAX_CONNECTION_ATTEMPTS) {
        resetConnectionCount();/* w  ww . j  av a  2s . co m*/
        String message = "Reached maximum number of connection attempts for Zencoder, aborting creation of job";
        Document errorDocument = createDocumentForException(message);
        throw new ZencoderErrorResponseException(errorDocument);
    }
    Document data;
    try {
        data = job.createXML();
        if (data == null) {
            String message = "Got no XML from Job";
            LOGGER.error(message);
            resetConnectionCount();
            Document errorDocument = createDocumentForException(message);
            throw new ZencoderErrorResponseException(errorDocument);
        }
        Element apikey = data.createElement("api_key");
        apikey.setTextContent(zencoderAPIKey);
        data.getDocumentElement().appendChild(apikey);
        Document response = sendPostRequest(zencoderAPIBaseUrl + "jobs?format=xml", data);
        // a null response means the call did not get through
        // we should try again, since the job has not been started
        if (response == null) {
            currentConnectionAttempt++;
            // maybe delay this call by a few seconds?
            return createJob(job);
        }
        String id = (String) xPath.evaluate("/api-response/job/id", response, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(id)) {
            job.setJobId(Integer.parseInt(id));
            resetConnectionCount();
            return response;
        }
        completeJobInfo(job, response);
        LOGGER.error("Error when sending request to Zencoder: ", response);
        resetConnectionCount();
        throw new ZencoderErrorResponseException(response);
    } catch (ParserConfigurationException e) {
        LOGGER.error("Parser threw Exception", e);
    } catch (XPathExpressionException e) {
        LOGGER.error("XPath threw Exception", e);
    }
    resetConnectionCount();
    return null;
}

From source file:org.gvnix.dynamic.configuration.roo.addon.ConfigurationsImpl.java

/**
 * Add new property element containing key and value elements on component.
 * /*from ww  w  .j a v a2  s. c  o m*/
 * @param comp Component where add property
 * @param key Property key
 * @param value Property value
 */
private void addProperty(Element comp, String key, String value) {

    // Get document and create property element
    Document doc = comp.getOwnerDocument();
    Element propElem = doc.createElement(PROPERTY_ELEMENT_NAME);

    // Create key
    Element keyElem = doc.createElement(KEY_ELEMENT_NAME);
    keyElem.setTextContent(key);
    propElem.appendChild(keyElem);

    // Create value element
    Element valueElem = doc.createElement(VALUE_ELEMENT_NAME);
    valueElem.setTextContent(value);
    propElem.appendChild(valueElem);

    // Add property on component
    comp.appendChild(propElem);
}

From source file:de.interactive_instruments.ShapeChange.Target.Metadata.ApplicationSchemaMetadata.java

protected void processProfilesMetadata(Element appSchemaElement) {

    Set<Info> schemaElements = new TreeSet<Info>();

    // identify all classes and properties that belong to the schema
    SortedSet<ClassInfo> schemaClasses = model.classes(schemaPi);

    if (schemaClasses != null) {

        for (ClassInfo ci : schemaClasses) {
            schemaElements.add(ci);/*from   w ww.  jav  a  2  s.  c  o m*/

            for (PropertyInfo pi : ci.properties().values()) {
                schemaElements.add(pi);
            }
        }
    }

    // identify the profiles of all relevant schema elements
    SortedSet<String> profileNames = new TreeSet<String>();

    for (Info i : schemaElements) {

        String[] profilesTVs = i.taggedValuesForTag("profiles");

        for (String profilesTV : profilesTVs) {

            if (profilesTV.trim().length() > 0) {

                try {

                    ProfileIdentifierMap piMap = ProfileIdentifierMap.parse(profilesTV, IdentifierPattern.loose,
                            i.name());

                    profileNames.addAll(piMap.getProfileIdentifiersByName().keySet());

                } catch (MalformedProfileIdentifierException e) {
                    result.addWarning(this, 9, profilesTV, i.fullNameInSchema(), e.getMessage());
                }
            }
        }
    }

    // now create the ProfilesMetadata XML element
    Element e_pm = document.createElement("ProfilesMetadata");

    for (String name : profileNames) {
        Element e_cp = document.createElement("containedProfile");
        e_cp.setTextContent(name);
        e_pm.appendChild(e_cp);
    }

    Element e_m = document.createElement("metadata");

    e_m.appendChild(e_pm);

    appSchemaElement.appendChild(e_m);
}

From source file:com.photon.phresco.plugins.JavaPackage.java

private void updatemainClassName() throws MojoExecutionException {
    try {/*from ww  w  .j  a va  2 s  .c om*/
        if (StringUtils.isEmpty(mainClassName)) {
            return;
        }
        File pom = project.getFile();
        List<Element> configList = new ArrayList<Element>();
        PomProcessor pomprocessor = new PomProcessor(pom);
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element archive = doc.createElement(JAVA_POM_ARCHIVE);
        Element manifest = doc.createElement(JAVA_POM_MANIFEST);
        Element addClasspath = doc.createElement(JAVA_POM_ADD_PATH);
        addClasspath.setTextContent("true");
        manifest.appendChild(addClasspath);
        Element mainClass = doc.createElement(JAVA_POM_MAINCLASS);
        mainClass.setTextContent(mainClassName);
        manifest.appendChild(addClasspath);
        manifest.appendChild(mainClass);
        archive.appendChild(manifest);
        configList.add(archive);

        pomprocessor.addConfiguration(JAR_PLUGIN_GROUPID, JAR_PLUGIN_ARTIFACT_ID, configList, false);
        pomprocessor.save();
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:eu.optimis.sm.gui.server.XmlUtil.java

public String getObjXml(String xml) {
    try {/*from  ww w  .  j  a  va  2 s. c om*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        NodeList timestampList = doc.getElementsByTagName("metric_timestamp");
        for (int i = 0; i < timestampList.getLength(); i++) {
            Element ts = (Element) timestampList.item(i);
            String tsLangType = ts.getTextContent();
            try {
                long millis = 0;
                millis = Long.parseLong(tsLangType);
                Date udate = new Date(millis * 1000);
                String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(udate);
                ts.setTextContent(timestamp);
            } catch (NumberFormatException e) {

            }
        }
        String rs = xmlToString(doc);
        return rs;

    } catch (SAXException e) {
        return null;
    } catch (ParserConfigurationException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.uisteps.utils.api.zapi.Zapi.java

private void exportToPom(File file, String cycleId, String clonedCycleId, String projectKey, String metaFilter,
        Boolean createExecutions, RestApi api)
        throws RestApiException, IOException, ParserConfigurationException, SAXException,
        TransformerConfigurationException, TransformerException, JSONException {

    StringBuilder executionsExport = new StringBuilder();

    JSONArray executions = api.getRequest("/rest/zapi/latest/execution?cycleId=" + clonedCycleId).get()
            .toJSONObject().getJSONArray("executions");

    for (int i = 0; i < executions.length(); i++) {
        JSONObject execution = executions.getJSONObject(i);
        executionsExport.append("+").append(execution.getString("issueKey").replace("-", "")).append(" ");
    }/*from w w w .  ja v a2 s.c om*/

    if (metaFilter != null && !metaFilter.isEmpty()) {
        executionsExport.append(" ").append(metaFilter);
    }

    Document doc = getXML(file);

    Element project = (Element) doc.getElementsByTagName("project").item(0);
    Element properties = (Element) project.getElementsByTagName("properties").item(0);

    Element metafilter = doc.createElement("metafilter");
    metafilter.setTextContent(executionsExport.toString());

    properties.appendChild(metafilter);

    Element cycleIdElement = doc.createElement("cycleId");
    cycleIdElement.setTextContent(cycleId);

    properties.appendChild(cycleIdElement);

    Element projectKeyElement = doc.createElement("projectKey");
    projectKeyElement.setTextContent(projectKey);

    properties.appendChild(projectKeyElement);

    Element createExecutionsElement = doc.createElement("createExecutions");
    createExecutionsElement.setTextContent(createExecutions.toString());

    properties.appendChild(createExecutionsElement);

    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.transform(new DOMSource(doc), new StreamResult(file));

}

From source file:eu.optimis.mi.gui.server.XmlUtil.java

public String getObjXml(String xml) {
    try {// www. ja va2 s .  c om
        // Create a builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        NodeList timestampList = doc.getElementsByTagName("metric_timestamp");
        for (int i = 0; i < timestampList.getLength(); i++) {
            Element ts = (Element) timestampList.item(i);
            String tsLangType = ts.getTextContent();
            try {
                long millis = 0;
                millis = Long.parseLong(tsLangType);
                Date udate = new Date(millis * 1000);
                String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(udate);
                ts.setTextContent(timestamp);
            } catch (NumberFormatException e) {

            }
        }
        String rs = xmlToString(doc);
        return rs;

    } catch (SAXException e) {
        return null;
    } catch (ParserConfigurationException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.photon.phresco.impl.ConfigManagerImpl.java

private void createProperties(Element configNode, Properties properties) {
    Set<Object> keySet = properties.keySet();
    for (Object key : keySet) {
        String value = (String) properties.get(key);
        Element propNode = document.createElement(key.toString());
        propNode.setTextContent(value);
        configNode.appendChild(propNode);
    }/*from   w  w w  .j a v  a  2s.  com*/
}

From source file:org.gvnix.dynamic.configuration.roo.addon.ConfigurationsImpl.java

/**
 * {@inheritDoc}//  www .  j ava2  s . c  o m
 */
public void deleteConfiguration(Element conf) {

    // Remove configuration element and their child component elements
    List<Element> comps = XmlUtils.findElements(COMPONENT_ELEMENT_NAME, conf);
    for (Element comp : comps) {
        conf.removeChild(comp);
    }
    conf.getParentNode().removeChild(conf);

    // If active configuration, remove the reference on configuration file
    Element activeConf = isActiveConfiguration(conf);
    if (activeConf != null) {
        activeConf.setTextContent("");
    }

    // Update the configuration file
    saveConfiguration(conf);
}