Example usage for org.w3c.dom Element getAttributeNodeNS

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

Introduction

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

Prototype

public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Retrieves an Attr node by local name and namespace URI.

Usage

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

/**
* You can list the web spaces under the current subscription by issuing a
* GET request.  (see//  w  ww  .j  a v  a 2s. c o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx for
* more information)
*
* @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 List Web Spaces operation response.
*/
@Override
public WebSpacesListResponse list()
        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, "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/WebSpaces";
    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
        WebSpacesListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSpacesListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element webSpacesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "WebSpaces");
            if (webSpacesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(webSpacesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "WebSpace")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element webSpacesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(webSpacesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "WebSpace")
                            .get(i1));
                    WebSpacesListResponse.WebSpace webSpaceInstance = new WebSpacesListResponse.WebSpace();
                    result.getWebSpaces().add(webSpaceInstance);

                    Element availabilityStateElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "AvailabilityState");
                    if (availabilityStateElement != null && availabilityStateElement.getTextContent() != null
                            && !availabilityStateElement.getTextContent().isEmpty()) {
                        WebSpaceAvailabilityState availabilityStateInstance;
                        availabilityStateInstance = WebSpaceAvailabilityState
                                .valueOf(availabilityStateElement.getTextContent());
                        webSpaceInstance.setAvailabilityState(availabilityStateInstance);
                    }

                    Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
                    if (currentNumberOfWorkersElement != null
                            && currentNumberOfWorkersElement.getTextContent() != null
                            && !currentNumberOfWorkersElement.getTextContent().isEmpty()) {
                        boolean isNil = false;
                        Attr nilAttribute = currentNumberOfWorkersElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute != null) {
                            isNil = "true".equals(nilAttribute.getValue());
                        }
                        if (isNil == false) {
                            int currentNumberOfWorkersInstance;
                            currentNumberOfWorkersInstance = DatatypeConverter
                                    .parseInt(currentNumberOfWorkersElement.getTextContent());
                            webSpaceInstance.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
                        }
                    }

                    Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
                    if (currentWorkerSizeElement != null && currentWorkerSizeElement.getTextContent() != null
                            && !currentWorkerSizeElement.getTextContent().isEmpty()) {
                        boolean isNil2 = false;
                        Attr nilAttribute2 = currentWorkerSizeElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute2 != null) {
                            isNil2 = "true".equals(nilAttribute2.getValue());
                        }
                        if (isNil2 == false) {
                            WorkerSizeOptions currentWorkerSizeInstance;
                            currentWorkerSizeInstance = WorkerSizeOptions
                                    .valueOf(currentWorkerSizeElement.getTextContent());
                            webSpaceInstance.setCurrentWorkerSize(currentWorkerSizeInstance);
                        }
                    }

                    Element geoLocationElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "GeoLocation");
                    if (geoLocationElement != null) {
                        String geoLocationInstance;
                        geoLocationInstance = geoLocationElement.getTextContent();
                        webSpaceInstance.setGeoLocation(geoLocationInstance);
                    }

                    Element geoRegionElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "GeoRegion");
                    if (geoRegionElement != null) {
                        String geoRegionInstance;
                        geoRegionInstance = geoRegionElement.getTextContent();
                        webSpaceInstance.setGeoRegion(geoRegionInstance);
                    }

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

                    Element planElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "Plan");
                    if (planElement != null) {
                        String planInstance;
                        planInstance = planElement.getTextContent();
                        webSpaceInstance.setPlan(planInstance);
                    }

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

                    Element subscriptionElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "Subscription");
                    if (subscriptionElement != null) {
                        String subscriptionInstance;
                        subscriptionInstance = subscriptionElement.getTextContent();
                        webSpaceInstance.setSubscription(subscriptionInstance);
                    }

                    Element workerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                    if (workerSizeElement != null && workerSizeElement.getTextContent() != null
                            && !workerSizeElement.getTextContent().isEmpty()) {
                        WorkerSizeOptions workerSizeInstance;
                        workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement.getTextContent());
                        webSpaceInstance.setWorkerSize(workerSizeInstance);
                    }
                }
            }

        }
        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

/**
* You can retrieve a list of all web sites in a web space by issuing an
* HTTP GET request.  (see//from   w w  w . j  ava 2s .c  om
* http://msdn.microsoft.com/en-us/library/windowsazure/dn236429.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Optional. Additional parameters.
* @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 The List Web Sites operation response.
*/
@Override
public WebSpacesListWebSitesResponse listWebSites(String webSpaceName, WebSiteListParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }

    // 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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "listWebSitesAsync", 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 + "/sites";
    ArrayList<String> queryParameters = new ArrayList<String>();
    if (parameters != null && parameters.getPropertiesToInclude() != null
            && parameters.getPropertiesToInclude().size() > 0) {
        queryParameters.add("propertiesToInclude=" + URLEncoder
                .encode(CollectionStringBuilder.join(parameters.getPropertiesToInclude(), ","), "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
        WebSpacesListWebSitesResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSpacesListWebSitesResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element sitesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Sites");
            if (sitesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(sitesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "Site")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element sitesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(sitesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "Site")
                            .get(i1));
                    WebSite siteInstance = new WebSite();
                    result.getWebSites().add(siteInstance);

                    Element adminEnabledElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "AdminEnabled");
                    if (adminEnabledElement != null && adminEnabledElement.getTextContent() != null
                            && !adminEnabledElement.getTextContent().isEmpty()) {
                        boolean adminEnabledInstance;
                        adminEnabledInstance = DatatypeConverter
                                .parseBoolean(adminEnabledElement.getTextContent().toLowerCase());
                        siteInstance.setAdminEnabled(adminEnabledInstance);
                    }

                    Element availabilityStateElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "AvailabilityState");
                    if (availabilityStateElement != null && availabilityStateElement.getTextContent() != null
                            && !availabilityStateElement.getTextContent().isEmpty()) {
                        WebSpaceAvailabilityState availabilityStateInstance;
                        availabilityStateInstance = WebSpaceAvailabilityState
                                .valueOf(availabilityStateElement.getTextContent());
                        siteInstance.setAvailabilityState(availabilityStateInstance);
                    }

                    Element sKUElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "SKU");
                    if (sKUElement != null && sKUElement.getTextContent() != null
                            && !sKUElement.getTextContent().isEmpty()) {
                        SkuOptions sKUInstance;
                        sKUInstance = SkuOptions.valueOf(sKUElement.getTextContent());
                        siteInstance.setSku(sKUInstance);
                    }

                    Element enabledElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "Enabled");
                    if (enabledElement != null && enabledElement.getTextContent() != null
                            && !enabledElement.getTextContent().isEmpty()) {
                        boolean enabledInstance;
                        enabledInstance = DatatypeConverter
                                .parseBoolean(enabledElement.getTextContent().toLowerCase());
                        siteInstance.setEnabled(enabledInstance);
                    }

                    Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "EnabledHostNames");
                    if (enabledHostNamesSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                            "http://schemas.microsoft.com/2003/10/Serialization/Arrays",
                                            "string")
                                    .get(i2));
                            siteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent());
                        }
                    }

                    Element hostNameSslStatesSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "HostNameSslStates");
                    if (hostNameSslStatesSequenceElement != null) {
                        for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNameSslStatesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                                .size(); i3 = i3 + 1) {
                            org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(hostNameSslStatesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                                    .get(i3));
                            WebSite.WebSiteHostNameSslState hostNameSslStateInstance = new WebSite.WebSiteHostNameSslState();
                            siteInstance.getHostNameSslStates().add(hostNameSslStateInstance);

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

                            Element sslStateElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                    "http://schemas.microsoft.com/windowsazure", "SslState");
                            if (sslStateElement != null && sslStateElement.getTextContent() != null
                                    && !sslStateElement.getTextContent().isEmpty()) {
                                WebSiteSslState sslStateInstance;
                                sslStateInstance = WebSiteSslState.valueOf(sslStateElement.getTextContent());
                                hostNameSslStateInstance.setSslState(sslStateInstance);
                            }

                            Element thumbprintElement = XmlUtility.getElementByTagNameNS(
                                    hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure",
                                    "Thumbprint");
                            if (thumbprintElement != null) {
                                boolean isNil = false;
                                Attr nilAttribute = thumbprintElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute != null) {
                                    isNil = "true".equals(nilAttribute.getValue());
                                }
                                if (isNil == false) {
                                    String thumbprintInstance;
                                    thumbprintInstance = thumbprintElement.getTextContent();
                                    hostNameSslStateInstance.setThumbprint(thumbprintInstance);
                                }
                            }

                            Element virtualIPElement = XmlUtility.getElementByTagNameNS(
                                    hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure",
                                    "VirtualIP");
                            if (virtualIPElement != null) {
                                boolean isNil2 = false;
                                Attr nilAttribute2 = virtualIPElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute2 != null) {
                                    isNil2 = "true".equals(nilAttribute2.getValue());
                                }
                                if (isNil2 == false) {
                                    InetAddress virtualIPInstance;
                                    virtualIPInstance = InetAddress
                                            .getByName(virtualIPElement.getTextContent());
                                    hostNameSslStateInstance.setVirtualIP(virtualIPInstance);
                                }
                            }
                        }
                    }

                    Element hostNamesSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "HostNames");
                    if (hostNamesSequenceElement != null) {
                        for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .size(); i4 = i4 + 1) {
                            org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(hostNamesSequenceElement,
                                            "http://schemas.microsoft.com/2003/10/Serialization/Arrays",
                                            "string")
                                    .get(i4));
                            siteInstance.getHostNames().add(hostNamesElement.getTextContent());
                        }
                    }

                    Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc");
                    if (lastModifiedTimeUtcElement != null
                            && lastModifiedTimeUtcElement.getTextContent() != null
                            && !lastModifiedTimeUtcElement.getTextContent().isEmpty()) {
                        Calendar lastModifiedTimeUtcInstance;
                        lastModifiedTimeUtcInstance = DatatypeConverter
                                .parseDateTime(lastModifiedTimeUtcElement.getTextContent());
                        siteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance);
                    }

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

                    Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "RepositorySiteName");
                    if (repositorySiteNameElement != null) {
                        String repositorySiteNameInstance;
                        repositorySiteNameInstance = repositorySiteNameElement.getTextContent();
                        siteInstance.setRepositorySiteName(repositorySiteNameInstance);
                    }

                    Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState");
                    if (runtimeAvailabilityStateElement != null
                            && runtimeAvailabilityStateElement.getTextContent() != null
                            && !runtimeAvailabilityStateElement.getTextContent().isEmpty()) {
                        WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance;
                        runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState
                                .valueOf(runtimeAvailabilityStateElement.getTextContent());
                        siteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance);
                    }

                    Element selfLinkElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "SelfLink");
                    if (selfLinkElement != null) {
                        URI selfLinkInstance;
                        selfLinkInstance = new URI(selfLinkElement.getTextContent());
                        siteInstance.setUri(selfLinkInstance);
                    }

                    Element serverFarmElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                    if (serverFarmElement != null) {
                        String serverFarmInstance;
                        serverFarmInstance = serverFarmElement.getTextContent();
                        siteInstance.setServerFarm(serverFarmInstance);
                    }

                    Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "SiteProperties");
                    if (sitePropertiesElement != null) {
                        WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties();
                        siteInstance.setSiteProperties(sitePropertiesInstance);

                        Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(
                                sitePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "AppSettings");
                        if (appSettingsSequenceElement != null) {
                            for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(appSettingsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .size(); i5 = i5 + 1) {
                                org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(appSettingsSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                        .get(i5));
                                String appSettingsKey = XmlUtility
                                        .getElementByTagNameNS(appSettingsElement,
                                                "http://schemas.microsoft.com/windowsazure", "Name")
                                        .getTextContent();
                                String appSettingsValue = XmlUtility
                                        .getElementByTagNameNS(appSettingsElement,
                                                "http://schemas.microsoft.com/windowsazure", "Value")
                                        .getTextContent();
                                sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue);
                            }
                        }

                        Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(
                                sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Metadata");
                        if (metadataSequenceElement != null) {
                            for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(metadataSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .size(); i6 = i6 + 1) {
                                org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(metadataSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                        .get(i6));
                                String metadataKey = XmlUtility
                                        .getElementByTagNameNS(metadataElement,
                                                "http://schemas.microsoft.com/windowsazure", "Name")
                                        .getTextContent();
                                String metadataValue = XmlUtility
                                        .getElementByTagNameNS(metadataElement,
                                                "http://schemas.microsoft.com/windowsazure", "Value")
                                        .getTextContent();
                                sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue);
                            }
                        }

                        Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(
                                sitePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "Properties");
                        if (propertiesSequenceElement != null) {
                            for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(propertiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .size(); i7 = i7 + 1) {
                                org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(propertiesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                        .get(i7));
                                String propertiesKey = XmlUtility
                                        .getElementByTagNameNS(propertiesElement,
                                                "http://schemas.microsoft.com/windowsazure", "Name")
                                        .getTextContent();
                                String propertiesValue = XmlUtility
                                        .getElementByTagNameNS(propertiesElement,
                                                "http://schemas.microsoft.com/windowsazure", "Value")
                                        .getTextContent();
                                sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue);
                            }
                        }
                    }

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

                    Element usageStateElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "UsageState");
                    if (usageStateElement != null && usageStateElement.getTextContent() != null
                            && !usageStateElement.getTextContent().isEmpty()) {
                        WebSiteUsageState usageStateInstance;
                        usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent());
                        siteInstance.setUsageState(usageStateInstance);
                    }

                    Element webSpaceElement = XmlUtility.getElementByTagNameNS(sitesElement,
                            "http://schemas.microsoft.com/windowsazure", "WebSpace");
                    if (webSpaceElement != null) {
                        String webSpaceInstance;
                        webSpaceInstance = webSpaceElement.getTextContent();
                        siteInstance.setWebSpace(webSpaceInstance);
                    }
                }
            }

        }
        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:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.StoredIDDataConnectorBeanDefinitionParser.java

/**
 * Builds a JDBC {@link javax.sql.DataSource} from an ApplicationManagedConnection configuration element.
 * //from   ww w .j a va 2 s  . co  m
 * @param pluginId ID of this data connector
 * @param amc the application managed configuration element
 * 
 * @return the built data source
 */
protected DataSource buildApplicationManagedConnection(String pluginId, Element amc) {
    ComboPooledDataSource datasource = new ComboPooledDataSource();

    String driverClass = DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcDriver"));
    ClassLoader classLoader = this.getClass().getClassLoader();
    try {
        classLoader.loadClass(driverClass);
    } catch (ClassNotFoundException e) {
        log.error(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
        throw new BeanCreationException(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
    }

    try {
        datasource.setDriverClass(driverClass);
        datasource.setJdbcUrl(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcURL")));
        datasource.setUser(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcUserName")));
        datasource.setPassword(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcPassword")));

        if (amc.hasAttributeNS(null, "poolAcquireIncrement")) {
            datasource.setAcquireIncrement(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireIncrement"))));
        } else {
            datasource.setAcquireIncrement(3);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryAttempts")) {
            datasource.setAcquireRetryAttempts(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryAttempts"))));
        } else {
            datasource.setAcquireRetryAttempts(36);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryDelay")) {
            datasource.setAcquireRetryDelay(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryDelay"))));
        } else {
            datasource.setAcquireRetryDelay(5000);
        }

        if (amc.hasAttributeNS(null, "poolBreakAfterAcquireFailure")) {
            datasource.setBreakAfterAcquireFailure(XMLHelper
                    .getAttributeValueAsBoolean(amc.getAttributeNodeNS(null, "poolBreakAfterAcquireFailure")));
        } else {
            datasource.setBreakAfterAcquireFailure(true);
        }

        if (amc.hasAttributeNS(null, "poolMinSize")) {
            datasource.setMinPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMinSize"))));
        } else {
            datasource.setMinPoolSize(2);
        }

        if (amc.hasAttributeNS(null, "poolMaxSize")) {
            datasource.setMaxPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxSize"))));
        } else {
            datasource.setMaxPoolSize(50);
        }

        if (amc.hasAttributeNS(null, "poolMaxIdleTime")) {
            datasource.setMaxIdleTime(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxIdleTime"))));
        } else {
            datasource.setMaxIdleTime(600);
        }

        if (amc.hasAttributeNS(null, "poolIdleTestPeriod")) {
            datasource.setIdleConnectionTestPeriod(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolIdleTestPeriod"))));
        } else {
            datasource.setIdleConnectionTestPeriod(180);
        }

        datasource.setMaxStatementsPerConnection(10);

        log.debug("Created application managed data source for data connector {}", pluginId);
        return datasource;
    } catch (PropertyVetoException e) {
        log.error("Unable to create data source for data connector {} with JDBC driver class {}", pluginId,
                driverClass);
        return null;
    }
}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.LdapDataConnectorBeanDefinitionParser.java

/**
 * Process the pooling configuration for the LDAP data connector.
 * /*from  w w  w .j  a v  a2s .com*/
 * @param pluginId ID of the LDAP plugin
 * @param pluginConfig LDAP plugin configuration element
 * @param pluginConfigChildren child elements of the plugin
 * @param pluginBuilder plugin builder
 * @param parserContext current parsing context
 */
protected void processPoolingConfig(String pluginId, Element pluginConfig,
        Map<QName, List<Element>> pluginConfigChildren, BeanDefinitionBuilder pluginBuilder,
        ParserContext parserContext) {

    List<Element> poolConfigElems = pluginConfigChildren
            .get(new QName(DataConnectorNamespaceHandler.NAMESPACE, "ConnectionPool"));
    if (poolConfigElems == null || poolConfigElems.size() == 0) {
        log.debug("Data connector {} is pooling connections: {}", pluginId, false);
        pluginBuilder.addPropertyValue("poolStrategy", new LdapPoolEmptyStrategy());
        return;
    }

    Element poolConfigElem = poolConfigElems.get(0);

    LdapPoolConfig ldapPoolConfig = new LdapPoolConfig();
    LdapPoolVTStrategy ldapPoolStrategy = new LdapPoolVTStrategy();
    ldapPoolStrategy.setLdapPoolConfig(ldapPoolConfig);
    log.debug("Data connector {} is pooling connections: {}", pluginId, true);
    pluginBuilder.addPropertyValue("poolStrategy", ldapPoolStrategy);

    int poolMinSize = 0;
    if (pluginConfig.hasAttributeNS(null, "poolInitialSize")) {
        poolMinSize = Integer.parseInt(pluginConfig.getAttributeNS(null, "poolInitialSize"));
        log.warn(
                "Data connector {} using deprecated attribute poolInitialSize on <DataConnector> use minPoolSize on child <PoolConfig> instead");
    } else if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "minPoolSize")) {
        poolMinSize = Integer.parseInt(poolConfigElem.getAttributeNS(null, "minPoolSize"));
    }
    log.debug("Data connector {} pool minimum connections: {}", pluginId, poolMinSize);
    ldapPoolConfig.setMinPoolSize(poolMinSize);

    int poolMaxSize = 3;
    if (pluginConfig.hasAttributeNS(null, "poolMaxIdleSize")) {
        poolMaxSize = Integer.parseInt(pluginConfig.getAttributeNS(null, "poolMaxIdleSize"));
        log.warn(
                "Data connector {} using deprecated attribute poolMaxIdleSize on <DataConnector> use maxPoolSize on child <PoolConfig> instead");
    } else if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "maxPoolSize")) {
        poolMaxSize = Integer.parseInt(poolConfigElem.getAttributeNS(null, "maxPoolSize"));
    }
    log.debug("Data connector {} pool maximum connections: {}", pluginId, poolMaxSize);
    ldapPoolConfig.setMaxPoolSize(poolMaxSize);

    boolean blockWhenEmpty = true;
    if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "blockWhenEmpty")) {
        blockWhenEmpty = XMLHelper
                .getAttributeValueAsBoolean(poolConfigElem.getAttributeNodeNS(null, "blockWhenEmpty"));
    }
    log.debug("Data connector {} pool block when empty: {}", pluginId, blockWhenEmpty);
    ldapPoolStrategy.setBlockWhenEmpty(blockWhenEmpty);

    int blockWaitTime = 0;
    if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "blockWaitTime")) {
        blockWaitTime = (int) SpringConfigurationUtils.parseDurationToMillis("blockWaitTime",
                poolConfigElem.getAttributeNS(null, "blockWaitTime"), 0);
    }
    if (blockWaitTime == 0) {
        log.debug("Data connector {} pool block wait time: indefintely", pluginId);
    } else {
        log.debug("Data connector {} pool block wait time: {}ms", pluginId, blockWaitTime);
    }
    ldapPoolStrategy.setBlockWaitTime(blockWaitTime);

    boolean poolValidatePeriodically = false;
    if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validatePeriodically")) {
        poolValidatePeriodically = XMLHelper
                .getAttributeValueAsBoolean(poolConfigElem.getAttributeNodeNS(null, "validatePeriodically"));
    }
    log.debug("Data connector {} pool validate periodically: {}", pluginId, poolValidatePeriodically);
    ldapPoolConfig.setValidatePeriodically(poolValidatePeriodically);

    int poolValidateTimerPeriod = 1800000;
    if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validateTimerPeriod")) {
        poolValidateTimerPeriod = (int) SpringConfigurationUtils.parseDurationToMillis("validateTimerPeriod",
                poolConfigElem.getAttributeNS(null, "validateTimerPeriod"), 0);
    }
    log.debug("Data connector {} pool validate timer period: {}ms", pluginId, poolValidateTimerPeriod);
    ldapPoolConfig.setValidateTimerPeriod(poolValidateTimerPeriod);

    String poolValidateDn = "";
    if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validateDN")) {
        poolValidateDn = poolConfigElem.getAttributeNS(null, "validateDN");
    }
    String poolValidateFilter = "(objectClass=*)";
    if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validateFilter")) {
        poolValidateFilter = poolConfigElem.getAttributeNS(null, "validateFilter");
    }
    LdapValidator poolValidator = new CompareLdapValidator(poolValidateDn,
            new SearchFilter(poolValidateFilter));
    log.debug("Data connector {} pool validation filter: {}", pluginId, poolValidateFilter);
    pluginBuilder.addPropertyValue("poolValidator", poolValidator);

    int poolExpirationTime = 600000;
    if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "expirationTime")) {
        poolExpirationTime = (int) SpringConfigurationUtils.parseDurationToMillis("expirationTime",
                poolConfigElem.getAttributeNS(null, "expirationTime"), 0);
    }
    log.debug("Data connector {} pool expiration time: {}ms", pluginId, poolExpirationTime);
    ldapPoolConfig.setExpirationTime(poolExpirationTime);
}

From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java

/**
* The Get Storage Account Properties operation returns system properties
* for the specified storage account.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx for
* more information)//from ww  w  .j  a  v a 2 s . c om
*
* @param accountName Required. Name of the storage account to get
* properties for.
* @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 The Get Storage Account Properties operation response.
*/
@Override
public StorageAccountGetResponse get(String accountName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (accountName == null) {
        throw new NullPointerException("accountName");
    }

    // 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("accountName", accountName);
        CloudTracing.enter(invocationId, this, "getAsync", 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/storageservices/";
    url = url + URLEncoder.encode(accountName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2014-10-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
        StorageAccountGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new StorageAccountGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element storageServiceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "StorageService");
            if (storageServiceElement != null) {
                StorageAccount storageServiceInstance = new StorageAccount();
                result.setStorageAccount(storageServiceInstance);

                Element urlElement = XmlUtility.getElementByTagNameNS(storageServiceElement,
                        "http://schemas.microsoft.com/windowsazure", "Url");
                if (urlElement != null) {
                    URI urlInstance;
                    urlInstance = new URI(urlElement.getTextContent());
                    storageServiceInstance.setUri(urlInstance);
                }

                Element serviceNameElement = XmlUtility.getElementByTagNameNS(storageServiceElement,
                        "http://schemas.microsoft.com/windowsazure", "ServiceName");
                if (serviceNameElement != null) {
                    String serviceNameInstance;
                    serviceNameInstance = serviceNameElement.getTextContent();
                    storageServiceInstance.setName(serviceNameInstance);
                }

                Element storageServicePropertiesElement = XmlUtility.getElementByTagNameNS(
                        storageServiceElement, "http://schemas.microsoft.com/windowsazure",
                        "StorageServiceProperties");
                if (storageServicePropertiesElement != null) {
                    StorageAccountProperties storageServicePropertiesInstance = new StorageAccountProperties();
                    storageServiceInstance.setProperties(storageServicePropertiesInstance);

                    Element descriptionElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "Description");
                    if (descriptionElement != null) {
                        boolean isNil = false;
                        Attr nilAttribute = descriptionElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute != null) {
                            isNil = "true".equals(nilAttribute.getValue());
                        }
                        if (isNil == false) {
                            String descriptionInstance;
                            descriptionInstance = descriptionElement.getTextContent();
                            storageServicePropertiesInstance.setDescription(descriptionInstance);
                        }
                    }

                    Element affinityGroupElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "AffinityGroup");
                    if (affinityGroupElement != null) {
                        String affinityGroupInstance;
                        affinityGroupInstance = affinityGroupElement.getTextContent();
                        storageServicePropertiesInstance.setAffinityGroup(affinityGroupInstance);
                    }

                    Element locationElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Location");
                    if (locationElement != null) {
                        String locationInstance;
                        locationInstance = locationElement.getTextContent();
                        storageServicePropertiesInstance.setLocation(locationInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent() != null
                                ? new String(Base64.decode(labelElement.getTextContent()))
                                : null;
                        storageServicePropertiesInstance.setLabel(labelInstance);
                    }

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

                    Element endpointsSequenceElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "Endpoints");
                    if (endpointsSequenceElement != null) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(endpointsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Endpoint")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element endpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(endpointsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Endpoint")
                                    .get(i1));
                            storageServicePropertiesInstance.getEndpoints()
                                    .add(new URI(endpointsElement.getTextContent()));
                        }
                    }

                    Element geoPrimaryRegionElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "GeoPrimaryRegion");
                    if (geoPrimaryRegionElement != null) {
                        String geoPrimaryRegionInstance;
                        geoPrimaryRegionInstance = geoPrimaryRegionElement.getTextContent();
                        storageServicePropertiesInstance.setGeoPrimaryRegion(geoPrimaryRegionInstance);
                    }

                    Element statusOfPrimaryElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "StatusOfPrimary");
                    if (statusOfPrimaryElement != null && statusOfPrimaryElement.getTextContent() != null
                            && !statusOfPrimaryElement.getTextContent().isEmpty()) {
                        GeoRegionStatus statusOfPrimaryInstance;
                        statusOfPrimaryInstance = GeoRegionStatus
                                .valueOf(statusOfPrimaryElement.getTextContent());
                        storageServicePropertiesInstance.setStatusOfGeoPrimaryRegion(statusOfPrimaryInstance);
                    }

                    Element lastGeoFailoverTimeElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "LastGeoFailoverTime");
                    if (lastGeoFailoverTimeElement != null
                            && lastGeoFailoverTimeElement.getTextContent() != null
                            && !lastGeoFailoverTimeElement.getTextContent().isEmpty()) {
                        Calendar lastGeoFailoverTimeInstance;
                        lastGeoFailoverTimeInstance = DatatypeConverter
                                .parseDateTime(lastGeoFailoverTimeElement.getTextContent());
                        storageServicePropertiesInstance.setLastGeoFailoverTime(lastGeoFailoverTimeInstance);
                    }

                    Element geoSecondaryRegionElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "GeoSecondaryRegion");
                    if (geoSecondaryRegionElement != null) {
                        String geoSecondaryRegionInstance;
                        geoSecondaryRegionInstance = geoSecondaryRegionElement.getTextContent();
                        storageServicePropertiesInstance.setGeoSecondaryRegion(geoSecondaryRegionInstance);
                    }

                    Element statusOfSecondaryElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "StatusOfSecondary");
                    if (statusOfSecondaryElement != null && statusOfSecondaryElement.getTextContent() != null
                            && !statusOfSecondaryElement.getTextContent().isEmpty()) {
                        GeoRegionStatus statusOfSecondaryInstance;
                        statusOfSecondaryInstance = GeoRegionStatus
                                .valueOf(statusOfSecondaryElement.getTextContent());
                        storageServicePropertiesInstance
                                .setStatusOfGeoSecondaryRegion(statusOfSecondaryInstance);
                    }

                    Element accountTypeElement = XmlUtility.getElementByTagNameNS(
                            storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                            "AccountType");
                    if (accountTypeElement != null) {
                        String accountTypeInstance;
                        accountTypeInstance = accountTypeElement.getTextContent();
                        storageServicePropertiesInstance.setAccountType(accountTypeInstance);
                    }
                }

                Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(
                        storageServiceElement, "http://schemas.microsoft.com/windowsazure",
                        "ExtendedProperties");
                if (extendedPropertiesSequenceElement != null) {
                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(extendedPropertiesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ExtendedProperty")
                            .size(); i2 = i2 + 1) {
                        org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(extendedPropertiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ExtendedProperty")
                                .get(i2));
                        String extendedPropertiesKey = XmlUtility
                                .getElementByTagNameNS(extendedPropertiesElement,
                                        "http://schemas.microsoft.com/windowsazure", "Name")
                                .getTextContent();
                        String extendedPropertiesValue = XmlUtility
                                .getElementByTagNameNS(extendedPropertiesElement,
                                        "http://schemas.microsoft.com/windowsazure", "Value")
                                .getTextContent();
                        storageServiceInstance.getExtendedProperties().put(extendedPropertiesKey,
                                extendedPropertiesValue);
                    }
                }
            }

        }
        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.storage.StorageAccountOperationsImpl.java

/**
* The List Storage Accounts operation lists the storage accounts available
* under the current subscription.  (see//w  w  w  .  ja  v a 2s  . co  m
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460787.aspx for
* more information)
*
* @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 The List Storage Accounts operation response.
*/
@Override
public StorageAccountListResponse list()
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // 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, "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/storageservices";
    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-10-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
        StorageAccountListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new StorageAccountListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element storageServicesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "StorageServices");
            if (storageServicesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(storageServicesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "StorageService")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element storageServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(storageServicesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "StorageService")
                            .get(i1));
                    StorageAccount storageServiceInstance = new StorageAccount();
                    result.getStorageAccounts().add(storageServiceInstance);

                    Element urlElement = XmlUtility.getElementByTagNameNS(storageServicesElement,
                            "http://schemas.microsoft.com/windowsazure", "Url");
                    if (urlElement != null) {
                        URI urlInstance;
                        urlInstance = new URI(urlElement.getTextContent());
                        storageServiceInstance.setUri(urlInstance);
                    }

                    Element serviceNameElement = XmlUtility.getElementByTagNameNS(storageServicesElement,
                            "http://schemas.microsoft.com/windowsazure", "ServiceName");
                    if (serviceNameElement != null) {
                        String serviceNameInstance;
                        serviceNameInstance = serviceNameElement.getTextContent();
                        storageServiceInstance.setName(serviceNameInstance);
                    }

                    Element storageServicePropertiesElement = XmlUtility.getElementByTagNameNS(
                            storageServicesElement, "http://schemas.microsoft.com/windowsazure",
                            "StorageServiceProperties");
                    if (storageServicePropertiesElement != null) {
                        StorageAccountProperties storageServicePropertiesInstance = new StorageAccountProperties();
                        storageServiceInstance.setProperties(storageServicePropertiesInstance);

                        Element descriptionElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "Description");
                        if (descriptionElement != null) {
                            boolean isNil = false;
                            Attr nilAttribute = descriptionElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute != null) {
                                isNil = "true".equals(nilAttribute.getValue());
                            }
                            if (isNil == false) {
                                String descriptionInstance;
                                descriptionInstance = descriptionElement.getTextContent();
                                storageServicePropertiesInstance.setDescription(descriptionInstance);
                            }
                        }

                        Element affinityGroupElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "AffinityGroup");
                        if (affinityGroupElement != null) {
                            String affinityGroupInstance;
                            affinityGroupInstance = affinityGroupElement.getTextContent();
                            storageServicePropertiesInstance.setAffinityGroup(affinityGroupInstance);
                        }

                        Element locationElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "Location");
                        if (locationElement != null) {
                            String locationInstance;
                            locationInstance = locationElement.getTextContent();
                            storageServicePropertiesInstance.setLocation(locationInstance);
                        }

                        Element labelElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement,
                                "http://schemas.microsoft.com/windowsazure", "Label");
                        if (labelElement != null) {
                            String labelInstance;
                            labelInstance = labelElement.getTextContent() != null
                                    ? new String(Base64.decode(labelElement.getTextContent()))
                                    : null;
                            storageServicePropertiesInstance.setLabel(labelInstance);
                        }

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

                        Element endpointsSequenceElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "Endpoints");
                        if (endpointsSequenceElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(endpointsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Endpoint")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element endpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(endpointsSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "Endpoint")
                                        .get(i2));
                                storageServicePropertiesInstance.getEndpoints()
                                        .add(new URI(endpointsElement.getTextContent()));
                            }
                        }

                        Element geoPrimaryRegionElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "GeoPrimaryRegion");
                        if (geoPrimaryRegionElement != null) {
                            String geoPrimaryRegionInstance;
                            geoPrimaryRegionInstance = geoPrimaryRegionElement.getTextContent();
                            storageServicePropertiesInstance.setGeoPrimaryRegion(geoPrimaryRegionInstance);
                        }

                        Element statusOfPrimaryElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "StatusOfPrimary");
                        if (statusOfPrimaryElement != null && statusOfPrimaryElement.getTextContent() != null
                                && !statusOfPrimaryElement.getTextContent().isEmpty()) {
                            GeoRegionStatus statusOfPrimaryInstance;
                            statusOfPrimaryInstance = GeoRegionStatus
                                    .valueOf(statusOfPrimaryElement.getTextContent());
                            storageServicePropertiesInstance
                                    .setStatusOfGeoPrimaryRegion(statusOfPrimaryInstance);
                        }

                        Element lastGeoFailoverTimeElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "LastGeoFailoverTime");
                        if (lastGeoFailoverTimeElement != null
                                && lastGeoFailoverTimeElement.getTextContent() != null
                                && !lastGeoFailoverTimeElement.getTextContent().isEmpty()) {
                            Calendar lastGeoFailoverTimeInstance;
                            lastGeoFailoverTimeInstance = DatatypeConverter
                                    .parseDateTime(lastGeoFailoverTimeElement.getTextContent());
                            storageServicePropertiesInstance
                                    .setLastGeoFailoverTime(lastGeoFailoverTimeInstance);
                        }

                        Element geoSecondaryRegionElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "GeoSecondaryRegion");
                        if (geoSecondaryRegionElement != null) {
                            String geoSecondaryRegionInstance;
                            geoSecondaryRegionInstance = geoSecondaryRegionElement.getTextContent();
                            storageServicePropertiesInstance.setGeoSecondaryRegion(geoSecondaryRegionInstance);
                        }

                        Element statusOfSecondaryElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "StatusOfSecondary");
                        if (statusOfSecondaryElement != null
                                && statusOfSecondaryElement.getTextContent() != null
                                && !statusOfSecondaryElement.getTextContent().isEmpty()) {
                            GeoRegionStatus statusOfSecondaryInstance;
                            statusOfSecondaryInstance = GeoRegionStatus
                                    .valueOf(statusOfSecondaryElement.getTextContent());
                            storageServicePropertiesInstance
                                    .setStatusOfGeoSecondaryRegion(statusOfSecondaryInstance);
                        }

                        Element accountTypeElement = XmlUtility.getElementByTagNameNS(
                                storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure",
                                "AccountType");
                        if (accountTypeElement != null) {
                            String accountTypeInstance;
                            accountTypeInstance = accountTypeElement.getTextContent();
                            storageServicePropertiesInstance.setAccountType(accountTypeInstance);
                        }
                    }

                    Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(
                            storageServicesElement, "http://schemas.microsoft.com/windowsazure",
                            "ExtendedProperties");
                    if (extendedPropertiesSequenceElement != null) {
                        for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(extendedPropertiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ExtendedProperty")
                                .size(); i3 = i3 + 1) {
                            org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(extendedPropertiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "ExtendedProperty")
                                    .get(i3));
                            String extendedPropertiesKey = XmlUtility
                                    .getElementByTagNameNS(extendedPropertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String extendedPropertiesValue = XmlUtility
                                    .getElementByTagNameNS(extendedPropertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            storageServiceInstance.getExtendedProperties().put(extendedPropertiesKey,
                                    extendedPropertiesValue);
                        }
                    }
                }
            }

        }
        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:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.RDBMSDataConnectorBeanDefinitionParser.java

/**
 * Builds a JDBC {@link javax.sql.DataSource} from an ApplicationManagedConnection configuration element.
 * //  w  ww. j  a  v a2  s.  c o  m
 * @param pluginId ID of this data connector
 * @param amc the application managed configuration element
 * 
 * @return the built data source
 */
protected DataSource buildApplicationManagedConnection(String pluginId, Element amc) {
    ComboPooledDataSource datasource = new ComboPooledDataSource();

    String driverClass = DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcDriver"));
    ClassLoader classLoader = this.getClass().getClassLoader();
    try {
        classLoader.loadClass(driverClass);
    } catch (ClassNotFoundException e) {
        log.error(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
        throw new BeanCreationException(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
    }

    try {
        datasource.setDriverClass(driverClass);
        datasource.setJdbcUrl(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcURL")));
        datasource.setUser(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcUserName")));
        datasource.setPassword(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcPassword")));

        if (amc.hasAttributeNS(null, "poolAcquireIncrement")) {
            datasource.setAcquireIncrement(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireIncrement"))));
        } else {
            datasource.setAcquireIncrement(3);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryAttempts")) {
            datasource.setAcquireRetryAttempts(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryAttempts"))));
        } else {
            datasource.setAcquireRetryAttempts(36);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryDelay")) {
            datasource.setAcquireRetryDelay(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryDelay"))));
        } else {
            datasource.setAcquireRetryDelay(5000);
        }

        if (amc.hasAttributeNS(null, "poolBreakAfterAcquireFailure")) {
            datasource.setBreakAfterAcquireFailure(XMLHelper
                    .getAttributeValueAsBoolean(amc.getAttributeNodeNS(null, "poolBreakAfterAcquireFailure")));
        } else {
            datasource.setBreakAfterAcquireFailure(true);
        }

        if (amc.hasAttributeNS(null, "poolMinSize")) {
            datasource.setMinPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMinSize"))));
        } else {
            datasource.setMinPoolSize(2);
        }

        if (amc.hasAttributeNS(null, "poolMaxSize")) {
            datasource.setMaxPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxSize"))));
        } else {
            datasource.setMaxPoolSize(50);
        }

        if (amc.hasAttributeNS(null, "poolMaxIdleTime")) {
            datasource.setMaxIdleTime(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxIdleTime"))));
        } else {
            datasource.setMaxIdleTime(600);
        }

        if (amc.hasAttributeNS(null, "poolIdleTestPeriod")) {
            datasource.setIdleConnectionTestPeriod(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolIdleTestPeriod"))));
        } else {
            datasource.setIdleConnectionTestPeriod(180);
        }

        log.debug("Created application managed data source for data connector {}", pluginId);
        return datasource;
    } catch (PropertyVetoException e) {
        log.error("Unable to create data source for data connector {} with JDBC driver class {}", pluginId,
                driverClass);
        return null;
    }
}

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

/**
* Returns information about an Azure SQL Database event logs.
*
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.//from  ww w  .  j  av a2  s. com
* @param databaseName Required. The name of the Azure SQL Database to be
* retrieved.
* @param parameters Required. The parameters for the Get Database Event
* Logs 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 Contains the response to a Get Database Event Logs request.
*/
@Override
public DatabaseGetEventLogsResponse getEventLogs(String serverName, String databaseName,
        DatabaseGetEventLogsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEventTypes() == null) {
        throw new NullPointerException("parameters.EventTypes");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/events";
    ArrayList<String> queryParameters = new ArrayList<String>();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    queryParameters.add("startDate="
            + URLEncoder.encode(simpleDateFormat.format(parameters.getStartDate().getTime()), "UTF-8"));
    queryParameters.add("intervalSizeInMinutes="
            + URLEncoder.encode(Integer.toString(parameters.getIntervalSizeInMinutes()), "UTF-8"));
    queryParameters.add("eventTypes=" + URLEncoder.encode(parameters.getEventTypes(), "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
        DatabaseGetEventLogsResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseGetEventLogsResponse();
            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));
                    DatabaseEventLog serviceResourceInstance = new DatabaseEventLog();
                    result.getEventLogs().add(serviceResourceInstance);

                    Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "DatabaseName");
                    if (databaseNameElement != null) {
                        String databaseNameInstance;
                        databaseNameInstance = databaseNameElement.getTextContent();
                        serviceResourceInstance.setDatabaseName(databaseNameInstance);
                    }

                    Element startTimeUtcElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "StartTimeUtc");
                    if (startTimeUtcElement != null) {
                        Calendar startTimeUtcInstance;
                        startTimeUtcInstance = DatatypeConverter
                                .parseDateTime(startTimeUtcElement.getTextContent());
                        serviceResourceInstance.setStartTimeUtc(startTimeUtcInstance);
                    }

                    Element intervalSizeInMinutesElement = XmlUtility.getElementByTagNameNS(
                            serviceResourcesElement, "http://schemas.microsoft.com/windowsazure",
                            "IntervalSizeInMinutes");
                    if (intervalSizeInMinutesElement != null) {
                        int intervalSizeInMinutesInstance;
                        intervalSizeInMinutesInstance = DatatypeConverter
                                .parseInt(intervalSizeInMinutesElement.getTextContent());
                        serviceResourceInstance.setIntervalSizeInMinutes(intervalSizeInMinutesInstance);
                    }

                    Element eventCategoryElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EventCategory");
                    if (eventCategoryElement != null) {
                        String eventCategoryInstance;
                        eventCategoryInstance = eventCategoryElement.getTextContent();
                        serviceResourceInstance.setEventCategory(eventCategoryInstance);
                    }

                    Element eventTypeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EventType");
                    if (eventTypeElement != null) {
                        String eventTypeInstance;
                        eventTypeInstance = eventTypeElement.getTextContent();
                        serviceResourceInstance.setEventType(eventTypeInstance);
                    }

                    Element eventSubtypeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EventSubtype");
                    if (eventSubtypeElement != null) {
                        String eventSubtypeInstance;
                        eventSubtypeInstance = eventSubtypeElement.getTextContent();
                        serviceResourceInstance.setEventSubtype(eventSubtypeInstance);
                    }

                    Element eventSubtypeDescriptionElement = XmlUtility.getElementByTagNameNS(
                            serviceResourcesElement, "http://schemas.microsoft.com/windowsazure",
                            "EventSubtypeDescription");
                    if (eventSubtypeDescriptionElement != null) {
                        String eventSubtypeDescriptionInstance;
                        eventSubtypeDescriptionInstance = eventSubtypeDescriptionElement.getTextContent();
                        serviceResourceInstance.setEventSubtypeDescription(eventSubtypeDescriptionInstance);
                    }

                    Element numberOfEventsElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "NumberOfEvents");
                    if (numberOfEventsElement != null) {
                        int numberOfEventsInstance;
                        numberOfEventsInstance = DatatypeConverter
                                .parseInt(numberOfEventsElement.getTextContent());
                        serviceResourceInstance.setNumberOfEvents(numberOfEventsInstance);
                    }

                    Element severityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Severity");
                    if (severityElement != null) {
                        int severityInstance;
                        severityInstance = DatatypeConverter.parseInt(severityElement.getTextContent());
                        serviceResourceInstance.setSeverity(severityInstance);
                    }

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

                    Element additionalDataElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "AdditionalData");
                    if (additionalDataElement != null) {
                        boolean isNil = false;
                        Attr nilAttribute = additionalDataElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute != null) {
                            isNil = "true".equals(nilAttribute.getValue());
                        }
                        if (isNil == false) {
                            String additionalDataInstance;
                            additionalDataInstance = additionalDataElement.getTextContent();
                            serviceResourceInstance.setAdditionalData(additionalDataInstance);
                        }
                    }

                    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.microsoft.windowsazure.management.websites.WebSiteOperationsImpl.java

/**
* You can swap a web site from one slot to another slot.
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param sourceSlotName Required. The name of the first web site slot to
* swap (source).// w  w w  .j a v  a  2 s  .c  om
* @param targetSlotName Required. The name of the second web site slot to
* swap with (target).
* @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
* long-running operation, indicating whether it has succeeded, is
* inprogress, has timed out, or has failed. Note that this status is
* distinct from the HTTP status code returned for the Get Operation Status
* operation itself. If the long-running operation failed, the response
* body includes error information regarding the failure.
*/
@Override
public WebSiteOperationStatusResponse beginSwappingSlots(String webSpaceName, String webSiteName,
        String sourceSlotName, String targetSlotName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (sourceSlotName == null) {
        throw new NullPointerException("sourceSlotName");
    }
    if (targetSlotName == null) {
        throw new NullPointerException("targetSlotName");
    }

    // 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("webSiteName", webSiteName);
        tracingParameters.put("sourceSlotName", sourceSlotName);
        tracingParameters.put("targetSlotName", targetSlotName);
        CloudTracing.enter(invocationId, this, "beginSwappingSlotsAsync", 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 + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    url = url + "(";
    url = url + URLEncoder.encode(sourceSlotName, "UTF-8");
    url = url + ")/slots";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("Command=swap");
    queryParameters.add("targetSlot=" + URLEncoder.encode(targetSlotName, "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
    HttpPost httpRequest = new HttpPost(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
        WebSiteOperationStatusResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSiteOperationStatusResponse();
            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 createdTimeElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "CreatedTime");
                if (createdTimeElement != null) {
                    Calendar createdTimeInstance;
                    createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent());
                    result.setCreatedTime(createdTimeInstance);
                }

                Element errorsSequenceElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Errors");
                if (errorsSequenceElement != null) {
                    boolean isNil = false;
                    Attr nilAttribute = errorsSequenceElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute != null) {
                        isNil = "true".equals(nilAttribute.getValue());
                    }
                    if (isNil == false) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(errorsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Error")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element errorsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(errorsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Error")
                                    .get(i1));
                            WebSiteOperationStatusResponse.Error errorInstance = new WebSiteOperationStatusResponse.Error();
                            result.getErrors().add(errorInstance);

                            Element codeElement = XmlUtility.getElementByTagNameNS(errorsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Code");
                            if (codeElement != null) {
                                boolean isNil2 = false;
                                Attr nilAttribute2 = codeElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute2 != null) {
                                    isNil2 = "true".equals(nilAttribute2.getValue());
                                }
                                if (isNil2 == false) {
                                    String codeInstance;
                                    codeInstance = codeElement.getTextContent();
                                    errorInstance.setCode(codeInstance);
                                }
                            }

                            Element messageElement = XmlUtility.getElementByTagNameNS(errorsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Message");
                            if (messageElement != null) {
                                boolean isNil3 = false;
                                Attr nilAttribute3 = messageElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute3 != null) {
                                    isNil3 = "true".equals(nilAttribute3.getValue());
                                }
                                if (isNil3 == false) {
                                    String messageInstance;
                                    messageInstance = messageElement.getTextContent();
                                    errorInstance.setMessage(messageInstance);
                                }
                            }

                            Element extendedCodeElement = XmlUtility.getElementByTagNameNS(errorsElement,
                                    "http://schemas.microsoft.com/windowsazure", "ExtendedCode");
                            if (extendedCodeElement != null) {
                                boolean isNil4 = false;
                                Attr nilAttribute4 = extendedCodeElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute4 != null) {
                                    isNil4 = "true".equals(nilAttribute4.getValue());
                                }
                                if (isNil4 == false) {
                                    String extendedCodeInstance;
                                    extendedCodeInstance = extendedCodeElement.getTextContent();
                                    errorInstance.setExtendedCode(extendedCodeInstance);
                                }
                            }

                            Element messageTemplateElement = XmlUtility.getElementByTagNameNS(errorsElement,
                                    "http://schemas.microsoft.com/windowsazure", "MessageTemplate");
                            if (messageTemplateElement != null) {
                                boolean isNil5 = false;
                                Attr nilAttribute5 = messageTemplateElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute5 != null) {
                                    isNil5 = "true".equals(nilAttribute5.getValue());
                                }
                                if (isNil5 == false) {
                                    String messageTemplateInstance;
                                    messageTemplateInstance = messageTemplateElement.getTextContent();
                                    errorInstance.setMessageTemplate(messageTemplateInstance);
                                }
                            }

                            Element parametersSequenceElement = XmlUtility.getElementByTagNameNS(errorsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Parameters");
                            if (parametersSequenceElement != null) {
                                boolean isNil6 = false;
                                Attr nilAttribute6 = parametersSequenceElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute6 != null) {
                                    isNil6 = "true".equals(nilAttribute6.getValue());
                                }
                                if (isNil6 == false) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(parametersSequenceElement,
                                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays",
                                                    "string")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element parametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(parametersSequenceElement,
                                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays",
                                                        "string")
                                                .get(i2));
                                        errorInstance.getParameters().add(parametersElement.getTextContent());
                                    }
                                } else {
                                    errorInstance.setParameters(null);
                                }
                            }

                            Element innerErrorsElement = XmlUtility.getElementByTagNameNS(errorsElement,
                                    "http://schemas.microsoft.com/windowsazure", "InnerErrors");
                            if (innerErrorsElement != null) {
                                boolean isNil7 = false;
                                Attr nilAttribute7 = innerErrorsElement
                                        .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                                if (nilAttribute7 != null) {
                                    isNil7 = "true".equals(nilAttribute7.getValue());
                                }
                                if (isNil7 == false) {
                                    String innerErrorsInstance;
                                    innerErrorsInstance = innerErrorsElement.getTextContent();
                                    errorInstance.setInnerErrors(innerErrorsInstance);
                                }
                            }
                        }
                    } else {
                        result.setErrors(null);
                    }
                }

                Element expirationTimeElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "ExpirationTime");
                if (expirationTimeElement != null) {
                    Calendar expirationTimeInstance;
                    expirationTimeInstance = DatatypeConverter
                            .parseDateTime(expirationTimeElement.getTextContent());
                    result.setExpirationTime(expirationTimeInstance);
                }

                Element geoMasterOperationIdElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "GeoMasterOperationId");
                if (geoMasterOperationIdElement != null) {
                    boolean isNil8 = false;
                    Attr nilAttribute8 = geoMasterOperationIdElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute8 != null) {
                        isNil8 = "true".equals(nilAttribute8.getValue());
                    }
                    if (isNil8 == false) {
                        String geoMasterOperationIdInstance;
                        geoMasterOperationIdInstance = geoMasterOperationIdElement.getTextContent();
                        result.setGeoMasterOperationId(geoMasterOperationIdInstance);
                    }
                }

                Element idElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Id");
                if (idElement != null) {
                    boolean isNil9 = false;
                    Attr nilAttribute9 = idElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute9 != null) {
                        isNil9 = "true".equals(nilAttribute9.getValue());
                    }
                    if (isNil9 == false) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

                Element modifiedTimeElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "ModifiedTime");
                if (modifiedTimeElement != null) {
                    Calendar modifiedTimeInstance;
                    modifiedTimeInstance = DatatypeConverter
                            .parseDateTime(modifiedTimeElement.getTextContent());
                    result.setModifiedTime(modifiedTimeInstance);
                }

                Element nameElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    boolean isNil10 = false;
                    Attr nilAttribute10 = nameElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute10 != null) {
                        isNil10 = "true".equals(nilAttribute10.getValue());
                    }
                    if (isNil10 == false) {
                        String nameInstance;
                        nameInstance = nameElement.getTextContent();
                        result.setName(nameInstance);
                    }
                }

                Element statusElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null && statusElement.getTextContent() != null
                        && !statusElement.getTextContent().isEmpty()) {
                    WebSiteOperationStatus statusInstance;
                    statusInstance = WebSiteOperationStatus.valueOf(statusElement.getTextContent());
                    result.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.websites.WebSiteOperationsImpl.java

/**
* You can retrieve historical usage metrics for a site by issuing an HTTP
* GET request.  (see/*from  w w  w .  ja v a  2s . 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 webSiteName Required. The name of the web site.
* @param parameters Required. Parameters supplied to the Get Historical
* Usage Metrics Web Site 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 Site operation response.
*/
@Override
public WebSiteGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName,
        String webSiteName, WebSiteGetHistoricalUsageMetricsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    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("webSiteName", webSiteName);
        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 + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "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"));
    queryParameters.add(
            "slotView=" + URLEncoder.encode(Boolean.toString(parameters.isSlotView()).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
        WebSiteGetHistoricalUsageMetricsResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSiteGetHistoricalUsageMetricsResponse();
            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();
        }
    }
}