Example usage for org.w3c.dom Attr getValue

List of usage examples for org.w3c.dom Attr getValue

Introduction

In this page you can find the example usage for org.w3c.dom Attr getValue.

Prototype

public String getValue();

Source Link

Document

On retrieval, the value of the attribute is returned as a string.

Usage

From source file:gov.nih.nci.cbiit.cmts.ws.servlet.AddNewScenario.java

/**
* Update the reference in .map to the .scs and .h3s files.
*
* @param  mapplingBakFileName  mapping file name
*///from w w  w.ja  va 2 s .  com
public void updateMapping(String mapplingBakFileName, String fileHome) throws Exception {

    Document xmlDOM = readFile(mapplingBakFileName);
    NodeList components = xmlDOM.getElementsByTagName("component");
    for (int i = 0; i < components.getLength(); i++) {
        Element component = (Element) components.item(i);
        //update location of SCS, H3S
        Attr locationAttr = component.getAttributeNode("location");
        Attr typeAttr = component.getAttributeNode("type");

        if (locationAttr != null) {
            String cmpType = "";
            if (typeAttr != null)
                cmpType = typeAttr.getValue();
            if (cmpType != null && cmpType.equalsIgnoreCase("v2"))
                continue;
            String originalLoc = locationAttr.getValue();
            String localName = extractOriginalFileName(originalLoc);
            //                locationAttr.setValue(fileHome+File.separator+cmpType+File.separator+localName);

            //includedXSDList.add(cmpType+File.separator+localName.toLowerCase());
            if (cmpType.equalsIgnoreCase(SOURCE_DIRECTORY_TAG)) {
                sourceOriginalXSDPath = originalLoc;
                locationAttr.setValue(SOURCE_DIRECTORY_TAG + File.separator + localName.toLowerCase());
                includedXSDList.add(SOURCE_DIRECTORY_TAG + File.separator + localName.toLowerCase());
            }
            if (cmpType.equalsIgnoreCase(TARGET_DIRECTORY_TAG)) {
                targetOriginalXSDPath = originalLoc;
                locationAttr.setValue(TARGET_DIRECTORY_TAG + File.separator + localName.toLowerCase());
                includedXSDList.add(TARGET_DIRECTORY_TAG + File.separator + localName.toLowerCase());
            }
            //System.out.println("CCCCC updateMapping Add file list : " + cmpType+File.separator+localName.toLowerCase());
            //locationAttr.setValue(cmpType+File.separator+localName);
        }
        //             //update VOM reference
        //             Attr groupAttr = component.getAttributeNode("group");
        //             if (groupAttr!=null
        //                   &&groupAttr.getValue()!=null
        //                   &&groupAttr.getValue().equalsIgnoreCase("vocabulary"))
        //             {
        //                NodeList chldComps = component.getElementsByTagName("data");
        //                for(int j=0;j<chldComps.getLength();j++)
        //                {
        //                   Element chldElement = (Element)chldComps.item(j);
        //                   Attr valueAttr=chldElement.getAttributeNode("value");
        //                   if (valueAttr!=null)
        //                   {
        //                      String localFileName=extractOriginalFileName(valueAttr.getValue());
        //                      valueAttr.setValue(localFileName);
        //                   }
        //                }
        //             }
    }
    System.out.println("AddNewScenario.updateMapping()..mapbakfile:" + mapplingBakFileName);

    outputXML(xmlDOM, mapplingBakFileName.substring(0, mapplingBakFileName.lastIndexOf(".bak")));
}

From source file:net.bpelunit.framework.SpecificationLoader.java

private int computeNumberOfRounds(XMLTestSuiteDocument xmlTestSuiteDocument, boolean isVary)
        throws SpecificationException {
    int rounds;/*from  w w  w .j a  v  a  2  s  .c  o  m*/
    rounds = 0;

    if (isVary) {
        /*
         * This is a varying test case. Each activity may have an arbitrary
         * number of delay times specified. These lists SHOULD be of equal
         * length, although no varying also also okay.
         * 
         * We use XPath to find all delay sequences and find the highest
         * size. This will be the size expected from all activities.
         */
        XPath xpath = XPathFactory.newInstance().newXPath();
        NamespaceContextImpl nsContext = new NamespaceContextImpl();
        nsContext.setNamespace("ts", BPELUnitConstants.BPELUNIT_TESTSUITE_NAMESPACE);
        xpath.setNamespaceContext(nsContext);
        try {
            NodeList set = (NodeList) xpath.evaluate("//@delaySequence", xmlTestSuiteDocument.getDomNode(),
                    XPathConstants.NODESET);
            int currentMax = 0;
            for (int i = 0; i < set.getLength(); i++) {
                if (set.item(i) instanceof Attr) {
                    Attr attr = (Attr) set.item(i);
                    List<Double> ints = getRoundInformation(attr.getValue());
                    if (ints != null) {
                        currentMax = ints.size();
                    }
                }
            }
            rounds = currentMax;
        } catch (XPathExpressionException e) {
            // This should not happen.
            throw new SpecificationException(
                    "There was a problem finding delay sequences. This most likely indicates a bug in the framework.",
                    e);
        }
    }
    return rounds;
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

private void resolveTypeImports(Element portTypeElement, RegistryObjectType wsdlEO) throws CatalogingException {
    try {/* w w  w .  ja  v a  2s . c o m*/
        String id = getPortTypeId(portTypeElement);
        if (idToRIMMap.get(id) == null) {
            processPortType(portTypeElement);
        }
        @SuppressWarnings("unused")
        ExtrinsicObjectType rimPortType = (ExtrinsicObjectType) idToRIMMap.get(id);
        List<Element> typeElements = resolveTypes(wsdlDocument);
        Iterator<?> schemaItr = resolveSchemaExtensions(typeElements);
        while (schemaItr.hasNext()) {
            Element schemaElement = (Element) schemaItr.next();
            Iterator<?> schemaAttributeItr = wsdlDocument.getAttributes(schemaElement).iterator();
            String location = null;
            @SuppressWarnings("unused")
            String localName = schemaElement.getLocalName();
            String namespace = schemaElement.getNamespaceURI();
            while (schemaAttributeItr.hasNext()) {
                Attr schemaAttribute = (Attr) schemaAttributeItr.next();
                String localAttrName = schemaAttribute.getLocalName();
                if (localAttrName.equalsIgnoreCase("namespace")) {
                    namespace = schemaAttribute.getValue();
                } else if (localAttrName.equalsIgnoreCase("schemaLocation")) {
                    location = schemaAttribute.getValue();
                }
            }
            RegistryObjectType importedObject = catalogImportStatement(wsdlEO, namespace, location);
            if (importedObject != null) {
                AssociationType1 ebAssociationType = bu.createAssociationType(wsdlEO.getId(),
                        importedObject.getId(), CanonicalConstants.CANONICAL_ASSOCIATION_TYPE_ID_Imports);
                //May need a more deterministic algorithm for setting this id??
                ebAssociationType.setId(wsdlEO.getId() + ":Imports:" + importedObject.getId());
                registryObjects.add(ebAssociationType);
            }
        }
    } catch (CatalogingException e) {
        throw e;
    } catch (Exception e) {
        throw new CatalogingException(e);
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * ?/*from w  w w  . j av a 2s.  c o m*/
 * 
 * @param e
 *            
 * @param subElementAsAttr
 *            trueElement?<br>
 *            
 * 
 *            <pre>
 * &lt;Foo size="103" name="Karen"&gt;
 *   &lt;dob&gt;2012-4-12&lt;/dobh&gt;
 *   &lt;dod&gt;2052-4-12&lt;/dodh&gt;
 * &lt;/Foo&gt;
 * </pre>
 * 
 *            subElementAsAttr=falsedob,dod?true?
 * @return
 */
public static Map<String, String> getAttributesMap(Element e, boolean subElementAsAttr) {
    Map<String, String> attribs = new HashMap<String, String>();
    if (e == null)
        return attribs;
    NamedNodeMap nmp = e.getAttributes();
    for (int i = 0; i < nmp.getLength(); i++) {
        Attr child = (Attr) nmp.item(i);
        attribs.put(StringEscapeUtils.unescapeHtml(child.getName()),
                StringEscapeUtils.unescapeHtml(child.getValue()));
    }
    if (subElementAsAttr) {
        NodeList nds = e.getChildNodes();
        for (int i = 0; i < nds.getLength(); i++) {
            Node node = nds.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element sub = (Element) node;
            String key = sub.getNodeName();
            String value = nodeText(sub);
            if (attribs.containsKey(key)) {
                attribs.put(key, attribs.get(key) + "," + value);
            } else {
                attribs.put(key, value);
            }
        }
    }
    return attribs;
}

From source file:com.legstar.jaxb.gen.CobolJAXBCustomizer.java

/**
 * JAXB needs to know the LegStar extension prefix used. Here we lookup the
 * extension attribute and version if they are found, we add to them
 * otherwise we create new attributes./*from   ww w .  j  av a  2s  .  c  om*/
 * <p/>
 * 
 * @param xsd the XML Schema
 * @param jaxbPrefix the JAXB namespace prefix
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void injectJaxbExtensionAttributes(final XmlSchema xsd, final String jaxbPrefix) {

    // Lookup the LegStar namespace prefix
    String coxbPrefix = COXB_DEFAULT_NAMESPACE_PREFIX;
    NamespacePrefixList nsList = xsd.getNamespaceContext();
    for (String prefix : nsList.getDeclaredPrefixes()) {
        if (nsList.getNamespaceURI(prefix).equals(CobolMarkup.NS)) {
            coxbPrefix = prefix;
            break;
        }
    }

    // Retrieve extension attributes if any
    Map metaInfoMap = xsd.getMetaInfoMap();
    Map<QName, Attr> extensionMap = null;
    if (metaInfoMap != null) {
        extensionMap = (Map<QName, Attr>) metaInfoMap.get(Constants.MetaDataConstants.EXTERNAL_ATTRIBUTES);
    } else {
        metaInfoMap = new LinkedHashMap();
        xsd.setMetaInfoMap(metaInfoMap);
    }
    if (extensionMap == null) {
        extensionMap = new HashMap<QName, Attr>();
    }

    // Extension attributes are DOM attributes
    Document doc = _db.newDocument();

    // Make sure the JAXB version extension is added
    QName versionQName = new QName(JAXB_NAMESPACE, JAXB_VERSION_ATTR_NAME);
    Attr attrib = doc.createAttribute(jaxbPrefix + ':' + JAXB_VERSION_ATTR_NAME);
    attrib.setValue(JAXB_VERSION_ATTR_VALUE);
    extensionMap.put(versionQName, attrib);

    /*
     * JAXB extension prefixes might already be present in which case we
     * make sure the legstar extension is there too. Extension prefixes are
     * specified as a whitespace-separated list of namespace prefixes.
     */

    QName extpfxQName = new QName(JAXB_NAMESPACE, JAXB_EXTENSION_BINDING_PREFIXES_ATTR_NAME);
    attrib = extensionMap.get(extpfxQName);
    if (attrib == null) {
        attrib = doc.createAttribute(jaxbPrefix + ':' + JAXB_EXTENSION_BINDING_PREFIXES_ATTR_NAME);
    }
    String extpfx = attrib.getValue();
    if (extpfx == null || extpfx.length() == 0) {
        extpfx = coxbPrefix;
    } else {
        boolean hasCoxbPrefix = false;
        StringTokenizer tokenizer = new StringTokenizer(extpfx, " ");
        while (tokenizer.hasMoreTokens()) {
            if (tokenizer.nextToken().equals(coxbPrefix)) {
                hasCoxbPrefix = true;
                break;
            }
        }
        if (!hasCoxbPrefix) {
            extpfx = extpfx + " " + coxbPrefix;
        }
    }
    attrib.setValue(extpfx);
    extensionMap.put(extpfxQName, attrib);

    metaInfoMap.put(Constants.MetaDataConstants.EXTERNAL_ATTRIBUTES, extensionMap);
}

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

/**
* Gets the status of the import or export operation in the specified server
* with the corresponding request ID.  The request ID is provided in the
* responses of the import or export operation.
*
* @param serverName Required. The name of the server in which the import or
* export operation is taking place./*  www.  j  a v  a2  s . com*/
* @param fullyQualifiedServerName Required. The fully qualified domain name
* of the Azure SQL Database Server where the operation is taking place.
* Example: a9s7f7s9d3.database.windows.net
* @param username Required. The administrator username for the Azure SQL
* Database Server.
* @param password Required. The administrator password for the Azure SQL
* Database Server.
* @param requestId Required. The request ID of the operation being queried.
* The request ID is obtained from the responses of the import and export
* operations.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Represents a list of import or export status values returned from
* GetStatus.
*/
@Override
public DacGetStatusResponse getStatus(String serverName, String fullyQualifiedServerName, String username,
        String password, String requestId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (fullyQualifiedServerName == null) {
        throw new NullPointerException("fullyQualifiedServerName");
    }
    if (username == null) {
        throw new NullPointerException("username");
    }
    if (password == null) {
        throw new NullPointerException("password");
    }
    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("serverName", serverName);
        tracingParameters.put("fullyQualifiedServerName", fullyQualifiedServerName);
        tracingParameters.put("username", username);
        tracingParameters.put("password", password);
        tracingParameters.put("requestId", requestId);
        CloudTracing.enter(invocationId, this, "getStatusAsync", 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 + "/DacOperations/Status";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("servername=" + URLEncoder.encode(fullyQualifiedServerName, "UTF-8"));
    queryParameters.add("username=" + URLEncoder.encode(username, "UTF-8"));
    queryParameters.add("password=" + URLEncoder.encode(password, "UTF-8"));
    queryParameters.add("reqId=" + URLEncoder.encode(requestId, "UTF-8"));
    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
        DacGetStatusResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DacGetStatusResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element arrayOfStatusInfoElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ArrayOfStatusInfo");
            if (arrayOfStatusInfoElement != null) {
                if (arrayOfStatusInfoElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                    "StatusInfo")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element statusInfoElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                        "StatusInfo")
                                .get(i1));
                        StatusInfo statusInfoInstance = new StatusInfo();
                        result.getStatusInfoList().add(statusInfoInstance);

                        Element blobUriElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "BlobUri");
                        if (blobUriElement != null) {
                            URI blobUriInstance;
                            blobUriInstance = new URI(blobUriElement.getTextContent());
                            statusInfoInstance.setBlobUri(blobUriInstance);
                        }

                        Element databaseNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "DatabaseName");
                        if (databaseNameElement != null) {
                            String databaseNameInstance;
                            databaseNameInstance = databaseNameElement.getTextContent();
                            statusInfoInstance.setDatabaseName(databaseNameInstance);
                        }

                        Element errorMessageElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ErrorMessage");
                        if (errorMessageElement != null) {
                            boolean isNil = false;
                            Attr nilAttribute = errorMessageElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute != null) {
                                isNil = "true".equals(nilAttribute.getValue());
                            }
                            if (isNil == false) {
                                String errorMessageInstance;
                                errorMessageInstance = errorMessageElement.getTextContent();
                                statusInfoInstance.setErrorMessage(errorMessageInstance);
                            }
                        }

                        Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "LastModifiedTime");
                        if (lastModifiedTimeElement != null) {
                            Calendar lastModifiedTimeInstance;
                            lastModifiedTimeInstance = DatatypeConverter
                                    .parseDateTime(lastModifiedTimeElement.getTextContent());
                            statusInfoInstance.setLastModifiedTime(lastModifiedTimeInstance);
                        }

                        Element queuedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "QueuedTime");
                        if (queuedTimeElement != null) {
                            Calendar queuedTimeInstance;
                            queuedTimeInstance = DatatypeConverter
                                    .parseDateTime(queuedTimeElement.getTextContent());
                            statusInfoInstance.setQueuedTime(queuedTimeInstance);
                        }

                        Element requestIdElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestId");
                        if (requestIdElement != null) {
                            String requestIdInstance;
                            requestIdInstance = requestIdElement.getTextContent();
                            statusInfoInstance.setRequestId(requestIdInstance);
                        }

                        Element requestTypeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestType");
                        if (requestTypeElement != null) {
                            String requestTypeInstance;
                            requestTypeInstance = requestTypeElement.getTextContent();
                            statusInfoInstance.setRequestType(requestTypeInstance);
                        }

                        Element serverNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ServerName");
                        if (serverNameElement != null) {
                            String serverNameInstance;
                            serverNameInstance = serverNameElement.getTextContent();
                            statusInfoInstance.setServerName(serverNameInstance);
                        }

                        Element statusElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "Status");
                        if (statusElement != null) {
                            String statusInstance;
                            statusInstance = statusElement.getTextContent();
                            statusInfoInstance.setStatus(statusInstance);
                        }
                    }
                }
            }

        }
        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.sql.DacOperationsImpl.java

/**
* Gets the status of the import or export operation in the specified server
* with the corresponding request ID.  The request ID is provided in the
* responses of the import or export operation.
*
* @param serverName Required. The name of the server in which the import or
* export operation is taking place./*from w w w.j  a v a  2 s  . co m*/
* @param parameters Required. The parameters needed to get the status of an
* import or export 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Represents a list of import or export status values returned from
* GetStatus.
*/
@Override
public DacGetStatusResponse getStatusPost(String serverName, DacGetStatusParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPassword() == null) {
        throw new NullPointerException("parameters.Password");
    }
    if (parameters.getRequestId() == null) {
        throw new NullPointerException("parameters.RequestId");
    }
    if (parameters.getServerName() == null) {
        throw new NullPointerException("parameters.ServerName");
    }
    if (parameters.getUserName() == null) {
        throw new NullPointerException("parameters.UserName");
    }

    // 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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "getStatusPostAsync", 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 + "/DacOperations/Status";
    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
    HttpPost httpRequest = new HttpPost(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 statusInputElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "StatusInput");
    requestDoc.appendChild(statusInputElement);

    Element passwordElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "Password");
    passwordElement.appendChild(requestDoc.createTextNode(parameters.getPassword()));
    statusInputElement.appendChild(passwordElement);

    Element requestIdElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "RequestId");
    requestIdElement.appendChild(requestDoc.createTextNode(parameters.getRequestId()));
    statusInputElement.appendChild(requestIdElement);

    Element serverNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "ServerName");
    serverNameElement.appendChild(requestDoc.createTextNode(parameters.getServerName()));
    statusInputElement.appendChild(serverNameElement);

    Element userNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "UserName");
    userNameElement.appendChild(requestDoc.createTextNode(parameters.getUserName()));
    statusInputElement.appendChild(userNameElement);

    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
        DacGetStatusResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DacGetStatusResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element arrayOfStatusInfoElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ArrayOfStatusInfo");
            if (arrayOfStatusInfoElement != null) {
                if (arrayOfStatusInfoElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                    "StatusInfo")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element statusInfoElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                        "StatusInfo")
                                .get(i1));
                        StatusInfo statusInfoInstance = new StatusInfo();
                        result.getStatusInfoList().add(statusInfoInstance);

                        Element blobUriElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "BlobUri");
                        if (blobUriElement != null) {
                            URI blobUriInstance;
                            blobUriInstance = new URI(blobUriElement.getTextContent());
                            statusInfoInstance.setBlobUri(blobUriInstance);
                        }

                        Element databaseNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "DatabaseName");
                        if (databaseNameElement != null) {
                            String databaseNameInstance;
                            databaseNameInstance = databaseNameElement.getTextContent();
                            statusInfoInstance.setDatabaseName(databaseNameInstance);
                        }

                        Element errorMessageElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ErrorMessage");
                        if (errorMessageElement != null) {
                            boolean isNil = false;
                            Attr nilAttribute = errorMessageElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute != null) {
                                isNil = "true".equals(nilAttribute.getValue());
                            }
                            if (isNil == false) {
                                String errorMessageInstance;
                                errorMessageInstance = errorMessageElement.getTextContent();
                                statusInfoInstance.setErrorMessage(errorMessageInstance);
                            }
                        }

                        Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "LastModifiedTime");
                        if (lastModifiedTimeElement != null) {
                            Calendar lastModifiedTimeInstance;
                            lastModifiedTimeInstance = DatatypeConverter
                                    .parseDateTime(lastModifiedTimeElement.getTextContent());
                            statusInfoInstance.setLastModifiedTime(lastModifiedTimeInstance);
                        }

                        Element queuedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "QueuedTime");
                        if (queuedTimeElement != null) {
                            Calendar queuedTimeInstance;
                            queuedTimeInstance = DatatypeConverter
                                    .parseDateTime(queuedTimeElement.getTextContent());
                            statusInfoInstance.setQueuedTime(queuedTimeInstance);
                        }

                        Element requestIdElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestId");
                        if (requestIdElement2 != null) {
                            String requestIdInstance;
                            requestIdInstance = requestIdElement2.getTextContent();
                            statusInfoInstance.setRequestId(requestIdInstance);
                        }

                        Element requestTypeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestType");
                        if (requestTypeElement != null) {
                            String requestTypeInstance;
                            requestTypeInstance = requestTypeElement.getTextContent();
                            statusInfoInstance.setRequestType(requestTypeInstance);
                        }

                        Element serverNameElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ServerName");
                        if (serverNameElement2 != null) {
                            String serverNameInstance;
                            serverNameInstance = serverNameElement2.getTextContent();
                            statusInfoInstance.setServerName(serverNameInstance);
                        }

                        Element statusElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "Status");
                        if (statusElement != null) {
                            String statusInstance;
                            statusInstance = statusElement.getTextContent();
                            statusInfoInstance.setStatus(statusInstance);
                        }
                    }
                }
            }

        }
        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:iristk.flow.FlowCompiler.java

private String createExpression(Element en) throws FlowCompilerException {
    String estring = "";
    estring += "<" + en.getLocalName();
    for (int j = 0; j < en.getAttributes().getLength(); j++) {
        Attr attr = (Attr) en.getAttributes().item(j);
        if (!(attr.getNamespaceURI() != null && attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/"))
                && !attr.getLocalName().equals("xmlns") && !attr.getLocalName().equals("xsi")) {
            estring += " " + attr.getLocalName() + "=\\\"" + attr.getValue() + "\\\"";
        }/*w w  w. j  av  a2s  .c  o  m*/
    }
    if (en.getChildNodes().getLength() == 0) {
        estring += "/>";
        return "\"" + estring + "\"";
    } else {
        String varName = varname("string");
        code.println("StringCreator " + varName + " = new StringCreator();");
        List<Object> children = new ArrayList<>();
        estring += ">";
        children.add(estring);
        for (int i = 0; i < en.getChildNodes().getLength(); i++) {
            children.add(en.getChildNodes().item(i));
        }
        children.add("</" + en.getLocalName() + ">");
        printActions(children, en, varName);
        return varName + ".toString()";
    }
}

From source file:com.microsoft.windowsazure.management.websites.WebHostingPlanOperationsImpl.java

/**
* You can retrieve historical usage metrics for a site by issuing an HTTP
* GET request.  (see//  ww  w . ja va 2 s .c o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param webHostingPlanName Required. The name of the web hosting plan.
* @param parameters Required. Parameters supplied to the Get Historical
* Usage Metrics Web hosting plan operation.
* @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 Get Historical Usage Metrics Web hosting plan operation
* response.
*/
@Override
public WebHostingPlanGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName,
        String webHostingPlanName, WebHostingPlanGetHistoricalUsageMetricsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webHostingPlanName == null) {
        throw new NullPointerException("webHostingPlanName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("webHostingPlanName", webHostingPlanName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "getHistoricalUsageMetricsAsync", 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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/serverFarms/";
    url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
    url = url + "/metrics";
    ArrayList<String> queryParameters = new ArrayList<String>();
    if (parameters.getMetricNames() != null && parameters.getMetricNames().size() > 0) {
        queryParameters.add("names="
                + URLEncoder.encode(CollectionStringBuilder.join(parameters.getMetricNames(), ","), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getStartTime() != null) {
        queryParameters.add("StartTime="
                + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getEndTime() != null) {
        queryParameters.add("EndTime="
                + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
    }
    if (parameters.getTimeGrain() != null) {
        queryParameters.add("timeGrain=" + URLEncoder.encode(parameters.getTimeGrain(), "UTF-8"));
    }
    queryParameters.add("details=" + URLEncoder
            .encode(Boolean.toString(parameters.isIncludeInstanceBreakdown()).toLowerCase(), "UTF-8"));
    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", "2014-04-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
        WebHostingPlanGetHistoricalUsageMetricsResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebHostingPlanGetHistoricalUsageMetricsResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element metricResponsesElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "MetricResponses");
            if (metricResponsesElement != null) {
                if (metricResponsesElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(metricResponsesElement,
                                    "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element usageMetricsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metricResponsesElement,
                                        "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                                .get(i1));
                        HistoricalUsageMetric metricResponseInstance = new HistoricalUsageMetric();
                        result.getUsageMetrics().add(metricResponseInstance);

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

                        Element dataElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Data");
                        if (dataElement != null) {
                            HistoricalUsageMetricData dataInstance = new HistoricalUsageMetricData();
                            metricResponseInstance.setData(dataInstance);

                            Element displayNameElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "DisplayName");
                            if (displayNameElement != null) {
                                String displayNameInstance;
                                displayNameInstance = displayNameElement.getTextContent();
                                dataInstance.setDisplayName(displayNameInstance);
                            }

                            Element endTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "EndTime");
                            if (endTimeElement != null) {
                                Calendar endTimeInstance;
                                endTimeInstance = DatatypeConverter
                                        .parseDateTime(endTimeElement.getTextContent());
                                dataInstance.setEndTime(endTimeInstance);
                            }

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

                            Element primaryAggregationTypeElement = XmlUtility.getElementByTagNameNS(
                                    dataElement, "http://schemas.microsoft.com/windowsazure",
                                    "PrimaryAggregationType");
                            if (primaryAggregationTypeElement != null) {
                                String primaryAggregationTypeInstance;
                                primaryAggregationTypeInstance = primaryAggregationTypeElement.getTextContent();
                                dataInstance.setPrimaryAggregationType(primaryAggregationTypeInstance);
                            }

                            Element startTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "StartTime");
                            if (startTimeElement != null) {
                                Calendar startTimeInstance;
                                startTimeInstance = DatatypeConverter
                                        .parseDateTime(startTimeElement.getTextContent());
                                dataInstance.setStartTime(startTimeInstance);
                            }

                            Element timeGrainElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "TimeGrain");
                            if (timeGrainElement != null) {
                                String timeGrainInstance;
                                timeGrainInstance = timeGrainElement.getTextContent();
                                dataInstance.setTimeGrain(timeGrainInstance);
                            }

                            Element unitElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "Unit");
                            if (unitElement != null) {
                                String unitInstance;
                                unitInstance = unitElement.getTextContent();
                                dataInstance.setUnit(unitInstance);
                            }

                            Element valuesSequenceElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "Values");
                            if (valuesSequenceElement != null) {
                                for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(valuesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                        .size(); i2 = i2 + 1) {
                                    org.w3c.dom.Element valuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(valuesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                            .get(i2));
                                    HistoricalUsageMetricSample metricSampleInstance = new HistoricalUsageMetricSample();
                                    dataInstance.getValues().add(metricSampleInstance);

                                    Element countElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Count");
                                    if (countElement != null) {
                                        int countInstance;
                                        countInstance = DatatypeConverter
                                                .parseInt(countElement.getTextContent());
                                        metricSampleInstance.setCount(countInstance);
                                    }

                                    Element maximumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Maximum");
                                    if (maximumElement != null) {
                                        boolean isNil = false;
                                        Attr nilAttribute = maximumElement.getAttributeNodeNS(
                                                "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                        if (nilAttribute != null) {
                                            isNil = "true".equals(nilAttribute.getValue());
                                        }
                                        if (isNil == false) {
                                            String maximumInstance;
                                            maximumInstance = maximumElement.getTextContent();
                                            metricSampleInstance.setMaximum(maximumInstance);
                                        }
                                    }

                                    Element minimumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Minimum");
                                    if (minimumElement != null) {
                                        boolean isNil2 = false;
                                        Attr nilAttribute2 = minimumElement.getAttributeNodeNS(
                                                "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                        if (nilAttribute2 != null) {
                                            isNil2 = "true".equals(nilAttribute2.getValue());
                                        }
                                        if (isNil2 == false) {
                                            String minimumInstance;
                                            minimumInstance = minimumElement.getTextContent();
                                            metricSampleInstance.setMinimum(minimumInstance);
                                        }
                                    }

                                    Element timeCreatedElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "TimeCreated");
                                    if (timeCreatedElement != null) {
                                        Calendar timeCreatedInstance;
                                        timeCreatedInstance = DatatypeConverter
                                                .parseDateTime(timeCreatedElement.getTextContent());
                                        metricSampleInstance.setTimeCreated(timeCreatedInstance);
                                    }

                                    Element totalElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Total");
                                    if (totalElement != null) {
                                        String totalInstance;
                                        totalInstance = totalElement.getTextContent();
                                        metricSampleInstance.setTotal(totalInstance);
                                    }

                                    Element instanceNameElement = XmlUtility.getElementByTagNameNS(
                                            valuesElement, "http://schemas.microsoft.com/windowsazure",
                                            "InstanceName");
                                    if (instanceNameElement != null) {
                                        String instanceNameInstance;
                                        instanceNameInstance = instanceNameElement.getTextContent();
                                        metricSampleInstance.setInstanceName(instanceNameInstance);
                                    }
                                }
                            }
                        }

                        Element messageElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Message");
                        if (messageElement != null) {
                            String messageInstance;
                            messageInstance = messageElement.getTextContent();
                            metricResponseInstance.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.websites.WebSpaceOperationsImpl.java

/**
* Get the available geo regions for this web space.
*
* @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.//from   w  w w.  j  a  v a  2 s .c  o m
* @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 List Geo Regions operation response.
*/
@Override
public WebSpacesListGeoRegionsResponse listGeoRegions()
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        CloudTracing.enter(invocationId, this, "listGeoRegionsAsync", 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/WebSpaces";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("properties=georegions");
    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", "2014-04-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
        WebSpacesListGeoRegionsResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSpacesListGeoRegionsResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element geoRegionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "GeoRegions");
            if (geoRegionsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(geoRegionsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "GeoRegion")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element geoRegionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(geoRegionsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "GeoRegion")
                            .get(i1));
                    WebSpacesListGeoRegionsResponse.GeoRegion geoRegionInstance = new WebSpacesListGeoRegionsResponse.GeoRegion();
                    result.getGeoRegions().add(geoRegionInstance);

                    Element descriptionElement = XmlUtility.getElementByTagNameNS(geoRegionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Description");
                    if (descriptionElement != null) {
                        String descriptionInstance;
                        descriptionInstance = descriptionElement.getTextContent();
                        geoRegionInstance.setDescription(descriptionInstance);
                    }

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

                    Element sortOrderElement = XmlUtility.getElementByTagNameNS(geoRegionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SortOrder");
                    if (sortOrderElement != null && sortOrderElement.getTextContent() != null
                            && !sortOrderElement.getTextContent().isEmpty()) {
                        boolean isNil = false;
                        Attr nilAttribute = sortOrderElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute != null) {
                            isNil = "true".equals(nilAttribute.getValue());
                        }
                        if (isNil == false) {
                            int sortOrderInstance;
                            sortOrderInstance = DatatypeConverter.parseInt(sortOrderElement.getTextContent());
                            geoRegionInstance.setSortOrder(sortOrderInstance);
                        }
                    }
                }
            }

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