Example usage for org.w3c.dom Document createTextNode

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

Introduction

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

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:ai.aitia.meme.paramsweep.intellisweepPlugin.JgapGAPlugin.java

private void saveParameterOrGene(final DefaultMutableTreeNode node, final Element chromosomeElement) {
    final Document document = chromosomeElement.getOwnerDocument();

    final ParameterOrGene userObj = (ParameterOrGene) node.getUserObject();
    final ParameterInfo info = userObj.getInfo();

    if (userObj.isGene()) {
        final GeneInfo geneInfo = userObj.getGeneInfo();

        final Element geneElement = document.createElement(GENE);
        chromosomeElement.appendChild(geneElement);

        geneElement.setAttribute(WizardSettingsManager.NAME, info.getName());
        geneElement.setAttribute(WizardSettingsManager.TYPE, geneInfo.getValueType());

        if (GeneInfo.INTERVAL.equals(geneInfo.getValueType())) {
            geneElement.setAttribute(IS_INTEGER, String.valueOf(geneInfo.isIntegerVals()));
            geneElement.setAttribute(MIN_VALUE, String.valueOf(geneInfo.getMinValue()));
            geneElement.setAttribute(MAX_VALUE, String.valueOf(geneInfo.getMaxValue()));
        } else if (GeneInfo.LIST.equals(geneInfo.getValueType())) {
            for (final Object value : geneInfo.getValueRange()) {
                final Element element = document.createElement(LIST_VALUE);
                geneElement.appendChild(element);
                element.appendChild(document.createTextNode(String.valueOf(value)));
            }/*w w w  . ja  v a  2s  . c o  m*/
        }
    } else {
        final Element paramElement = document.createElement(PARAMETER);
        chromosomeElement.appendChild(paramElement);

        paramElement.setAttribute(WizardSettingsManager.NAME, info.getName());
        paramElement.appendChild(document.createTextNode(String.valueOf(info.getValue())));
    }
}

From source file:com.microsoft.windowsazure.management.sql.DatabaseOperationsImpl.java

/**
* Updates the properties of an Azure SQL Database.
*
* @param serverName Required. The name of the Azure SQL Database Server
* where the database is hosted./*w w w. j a  va2s . c  om*/
* @param databaseName Required. The name of the Azure SQL Database to be
* updated.
* @param parameters Required. The parameters for the Update Database
* operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Contains the response from a request to Update Database.
*/
@Override
public DatabaseUpdateResponse update(String serverName, String databaseName,
        DatabaseUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEdition() == null) {
        throw new NullPointerException("parameters.Edition");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("databaseName", databaseName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceResource");
    requestDoc.appendChild(serviceResourceElement);

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        serviceResourceElement.appendChild(nameElement);
    }

    Element editionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Edition");
    editionElement.appendChild(requestDoc.createTextNode(parameters.getEdition()));
    serviceResourceElement.appendChild(editionElement);

    if (parameters.getMaximumDatabaseSizeInGB() != null) {
        Element maxSizeGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeGB");
        maxSizeGBElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getMaximumDatabaseSizeInGB())));
        serviceResourceElement.appendChild(maxSizeGBElement);
    }

    if (parameters.getMaximumDatabaseSizeInBytes() != null) {
        Element maxSizeBytesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeBytes");
        maxSizeBytesElement.appendChild(
                requestDoc.createTextNode(Long.toString(parameters.getMaximumDatabaseSizeInBytes())));
        serviceResourceElement.appendChild(maxSizeBytesElement);
    }

    if (parameters.getServiceObjectiveId() != null) {
        Element serviceObjectiveIdElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
        serviceObjectiveIdElement.appendChild(requestDoc.createTextNode(parameters.getServiceObjectiveId()));
        serviceResourceElement.appendChild(serviceObjectiveIdElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        DatabaseUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseUpdateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                Database serviceResourceInstance = new Database();
                result.setDatabase(serviceResourceInstance);

                Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Id");
                if (idElement != null) {
                    int idInstance;
                    idInstance = DatatypeConverter.parseInt(idElement.getTextContent());
                    serviceResourceInstance.setId(idInstance);
                }

                Element editionElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Edition");
                if (editionElement2 != null) {
                    String editionInstance;
                    editionInstance = editionElement2.getTextContent();
                    serviceResourceInstance.setEdition(editionInstance);
                }

                Element maxSizeGBElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeGB");
                if (maxSizeGBElement2 != null) {
                    int maxSizeGBInstance;
                    maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance);
                }

                Element maxSizeBytesElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes");
                if (maxSizeBytesElement2 != null) {
                    long maxSizeBytesInstance;
                    maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance);
                }

                Element collationNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CollationName");
                if (collationNameElement != null) {
                    String collationNameInstance;
                    collationNameInstance = collationNameElement.getTextContent();
                    serviceResourceInstance.setCollationName(collationNameInstance);
                }

                Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CreationDate");
                if (creationDateElement != null) {
                    Calendar creationDateInstance;
                    creationDateInstance = DatatypeConverter
                            .parseDateTime(creationDateElement.getTextContent());
                    serviceResourceInstance.setCreationDate(creationDateInstance);
                }

                Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsFederationRoot");
                if (isFederationRootElement != null) {
                    boolean isFederationRootInstance;
                    isFederationRootInstance = DatatypeConverter
                            .parseBoolean(isFederationRootElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsFederationRoot(isFederationRootInstance);
                }

                Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsSystemObject");
                if (isSystemObjectElement != null) {
                    boolean isSystemObjectInstance;
                    isSystemObjectInstance = DatatypeConverter
                            .parseBoolean(isSystemObjectElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsSystemObject(isSystemObjectInstance);
                }

                Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SizeMB");
                if (sizeMBElement != null) {
                    String sizeMBInstance;
                    sizeMBInstance = sizeMBElement.getTextContent();
                    serviceResourceInstance.setSizeMB(sizeMBInstance);
                }

                Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorCode");
                if (serviceObjectiveAssignmentErrorCodeElement != null) {
                    String serviceObjectiveAssignmentErrorCodeInstance;
                    serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(
                            serviceObjectiveAssignmentErrorCodeInstance);
                }

                Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorDescription");
                if (serviceObjectiveAssignmentErrorDescriptionElement != null) {
                    String serviceObjectiveAssignmentErrorDescriptionInstance;
                    serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(
                            serviceObjectiveAssignmentErrorDescriptionInstance);
                }

                Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentState");
                if (serviceObjectiveAssignmentStateElement != null) {
                    String serviceObjectiveAssignmentStateInstance;
                    serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement
                            .getTextContent();
                    serviceResourceInstance
                            .setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance);
                }

                Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentStateDescription");
                if (serviceObjectiveAssignmentStateDescriptionElement != null) {
                    String serviceObjectiveAssignmentStateDescriptionInstance;
                    serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(
                            serviceObjectiveAssignmentStateDescriptionInstance);
                }

                Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentSuccessDate");
                if (serviceObjectiveAssignmentSuccessDateElement != null) {
                    String serviceObjectiveAssignmentSuccessDateInstance;
                    serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(
                            serviceObjectiveAssignmentSuccessDateInstance);
                }

                Element serviceObjectiveIdElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
                if (serviceObjectiveIdElement2 != null) {
                    String serviceObjectiveIdInstance;
                    serviceObjectiveIdInstance = serviceObjectiveIdElement2.getTextContent();
                    serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance);
                }

                Element assignedServiceObjectiveIdElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "AssignedServiceObjectiveId");
                if (assignedServiceObjectiveIdElement != null) {
                    String assignedServiceObjectiveIdInstance;
                    assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.getTextContent();
                    serviceResourceInstance.setAssignedServiceObjectiveId(assignedServiceObjectiveIdInstance);
                }

                Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "RecoveryPeriodStartDate");
                if (recoveryPeriodStartDateElement != null
                        && recoveryPeriodStartDateElement.getTextContent() != null
                        && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) {
                    Calendar recoveryPeriodStartDateInstance;
                    recoveryPeriodStartDateInstance = DatatypeConverter
                            .parseDateTime(recoveryPeriodStartDateElement.getTextContent());
                    serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance);
                }

                Element nameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement2 != null) {
                    String nameInstance;
                    nameInstance = nameElement2.getTextContent();
                    serviceResourceInstance.setName(nameInstance);
                }

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.collabnet.tracker.core.TrackerWebServicesClient.java

public ClientArtifactListXMLHelper createOrUpdateArtifactList(Document doc, List<ClientArtifact> artifacts,
        Long lastReadOn, boolean provideReason, boolean isFoundReasonForCurrentlyProcessedArtifact,
        String reasonForCurrentlyProcessedArtifact) throws Exception {
    EngineConfiguration config = mClient.getEngineConfiguration();
    DispatcherService service = new DispatcherServiceLocator(config);
    URL portAddress = mClient.constructServiceURL("/ws/Dispatcher");
    Dispatcher theService = service.getDispatcher(portAddress);
    Element root = doc.getDocumentElement();

    Element artifactListNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "artifactList");
    root.appendChild(artifactListNode);//  www .ja v  a2s .  com

    // TODO: Move all the below code to clientArtifact.java?

    HashMap<String, Integer> nameSpaces = new HashMap<String, Integer>();
    // List<String> nameSpaces = new ArrayList<String>();
    int nameSpaceCount = 1;
    nameSpaces.put(DEFAULT_NAMESPACE, nameSpaceCount);

    for (int i = 0; i < artifacts.size(); i++) {
        ClientArtifact ca = artifacts.get(i);
        String nsXNameSpace = ca.getNamespace();
        String artifactType = ca.getTagName();
        // int nsCtr;
        // check if the namespace alrady exists in the xml so far
        if (nameSpaces.get(nsXNameSpace) == null) {
            nameSpaces.put(nsXNameSpace, ++nameSpaceCount);
        }

        String nsNumberString = "ns" + nameSpaces.get(nsXNameSpace) + ":";

        Element artifactNode = doc.createElementNS(nsXNameSpace, nsNumberString + artifactType);
        artifactListNode.appendChild(artifactNode);

        Element modByNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + MODIFIED_BY_FIELD_NAME);
        modByNode.appendChild(doc.createTextNode(mClient.getUserName()));
        artifactNode.appendChild(modByNode);
        if (lastReadOn != null) {
            Element lastReadNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + LAST_READ_ON_FIELD_NAME);
            lastReadNode.appendChild(doc.createTextNode(Long.toString(lastReadOn)));
            artifactNode.appendChild(lastReadNode);
        } else {
            Element lastReadNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + LAST_READ_ON_FIELD_NAME);
            lastReadNode.appendChild(doc.createTextNode(Long.toString(new Date().getTime())));
            artifactNode.appendChild(lastReadNode);
        }

        // Add each attribute
        Map<String, List<String>> textAttributes = ca.getAttributes();

        for (Map.Entry<String, List<String>> attributeEntry : textAttributes.entrySet()) {
            String attribute = attributeEntry.getKey();
            List<String> values = attributeEntry.getValue();

            // strip the namespace from the attribute key
            String[] parts = attribute.substring(1).split("\\}");
            String attributeNamespace = parts[0];
            attribute = parts[1];
            if (nameSpaces.get(attributeNamespace) == null) {
                nameSpaces.put(attributeNamespace, ++nameSpaceCount);
            }
            nsNumberString = "ns" + nameSpaces.get(attributeNamespace) + ":";
            Element attributeNode = doc.createElementNS(attributeNamespace, nsNumberString + attribute);
            if (values.size() > 1 || (attributeNamespace.equals(DEFAULT_NAMESPACE) && attribute.equals("id"))) {
                for (String value : values) {
                    if (!(StringUtils.isEmpty(value))) {

                        Element valueNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:value");
                        // valueNode.setNodeValue(value);
                        // we do not need this line any more because the
                        // GenericArtifactXMLHelper will care
                        // about it
                        // value =
                        // TrackerUtil.removeInvalidXmlCharacters(value);
                        valueNode.appendChild(doc.createTextNode(value));
                        attributeNode.appendChild(valueNode);
                    }
                }
            } else {
                // TODO: consider the namespace of the attributes?
                // attributeNode.setNodeValue(values.get(0));
                String value = values.get(0);
                value = TrackerUtil.removeInvalidXmlCharacters(value);
                if (value == null)
                    value = "";
                attributeNode.appendChild(doc.createTextNode(value));
            }
            artifactNode.appendChild(attributeNode);
        }
        List<ClientArtifactComment> comments = ca.getComments();
        for (ClientArtifactComment comment : comments) {
            String commentText = comment.getCommentText();
            Element commentNode = doc.createElementNS("urn:ws.tracker.collabnet.com", "ns1:" + "comment");
            Element textNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "text");
            commentText = TrackerUtil.removeInvalidXmlCharacters(commentText);
            textNode.appendChild(doc.createTextNode(commentText));
            commentNode.appendChild(textNode);
            artifactNode.appendChild(commentNode);
        }
        if (provideReason || isFoundReasonForCurrentlyProcessedArtifact) {
            Element reasonNode = doc.createElementNS("urn:ws.tracker.collabnet.com", "ns1:" + "reason");
            reasonNode.appendChild(doc.createTextNode(
                    provideReason ? "Synchronized by Connector" : reasonForCurrentlyProcessedArtifact));
            artifactNode.appendChild(reasonNode);
        }
    } // for every artifact

    Element sendMail = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "sendEmail");
    sendMail.appendChild(doc.createTextNode("true"));
    root.appendChild(sendMail);

    if (log.isDebugEnabled())
        this.printDocument(doc);

    Response r = theService.execute(toRequest(doc));
    Document result = toDocument(r);
    if (log.isDebugEnabled())
        this.printDocument(result);
    ClientArtifactListXMLHelper helper = new ClientArtifactListXMLHelper(result);
    return helper;
}

From source file:lcmc.data.VMSXML.java

/** Add CPU match node. */
private void addCPUMatchNode(final Document doc, final Node root, final Map<String, String> parametersMap) {
    final String cpuMatch = parametersMap.get(VM_PARAM_CPU_MATCH);
    final Element cpuMatchNode = (Element) root.appendChild(doc.createElement("cpu"));
    if (!"".equals(cpuMatch)) {
        cpuMatchNode.setAttribute("match", cpuMatch);
    }/*  w  ww  .  j  a  v  a2 s.c o  m*/
    final String model = parametersMap.get(VM_PARAM_CPUMATCH_MODEL);
    if (!"".equals(model)) {
        final Node modelNode = (Element) cpuMatchNode.appendChild(doc.createElement("model"));
        modelNode.appendChild(doc.createTextNode(model));
    }
    final String vendor = parametersMap.get(VM_PARAM_CPUMATCH_VENDOR);
    if (!"".equals(vendor)) {
        final Node vendorNode = (Element) cpuMatchNode.appendChild(doc.createElement("vendor"));
        vendorNode.appendChild(doc.createTextNode(vendor));
    }
    final String sockets = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_SOCKETS);
    final String cores = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_CORES);
    final String threads = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_THREADS);
    final boolean isSockets = !"".equals(sockets);
    final boolean isCores = !"".equals(cores);
    final boolean isThreads = !"".equals(threads);
    if (isSockets || isCores || isThreads) {
        final Element topologyNode = (Element) cpuMatchNode.appendChild(doc.createElement("topology"));
        if (isSockets) {
            topologyNode.setAttribute("sockets", sockets);
        }
        if (isCores) {
            topologyNode.setAttribute("cores", cores);
        }
        if (isThreads) {
            topologyNode.setAttribute("threads", threads);
        }
    }
    final String policy = parametersMap.get(VM_PARAM_CPUMATCH_FEATURE_POLICY);
    final String features = parametersMap.get(VM_PARAM_CPUMATCH_FEATURES);
    if (!"".equals(policy) && !"".equals(features)) {
        for (final String feature : features.split("\\s+")) {
            final Element featureNode = (Element) cpuMatchNode.appendChild(doc.createElement("feature"));
            featureNode.setAttribute("policy", policy);
            featureNode.setAttribute("name", feature);
        }
    }
    if (!cpuMatchNode.hasChildNodes()) {
        root.removeChild(cpuMatchNode);

    }
}

From source file:it.greenvulcano.gvesb.utils.ResultSetUtils.java

/**
 * Returns all values from the ResultSet as an XML.
 * For instance, if the ResultSet has 3 values, the returned XML will have following fields:
 *                                <RowSet>
 *                                  <data>
 *                                    <row>
 *                                      <col>value1</col>
 *                                      <col>value2</col>
 *                                      <col>value3</col>
 *                                    </row>
 *                                    <row>
 *                                      <col>value4</col>
 *                                      <col>value5</col>
 *                                      <col>value6</col>
 *                                    </row>
 *                                  ../*from   w ww . ja  v  a  2s  .c om*/
 *                                    <row>
 *                                      <col>valuex</col>
 *                                      <col>valuey</col>
 *                                      <col>valuez</col>
 *                                    </row>
 *                                  </data>
 *                                </RowSet>
 * @param rs
 * @return
 * @throws Exception
 */
public static Document getResultSetAsDOM(ResultSet rs) throws Exception {
    XMLUtils xml = XMLUtils.getParserInstance();
    try {
        Document doc = xml.newDocument("RowSet");
        Element docRoot = doc.getDocumentElement();

        if (rs != null) {
            try {
                ResultSetMetaData metadata = rs.getMetaData();
                Element data = null;
                Element row = null;
                Element col = null;
                Text text = null;
                String textVal = null;
                while (rs.next()) {
                    boolean restartResultset = false;
                    for (int j = 1; j <= metadata.getColumnCount() && !restartResultset; j++) {
                        col = xml.createElement(doc, "col");
                        restartResultset = false;
                        switch (metadata.getColumnType(j)) {
                        case Types.CLOB: {
                            Clob clob = rs.getClob(j);
                            if (clob != null) {
                                Reader is = clob.getCharacterStream();
                                StringWriter strW = new StringWriter();

                                IOUtils.copy(is, strW);
                                is.close();
                                textVal = strW.toString();
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case Types.BLOB: {
                            Blob blob = rs.getBlob(j);
                            if (blob != null) {
                                InputStream is = blob.getBinaryStream();
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                IOUtils.copy(is, baos);
                                is.close();
                                try {
                                    byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                                    textVal = new String(Base64.getEncoder().encode(buffer));
                                } catch (SQLFeatureNotSupportedException exc) {
                                    textVal = new String(Base64.getEncoder().encode(baos.toByteArray()));
                                }
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case -10: { // OracleTypes.CURSOR
                            Object obj = rs.getObject(j);
                            if (obj instanceof ResultSet) {
                                rs = (ResultSet) obj;
                                metadata = rs.getMetaData();
                            }
                            restartResultset = true;
                        }
                            break;
                        default: {
                            textVal = rs.getString(j);
                            if (textVal == null) {
                                textVal = "";
                            }
                        }
                        }
                        if (restartResultset) {
                            continue;
                        }
                        if (row == null || j == 1) {
                            row = xml.createElement(doc, "row");
                        }
                        if (textVal != null) {
                            text = doc.createTextNode(textVal);
                            col.appendChild(text);
                        }
                        row.appendChild(col);
                    }
                    if (row != null) {
                        if (data == null) {
                            data = xml.createElement(doc, "data");
                        }
                        data.appendChild(row);
                    }
                }
                if (data != null) {
                    docRoot.appendChild(data);
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (Exception exc) {
                        // do nothing
                    }
                    rs = null;
                }
            }
        }

        return doc;
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveNews() {
    try {/*from  ww w .  j a v  a2 s . c  om*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(errorHandler);
        Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        for (Iterator iter = allNews().iterator(); iter.hasNext();) {
            NewsItem news = (NewsItem) iter.next();

            Element element = document.createElement("news"); //$NON-NLS-1$
            element.setAttribute("readed", String.valueOf(news.isReaded())); //$NON-NLS-1$
            root.appendChild(element);

            Element node = document.createElement("date"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(news.getDate())));
            element.appendChild(node);
            node = document.createElement("description"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(news.getTitle()));
            element.appendChild(node);
            node = document.createElement("source"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(news.getSource()));
            element.appendChild(node);
            node = document.createElement("url"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(news.getUrl()));
            element.appendChild(node);

            Object[] o = news.getSecurities().toArray();
            for (int i = 0; i < o.length; i++) {
                node = document.createElement("security"); //$NON-NLS-1$
                node.appendChild(document.createTextNode(String.valueOf(((Security) o[i]).getId())));
                element.appendChild(node);
            }
        }

        saveDocument(document, "", "news.xml"); //$NON-NLS-1$ //$NON-NLS-2$

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
}

From source file:com.buaa.cfs.conf.Configuration.java

/**
 * Return the XML DOM corresponding to this Configuration.
 *///from  w  ww .j ava2  s  .  c o  m
private synchronized Document asXmlDocument() throws IOException {
    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException pe) {
        throw new IOException(pe);
    }
    Element conf = doc.createElement("configuration");
    doc.appendChild(conf);
    conf.appendChild(doc.createTextNode("\n"));
    handleDeprecation(); //ensure properties is set and deprecation is handled
    for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        Object object = properties.get(name);
        String value = null;
        if (object instanceof String) {
            value = (String) object;
        } else {
            continue;
        }
        Element propNode = doc.createElement("property");
        conf.appendChild(propNode);

        Element nameNode = doc.createElement("name");
        nameNode.appendChild(doc.createTextNode(name));
        propNode.appendChild(nameNode);

        Element valueNode = doc.createElement("value");
        valueNode.appendChild(doc.createTextNode(value));
        propNode.appendChild(valueNode);

        if (updatingResource != null) {
            String[] sources = updatingResource.get(name);
            if (sources != null) {
                for (String s : sources) {
                    Element sourceNode = doc.createElement("source");
                    sourceNode.appendChild(doc.createTextNode(s));
                    propNode.appendChild(sourceNode);
                }
            }
        }

        conf.appendChild(doc.createTextNode("\n"));
    }
    return doc;
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveEvents() {
    try {/*w  ww  .  java  2 s  .  c  o  m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(errorHandler);
        Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        for (Iterator iter = allEvents().iterator(); iter.hasNext();) {
            Event event = (Event) iter.next();

            Element element = document.createElement("event"); //$NON-NLS-1$
            if (event.getSecurity() != null)
                element.setAttribute("security", String.valueOf(event.getSecurity().getId())); //$NON-NLS-1$
            root.appendChild(element);

            Element node = document.createElement("date"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(event.getDate())));
            element.appendChild(node);
            node = document.createElement("message"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(event.getMessage()));
            element.appendChild(node);
            node = document.createElement("longMessage"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(event.getLongMessage()));
            element.appendChild(node);
        }

        saveDocument(document, "", "events.xml"); //$NON-NLS-1$ //$NON-NLS-2$

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
}

From source file:com.commander4j.thread.AutoLabellerThread.java

public void run() {
    logger.debug("AutoLabeller Thread running");
    setSessionID(JUnique.getUniqueID());
    JDBUser user = new JDBUser(getHostID(), getSessionID());
    user.setUserId("interface");
    user.setPassword("interface");
    user.setLoginPassword("interface");
    Common.userList.addUser(getSessionID(), user);
    Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true);

    Boolean dbconnected = false;//from  w  w  w.  j ava2 s  .  c om

    if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) {

        dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID);

    } else {
        dbconnected = true;
    }

    if (dbconnected) {

        JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID());
        LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>();

        int noOfMessages = 0;

        while (true) {

            JWait.milliSec(500);

            if (allDone) {
                if (dbconnected) {
                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                }
                return;
            }

            autolabellerList.clear();
            autolabellerList = alp.getModifiedPrinterLines();
            noOfMessages = autolabellerList.size();

            if (noOfMessages > 0) {
                for (int x = 0; x < noOfMessages; x++) {
                    JWait.milliSec(100);

                    JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x);

                    messageProcessedOK = true;
                    messageError = "";

                    if (autolabview.getPrinterObj().isEnabled()) {
                        logger.debug("Line             =" + autolabview.getAutoLabellerObj().getLine());
                        logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription());
                        logger.debug("Printer ID       =" + autolabview.getPrinterObj().getPrinterID());
                        logger.debug("Printer Enabled  =" + autolabview.getPrinterObj().isEnabled());
                        logger.debug("Export Path      =" + autolabview.getPrinterObj().getExportRealPath());
                        logger.debug("Export Enabled   =" + autolabview.getPrinterObj().isExportEnabled());
                        logger.debug("Export Format    =" + autolabview.getPrinterObj().getExportFormat());
                        logger.debug("Direct Print     =" + autolabview.getPrinterObj().isDirectPrintEnabled());
                        logger.debug("Printer Type     =" + autolabview.getPrinterObj().getPrinterType());
                        logger.debug("Printer IP       =" + autolabview.getPrinterObj().getIPAddress());
                        logger.debug("Printer Port     =" + autolabview.getPrinterObj().getPort());
                        logger.debug("Process Order    =" + autolabview.getLabelDataObj().getProcessOrder());
                        logger.debug("Material         =" + autolabview.getLabelDataObj().getMaterial());
                        logger.debug("Module ID        =" + autolabview.getModuleObj().getModuleId());
                        logger.debug("Module Type      =" + autolabview.getModuleObj().getType());

                        if (autolabview.getPrinterObj().isExportEnabled()) {
                            String exportPath = JUtility.replaceNullStringwithBlank(
                                    JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath()));
                            if (exportPath.equals("") == false) {
                                if (exportPath.substring(exportPath.length() - 1)
                                        .equals(File.separator) == false) {
                                    exportPath = exportPath + File.separator;
                                }
                            } else {
                                exportPath = Common.interface_output_path + "Auto Labeller" + File.separator;
                            }

                            String exportFilename = exportPath
                                    + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine())
                                    + "_"
                                    + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID())
                                    + "." + autolabview.getPrinterObj().getExportFormat();

                            String exportFilenameTemp = exportFilename + ".out";

                            logger.debug("Export Filename  =" + exportFilename);

                            /* ================CSV================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;
                                    String labelType = autolabview.getLabelDataObj().getLabelType();
                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(
                                                    Common.hostList.getHost(getHostID()).getSqlstatements()
                                                            .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"
                                                                    + "_" + labelType));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();

                                    logger.debug("Writing CSV");

                                    CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp),
                                            CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER,
                                            CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);

                                    writer.writeAll(rs, true);

                                    rs.close();

                                    stmt.close();

                                    writer.close();

                                    File fromFile = new File(exportFilenameTemp);
                                    File toFile = new File(exportFilename);

                                    FileUtils.deleteQuietly(toFile);
                                    FileUtils.moveFile(fromFile, toFile);

                                    fromFile = null;
                                    toFile = null;

                                } catch (Exception e) {
                                    messageProcessedOK = false;
                                    messageError = e.getMessage();
                                }
                            }

                            /* ================XML================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("XML")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;

                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(Common.hostList.getHost(getHostID())
                                                    .getSqlstatements()
                                                    .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();
                                    ResultSetMetaData rsmd = rs.getMetaData();
                                    int colCount = rsmd.getColumnCount();

                                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                    Document document = builder.newDocument();

                                    Element message = (Element) document.createElement("message");

                                    Element hostUniqueID = addElement(document, "hostRef",
                                            Common.hostList.getHost(getHostID()).getUniqueID());
                                    message.appendChild(hostUniqueID);

                                    Element messageRef = addElement(document, "messageRef",
                                            autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageRef);

                                    Element messageType = addElement(document, "interfaceType",
                                            "Auto Labeller Data");
                                    message.appendChild(messageType);

                                    Element messageInformation = addElement(document, "messageInformation",
                                            "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageInformation);

                                    Element messageDirection = addElement(document, "interfaceDirection",
                                            "Output");
                                    message.appendChild(messageDirection);

                                    Element messageDate = addElement(document, "messageDate",
                                            JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()));
                                    message.appendChild(messageDate);

                                    if (rs.first()) {

                                        Element labelData = (Element) document.createElement("LabelData");

                                        Element row = document.createElement("Row");
                                        labelData.appendChild(row);
                                        for (int i = 1; i <= colCount; i++) {
                                            String columnName = rsmd.getColumnName(i);
                                            Object value = rs.getObject(i);
                                            Element node = document.createElement(columnName);
                                            node.appendChild(document.createTextNode(value.toString()));
                                            row.appendChild(node);
                                        }

                                        message.appendChild(labelData);

                                        document.appendChild(message);

                                        JXMLDocument xmld = new JXMLDocument();
                                        xmld.setDocument(document);

                                        // ===============================

                                        DOMImplementationLS DOMiLS = null;
                                        FileOutputStream FOS = null;

                                        // testing the support for DOM
                                        // Load and Save
                                        if ((document.getFeature("Core", "3.0") != null)
                                                && (document.getFeature("LS", "3.0") != null)) {
                                            DOMiLS = (DOMImplementationLS) (document.getImplementation())
                                                    .getFeature("LS", "3.0");

                                            // get a LSOutput object
                                            LSOutput LSO = DOMiLS.createLSOutput();

                                            FOS = new FileOutputStream(exportFilename);
                                            LSO.setByteStream((OutputStream) FOS);

                                            // get a LSSerializer object
                                            LSSerializer LSS = DOMiLS.createLSSerializer();

                                            // do the serialization
                                            LSS.write(document, LSO);

                                            FOS.close();
                                        }

                                        // ===============================

                                    }
                                    rs.close();
                                    stmt.close();

                                } catch (Exception e) {
                                    messageError = e.getMessage();
                                }

                            }

                            if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) {

                            }
                        }

                        if (autolabview.getPrinterObj().isDirectPrintEnabled()) {

                        }

                    }

                    if (messageProcessedOK == true) {
                        autolabview.getAutoLabellerObj().setModified(false);
                        autolabview.getAutoLabellerObj().update();
                    } else {
                        logger.debug(messageError);
                    }

                    autolabview = null;
                }
            }
        }
    }
}

From source file:com.redsqirl.workflow.server.Workflow.java

protected Document saveInXML() throws ParserConfigurationException, IOException {
    String error = null;//from  w  w w  .jav a 2s.c o m
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("workflow");
    doc.appendChild(rootElement);

    {
        Element jobId = doc.createElement("job-id");
        String jobIdContent = oozieJobId;
        if (jobIdContent == null) {
            jobIdContent = "";
        }
        logger.debug("Job Id: " + jobIdContent);
        jobId.appendChild(doc.createTextNode(jobIdContent));

        rootElement.appendChild(jobId);
    }
    {
        Element oozieRunningAction = doc.createElement("oozie-running-action");
        String oozieActionNbContent = String.valueOf(nbOozieRunningActions);
        if (oozieActionNbContent == null) {
            oozieActionNbContent = "";
        }
        logger.debug("Number of Oozie running actions: " + oozieActionNbContent);
        oozieRunningAction.appendChild(doc.createTextNode(oozieActionNbContent));

        rootElement.appendChild(oozieRunningAction);
    }

    Element wfComment = doc.createElement("wfcomment");
    wfComment.appendChild(doc.createTextNode(comment));
    rootElement.appendChild(wfComment);

    Iterator<DataFlowCoordinator> itCoord = coordinators.iterator();
    while (itCoord.hasNext() && error == null) {
        DataFlowCoordinator coordCur = itCoord.next();
        Element coordinatorEl = doc.createElement("coordinator");
        error = coordCur.saveInXml(doc, coordinatorEl);
        rootElement.appendChild(coordinatorEl);
    }

    if (error != null) {
        throw new IOException(error);
    }
    return doc;
}