Example usage for org.w3c.dom Element getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

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

Usage

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

/**
 * /*w ww.j a  v a2 s  .  c  o  m*/
 * @param account
 * @param accountId
 * @param cADbject
 * @return
 * @throws Exception
 */
public static final Opportunity createCRMObjectTypeOpportunity(final ScribeObject cADbject,
        final String crmFieldIntraSeparator) throws Exception {

    /* Create xml beans object */
    final Opportunity opportunity = Opportunity.Factory.newInstance();

    /* Create new cursor */
    XmlCursor cursor = null;
    try {
        cursor = opportunity.newCursor();
        cursor.toFirstContentToken();
        final Node node = cursor.getDomNode();

        /* Get main namespace URl */
        if (node != null) {

            final String nsURL = node.getNamespaceURI();

            /* Iterate on the Element list and create SOAP object */
            for (final Element element : cADbject.getXmlContent()) {

                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside createCRMObject_Opportunity: adding node : "
                            + element.getNodeName() + " with value : " + element.getTextContent());
                }

                /* Get crm field */
                final String crmField = element.getNodeName();

                String crmFieldName = null;

                /* If field contains the type information */
                if (crmField != null && crmField.contains(crmFieldIntraSeparator)) {

                    /* Split the field and get name */
                    crmFieldName = crmField.split(crmFieldIntraSeparator)[0];
                } else {
                    crmFieldName = crmField;
                }

                /* Add all new nodes */
                cursor.beginElement(new QName(nsURL, crmFieldName));

                /* Set node attributes */
                if (element.getAttributes() != null) {

                    /* Get attribute map */
                    final NamedNodeMap namedNodeMap = element.getAttributes();

                    /* Interate over map */
                    for (int i = 0; i < namedNodeMap.getLength(); i++) {

                        /* Get respective item */
                        final Node namedNode = namedNodeMap.item(i);

                        if (logger.isDebugEnabled()) {
                            logger.debug("----Inside createCRMObject_Opportunity: adding attribute name : "
                                    + namedNode.getNodeName() + " with value: " + namedNode.getNodeValue());
                        }

                        /* Set node attribute */
                        cursor.insertAttributeWithValue(namedNode.getNodeName(), namedNode.getNodeValue());
                    }
                }

                /* Set node value */
                cursor.insertChars(element.getTextContent());

                /* Jump to next token */
                cursor.toNextToken();
            }
        }
    } finally {
        if (cursor != null) {
            cursor.dispose();
        }
    }
    return opportunity;
}

From source file:org.yamj.core.service.metadata.nfo.InfoReader.java

/**
 * Parse Genres from the XML NFO file//w  w  w.ja v a 2s.  c  om
 * Caters for multiple genres on the same line and multiple lines.
 *
 * @param nlElements
 * @param dto
*/
private void parseGenres(NodeList nlElements, InfoDTO dto) {
    Node nElements;
    for (int looper = 0; looper < nlElements.getLength(); looper++) {
        nElements = nlElements.item(looper);
        if (nElements.getNodeType() == Node.ELEMENT_NODE) {
            Element eGenre = (Element) nElements;
            NodeList nlNames = eGenre.getElementsByTagName("name");
            if ((nlNames != null) && (nlNames.getLength() > 0)) {
                parseGenres(nlNames, dto);
            } else if (eGenre.getTextContent() != null) {
                for (String genre : eGenre.getTextContent().split(SPLIT_GENRE)) {
                    dto.adGenre(genre);
                }
            }
        }
    }
}

From source file:de.csw.expertfinder.mediawiki.api.MediaWikiAPI.java

/**
 * Performs a request to the wiki's OpenSearch API
 * (http://<your.wiki.host>/w/api.php)
 * //from   w w w .  j  ava2  s.  c  o  m
 * @param params
 * @param elementName
 * @param attributeName
 * @return a list containing article names starting with the given prefix
 * @throws MediaWikiAPIException
 */
private Set<String> openSearch(String prefix) throws MediaWikiAPIException {

    TreeSet<String> result = new TreeSet<String>();

    Document document = queryMediaWiki("opensearch", new BasicNameValuePair[] {
            new BasicNameValuePair("search", prefix), new BasicNameValuePair("limit", "10") });

    NodeList plElements = document.getElementsByTagName("Text");
    int length = plElements.getLength();
    for (int i = 0; i < length; i++) {
        Element plElement = (Element) plElements.item(i);
        String articleName = plElement.getTextContent().trim();
        result.add(articleName);
    }

    return result;
}

From source file:marytts.tools.install.ComponentDescription.java

protected ComponentDescription(Element xmlDescription) throws NullPointerException {
    this.name = xmlDescription.getAttribute("name");
    this.locale = MaryUtils.string2locale(xmlDescription.getAttribute("locale"));
    this.version = xmlDescription.getAttribute("version");
    Element descriptionElement = (Element) xmlDescription.getElementsByTagName("description").item(0);
    this.description = descriptionElement.getTextContent().trim();
    Element licenseElement = (Element) xmlDescription.getElementsByTagName("license").item(0);
    try {/*from   www .  j av  a2 s  . com*/
        this.license = new URL(licenseElement.getAttribute("href").trim().replaceAll(" ", "%20"));
    } catch (MalformedURLException mue) {
        new Exception("Invalid license URL -- ignoring", mue).printStackTrace();
        this.license = null;
    }
    Element packageElement = (Element) xmlDescription.getElementsByTagName("package").item(0);
    packageFilename = packageElement.getAttribute("filename").trim();
    packageSize = Integer.parseInt(packageElement.getAttribute("size"));
    packageMD5 = packageElement.getAttribute("md5sum");
    NodeList locationElements = packageElement.getElementsByTagName("location");
    locations = new ArrayList<URL>(locationElements.getLength());
    for (int i = 0, max = locationElements.getLength(); i < max; i++) {
        Element aLocationElement = (Element) locationElements.item(i);
        try {
            String urlString = aLocationElement.getAttribute("href").trim().replaceAll(" ", "%20");
            boolean isFolder = true;
            if (aLocationElement.hasAttribute("folder")) {
                isFolder = Boolean.valueOf(aLocationElement.getAttribute("folder"));
            }
            if (isFolder && !urlString.endsWith(packageFilename)) {
                if (!urlString.endsWith("/")) {
                    urlString += "/";
                }
                urlString += packageFilename;
            }
            locations.add(new URL(urlString));
        } catch (MalformedURLException mue) {
            new Exception("Invalid location -- ignoring", mue).printStackTrace();
        }
    }
    archiveFile = new File(System.getProperty("mary.downloadDir"), packageFilename);
    String infoFilename = packageFilename.substring(0, packageFilename.lastIndexOf('.')) + "-component.xml";
    infoFile = new File(System.getProperty("mary.installedDir"), infoFilename);
    determineStatus();
    NodeList filesElements = xmlDescription.getElementsByTagName("files");
    if (filesElements.getLength() > 0) {
        Element filesElement = (Element) filesElements.item(0);
        installedFilesNames = filesElement.getTextContent();
    }
}

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

/**
* Returns a collection of databases that has been dropped but can still be
* restored from a specified server.//from www  . ja va 2s.  c o  m
*
* @param serverName Required. The name of the Azure SQL Database Server to
* query for dropped databases that can still be restored.
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return Contains the response to the List Restorable Dropped Databases
* request.
*/
@Override
public RestorableDroppedDatabaseListResponse list(String serverName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }

    // 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);
        CloudTracing.enter(invocationId, this, "listAsync", 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 + "/restorabledroppeddatabases";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("contentview=generic");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    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
    HttpGet httpRequest = new HttpGet(url);

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

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResources");
            if (serviceResourcesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                            .get(i1));
                    RestorableDroppedDatabase serviceResourceInstance = new RestorableDroppedDatabase();
                    result.getDatabases().add(serviceResourceInstance);

                    Element entityIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EntityId");
                    if (entityIdElement != null) {
                        String entityIdInstance;
                        entityIdInstance = entityIdElement.getTextContent();
                        serviceResourceInstance.setEntityId(entityIdInstance);
                    }

                    Element serverNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "ServerName");
                    if (serverNameElement != null) {
                        String serverNameInstance;
                        serverNameInstance = serverNameElement.getTextContent();
                        serviceResourceInstance.setServerName(serverNameInstance);
                    }

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

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

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

                    Element deletionDateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "DeletionDate");
                    if (deletionDateElement != null) {
                        Calendar deletionDateInstance;
                        deletionDateInstance = DatatypeConverter
                                .parseDateTime(deletionDateElement.getTextContent());
                        serviceResourceInstance.setDeletionDate(deletionDateInstance);
                    }

                    Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS(
                            serviceResourcesElement, "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 nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        String nameInstance;
                        nameInstance = nameElement.getTextContent();
                        serviceResourceInstance.setName(nameInstance);
                    }

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

                    Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "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.cloud.test.regression.ApiCommand.java

public void sendCommand(HttpClient client, Connection conn) {
    if (TestCaseEngine._printUrl == true) {
        s_logger.info("url is " + this.command);
    }//from   ww w .  j av  a2 s .c o m

    if (this.getCommandType() == CommandType.SCRIPT) {
        try {
            s_logger.info("Executing command " + this.command);
            Runtime rtime = Runtime.getRuntime();
            Process child = rtime.exec(this.command);
            Thread.sleep(10000);
            int retCode = child.waitFor();
            if (retCode != 0) {
                this.responseCode = retCode;
            } else {
                this.responseCode = 200;
            }

        } catch (Exception ex) {
            s_logger.error("Unable to execute a command " + this.command, ex);
        }
    } else if (this.getCommandType() == CommandType.MYSQL) {
        try {
            Statement stmt = conn.createStatement();
            this.result = stmt.executeQuery(this.command);
            this.responseCode = 200;
        } catch (Exception ex) {
            this.responseCode = 400;
            s_logger.error("Unable to execute mysql query " + this.command, ex);
        }
    } else {
        HttpMethod method = new GetMethod(this.command);
        try {
            this.responseCode = client.executeMethod(method);

            if (this.responseCode == 200) {
                InputStream is = method.getResponseBodyAsStream();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(is);
                doc.getDocumentElement().normalize();

                if (!(this.isAsync)) {
                    this.responseBody = doc.getDocumentElement();
                } else {
                    // get async job result
                    Element jobTag = (Element) doc.getDocumentElement().getElementsByTagName("jobid").item(0);
                    String jobId = jobTag.getTextContent();
                    Element responseBodyAsyncEl = queryAsyncJobResult(jobId);
                    if (responseBodyAsyncEl == null) {
                        s_logger.error("Can't get a async result");
                    } else {
                        this.responseBody = responseBodyAsyncEl;
                        // get status of the job
                        Element jobStatusTag = (Element) responseBodyAsyncEl.getElementsByTagName("jobstatus")
                                .item(0);
                        String jobStatus = jobStatusTag.getTextContent();
                        if (!jobStatus.equals("1")) { // Need to modify with different error codes for jobAsync
                            // results
                            // set fake response code by now
                            this.responseCode = 400;
                        }
                    }
                }
            }

            if (TestCaseEngine._printUrl == true) {
                s_logger.info("Response code is " + this.responseCode);
            }
        } catch (Exception ex) {
            s_logger.error("Command " + command + " failed with exception " + ex.getMessage());
        } finally {
            method.releaseConnection();
        }
    }
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public PolicyValue getPolicyId() {
    try {//  www.j a  v a2s .c  om
        Element policyId = XMLUtils.getElement(signatureElement,
                "./ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/"
                        + "xades:SignaturePolicyIdentifier");
        if (policyId != null) {
            /* There is a policy */
            Element el = XMLUtils.getElement(policyId,
                    "./xades:SignaturePolicyId/xades:SigPolicyId/xades:Identifier");
            if (el != null) {
                /* Explicit policy */
                return new PolicyValue(el.getTextContent());
            } else {
                /* Implicit policy */
                return new PolicyValue();
            }
        } else {
            return null;
        }
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.SIGNATURE_POLICY_ENCODING);
    }
}

From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java

/**
 * This method:<ul>/*  www.j a  v a  2s .c  o m*/
 *     <li>Copies POM from original project to archetype-resources</li>
 *     <li>Generates <code></code>archetype-descriptor.xml</code></li>
 *     <li>Generates Archetype's <code>pom.xml</code> if not present in target directory.</li>
 * </ul>
 *
 * @param projectPom POM file of original project
 * @param archetypeDir target directory of created Maven Archetype project
 * @param archetypePom created POM file for Maven Archetype project
 * @param metadataXmlOutFile generated archetype-metadata.xml file
 * @param replaceFn replace function
 * @throws IOException
 */
private void createArchetypeDescriptors(File projectPom, File archetypeDir, File archetypePom,
        File metadataXmlOutFile, Replacement replaceFn) throws IOException {
    LOG.debug("Parsing " + projectPom);
    String text = replaceFn.replace(FileUtils.readFileToString(projectPom));

    // lets update the XML
    Document doc = archetypeUtils.parseXml(new InputSource(new StringReader(text)));
    Element root = doc.getDocumentElement();

    // let's get some values from the original project
    String originalArtifactId, originalName, originalDescription;
    Element artifactIdEl = (Element) findChild(root, "artifactId");

    Element nameEl = (Element) findChild(root, "name");
    Element descriptionEl = (Element) findChild(root, "description");
    if (artifactIdEl != null && artifactIdEl.getTextContent() != null
            && artifactIdEl.getTextContent().trim().length() > 0) {
        originalArtifactId = artifactIdEl.getTextContent().trim();
    } else {
        originalArtifactId = archetypeDir.getName();
    }
    if (nameEl != null && nameEl.getTextContent() != null && nameEl.getTextContent().trim().length() > 0) {
        originalName = nameEl.getTextContent().trim();
    } else {
        originalName = originalArtifactId;
    }
    if (descriptionEl != null && descriptionEl.getTextContent() != null
            && descriptionEl.getTextContent().trim().length() > 0) {
        originalDescription = descriptionEl.getTextContent().trim();
    } else {
        originalDescription = originalName;
    }

    Set<String> propertyNameSet = new TreeSet<String>();

    if (root != null) {
        // remove the parent element and the following text Node
        NodeList parents = root.getElementsByTagName("parent");
        if (parents.getLength() > 0) {
            if (parents.item(0).getNextSibling().getNodeType() == Node.TEXT_NODE) {
                root.removeChild(parents.item(0).getNextSibling());
            }
            root.removeChild(parents.item(0));
        }

        // lets load all the properties defined in the <properties> element in the pom.
        Set<String> pomPropertyNames = new LinkedHashSet<String>();

        NodeList propertyElements = root.getElementsByTagName("properties");
        if (propertyElements.getLength() > 0) {
            Element propertyElement = (Element) propertyElements.item(0);
            NodeList children = propertyElement.getChildNodes();
            for (int cn = 0; cn < children.getLength(); cn++) {
                Node e = children.item(cn);
                if (e instanceof Element) {
                    pomPropertyNames.add(e.getNodeName());
                }
            }
        }
        LOG.debug("Found <properties> in the pom: {}", pomPropertyNames);

        // lets find all the property names
        NodeList children = root.getElementsByTagName("*");
        for (int cn = 0; cn < children.getLength(); cn++) {
            Node e = children.item(cn);
            if (e instanceof Element) {
                //val text = e.childrenText
                String cText = e.getTextContent();
                String prefix = "${";
                if (cText.startsWith(prefix)) {
                    int offset = prefix.length();
                    int idx = cText.indexOf("}", offset + 1);
                    if (idx > 0) {
                        String name = cText.substring(offset, idx);
                        if (!pomPropertyNames.contains(name) && isValidRequiredPropertyName(name)) {
                            propertyNameSet.add(name);
                        }
                    }
                }
            }
        }

        // now lets replace the contents of some elements (adding new elements if they are not present)
        List<String> beforeNames = Arrays.asList("artifactId", "version", "packaging", "name", "properties");
        replaceOrAddElementText(doc, root, "version", "${version}", beforeNames);
        replaceOrAddElementText(doc, root, "artifactId", "${artifactId}", beforeNames);
        replaceOrAddElementText(doc, root, "groupId", "${groupId}", beforeNames);
    }
    archetypePom.getParentFile().mkdirs();

    archetypeUtils.writeXmlDocument(doc, archetypePom);

    // lets update the archetype-metadata.xml file
    String archetypeXmlText = defaultArchetypeXmlText();

    Document archDoc = archetypeUtils.parseXml(new InputSource(new StringReader(archetypeXmlText)));
    Element archRoot = archDoc.getDocumentElement();

    // replace @name attribute on root element
    archRoot.setAttribute("name", archetypeDir.getName());

    LOG.debug(("Found property names: {}"), propertyNameSet);
    // lets add all the properties
    Element requiredProperties = replaceOrAddElement(archDoc, archRoot, "requiredProperties",
            Arrays.asList("fileSets"));

    // lets add the various properties in
    for (String propertyName : propertyNameSet) {
        requiredProperties.appendChild(archDoc.createTextNode("\n" + indent + indent));
        Element requiredProperty = archDoc.createElement("requiredProperty");
        requiredProperties.appendChild(requiredProperty);
        requiredProperty.setAttribute("key", propertyName);
        requiredProperty.appendChild(archDoc.createTextNode("\n" + indent + indent + indent));
        Element defaultValue = archDoc.createElement("defaultValue");
        requiredProperty.appendChild(defaultValue);
        defaultValue.appendChild(archDoc.createTextNode("${" + propertyName + "}"));
        requiredProperty.appendChild(archDoc.createTextNode("\n" + indent + indent));
    }
    requiredProperties.appendChild(archDoc.createTextNode("\n" + indent));

    metadataXmlOutFile.getParentFile().mkdirs();
    archetypeUtils.writeXmlDocument(archDoc, metadataXmlOutFile);

    File archetypeProjectPom = new File(archetypeDir, "pom.xml");
    // now generate Archetype's pom
    if (!archetypeProjectPom.exists()) {
        StringWriter sw = new StringWriter();
        IOUtils.copy(getClass().getResourceAsStream("default-archetype-pom.xml"), sw, "UTF-8");
        Document pomDocument = archetypeUtils.parseXml(new InputSource(new StringReader(sw.toString())));

        List<String> emptyList = Collections.emptyList();

        // artifactId = original artifactId with "-archetype"
        Element artifactId = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "artifactId",
                emptyList);
        artifactId.setTextContent(archetypeDir.getName());

        // name = "Fabric8 :: Qickstarts :: xxx" -> "Fabric8 :: Archetypes :: xxx"
        Element name = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "name", emptyList);
        if (originalName.contains(" :: ")) {
            String[] originalNameTab = originalName.split(" :: ");
            if (originalNameTab.length > 2) {
                StringBuilder sb = new StringBuilder();
                sb.append("Fabric8 :: Archetypes");
                for (int idx = 2; idx < originalNameTab.length; idx++) {
                    sb.append(" :: ").append(originalNameTab[idx]);
                }
                name.setTextContent(sb.toString());
            } else {
                name.setTextContent("Fabric8 :: Archetypes :: " + originalNameTab[1]);
            }
        } else {
            name.setTextContent("Fabric8 :: Archetypes :: " + originalName);
        }

        // description = "Creates a new " + originalDescription
        Element description = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "description",
                emptyList);
        description.setTextContent("Creates a new " + originalDescription);

        archetypeUtils.writeXmlDocument(pomDocument, archetypeProjectPom);
    }
}

From source file:com.microsoft.windowsazure.management.compute.ComputeManagementClientImpl.java

/**
* The Get Operation Status operation returns the status of the specified
* operation. After calling an asynchronous operation, you can call Get
* Operation Status to determine whether the operation has succeeded,
* failed, or is still in progress.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for
* more information)/* w ww  .jav a2  s. com*/
*
* @param requestId Required. The request ID for the request you wish to
* track. The request ID is returned in the x-ms-request-id response header
* for every request.
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse getOperationStatus(String requestId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (requestId == null) {
        throw new NullPointerException("requestId");
    }

    // 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("requestId", requestId);
        CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operations/";
    url = url + URLEncoder.encode(requestId, "UTF-8");
    String baseUrl = this.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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2015-04-01");

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

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

            Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Operation");
            if (operationElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setId(idInstance);
                }

                Element statusElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null && statusElement.getTextContent() != null
                        && !statusElement.getTextContent().isEmpty()) {
                    OperationStatus statusInstance;
                    statusInstance = OperationStatus.valueOf(statusElement.getTextContent());
                    result.setStatus(statusInstance);
                }

                Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "HttpStatusCode");
                if (httpStatusCodeElement != null && httpStatusCodeElement.getTextContent() != null
                        && !httpStatusCodeElement.getTextContent().isEmpty()) {
                    Integer httpStatusCodeInstance;
                    httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent());
                    result.setHttpStatusCode(httpStatusCodeInstance);
                }

                Element errorElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Error");
                if (errorElement != null) {
                    OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails();
                    result.setError(errorInstance);

                    Element codeElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Code");
                    if (codeElement != null) {
                        String codeInstance;
                        codeInstance = codeElement.getTextContent();
                        errorInstance.setCode(codeInstance);
                    }

                    Element messageElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Message");
                    if (messageElement != null) {
                        String messageInstance;
                        messageInstance = messageElement.getTextContent();
                        errorInstance.setMessage(messageInstance);
                    }
                }
            }

        }
        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.microsoft.windowsazure.management.servicebus.ServiceBusManagementClientImpl.java

/**
* The Get Operation Status operation returns the status of thespecified
* operation. After calling an asynchronous operation, you can call Get
* Operation Status to determine whether the operation has succeeded,
* failed, or is still in progress.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for
* more information)/*from  www.java  2s .  c o m*/
*
* @param requestId Required. The request ID for the request you wish to
* track. The request ID is returned in the x-ms-request-id response header
* for every request.
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request.  If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse getOperationStatus(String requestId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (requestId == null) {
        throw new NullPointerException("requestId");
    }

    // 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("requestId", requestId);
        CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operations/";
    url = url + URLEncoder.encode(requestId, "UTF-8");
    String baseUrl = this.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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2013-08-01");

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

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

            Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Operation");
            if (operationElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setId(idInstance);
                }

                Element statusElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null && statusElement.getTextContent() != null
                        && !statusElement.getTextContent().isEmpty()) {
                    OperationStatus statusInstance;
                    statusInstance = OperationStatus.valueOf(statusElement.getTextContent());
                    result.setStatus(statusInstance);
                }

                Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "HttpStatusCode");
                if (httpStatusCodeElement != null && httpStatusCodeElement.getTextContent() != null
                        && !httpStatusCodeElement.getTextContent().isEmpty()) {
                    Integer httpStatusCodeInstance;
                    httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent());
                    result.setHttpStatusCode(httpStatusCodeInstance);
                }

                Element errorElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Error");
                if (errorElement != null) {
                    OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails();
                    result.setError(errorInstance);

                    Element codeElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Code");
                    if (codeElement != null) {
                        String codeInstance;
                        codeInstance = codeElement.getTextContent();
                        errorInstance.setCode(codeInstance);
                    }

                    Element messageElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Message");
                    if (messageElement != null) {
                        String messageInstance;
                        messageInstance = messageElement.getTextContent();
                        errorInstance.setMessage(messageInstance);
                    }
                }
            }

        }
        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();
        }
    }
}