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

/**
 * Processes query handling related configuration options.
 * /*from   w  w w  . j  av a 2  s .  com*/
 * @param pluginId ID of the data connector
 * @param pluginConfig configuration element for the data connector
 * @param pluginConfigChildren child config elements for the data connect
 * @param pluginBuilder builder of the data connector
 * @param parserContext current configuration parsing context
 */
protected void processQueryHandlingConfig(String pluginId, Element pluginConfig,
        Map<QName, List<Element>> pluginConfigChildren, BeanDefinitionBuilder pluginBuilder,
        ParserContext parserContext) {
    String templateEngineRef = pluginConfig.getAttributeNS(null, "templateEngine");
    pluginBuilder.addPropertyReference("templateEngine", templateEngineRef);

    List<Element> queryTemplateElems = pluginConfigChildren
            .get(new QName(DataConnectorNamespaceHandler.NAMESPACE, "QueryTemplate"));
    String queryTemplate = queryTemplateElems.get(0).getTextContent();
    log.debug("Data connector {} query template: {}", pluginId, queryTemplate);
    pluginBuilder.addPropertyValue("queryTemplate", queryTemplate);

    long queryTimeout = 5 * 1000;
    if (pluginConfig.hasAttributeNS(null, "queryTimeout")) {
        queryTimeout = SpringConfigurationUtils.parseDurationToMillis(
                "queryTimeout on relational database connector " + pluginId,
                pluginConfig.getAttributeNS(null, "queryTimeout"), 0);
    }
    log.debug("Data connector {} SQL query timeout: {}ms", pluginId, queryTimeout);
    pluginBuilder.addPropertyValue("queryTimeout", queryTimeout);

    boolean useSP = false;
    if (pluginConfig.hasAttributeNS(null, "queryUsesStoredProcedure")) {
        useSP = XMLHelper
                .getAttributeValueAsBoolean(pluginConfig.getAttributeNodeNS(null, "queryUsesStoredProcedure"));
    }
    log.debug("Data connector {} query uses stored procedures: {}", pluginId, useSP);
    pluginBuilder.addPropertyValue("queryUsesStoredProcedures", useSP);

    boolean readOnlyCtx = true;
    if (pluginConfig.hasAttributeNS(null, "readOnlyConnection")) {
        readOnlyCtx = XMLHelper
                .getAttributeValueAsBoolean(pluginConfig.getAttributeNodeNS(null, "readOnlyConnection"));
    }
    log.debug("Data connector {} connections are read only: {}", pluginId, readOnlyCtx);
    pluginBuilder.addPropertyValue("readOnlyConnections", readOnlyCtx);

}

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

/**
* Gets the status of the import or export operation in the specified server
* with the corresponding request ID.  The request ID is provided in the
* responses of the import or export operation.
*
* @param serverName Required. The name of the server in which the import or
* export operation is taking place.//from w w  w  .  j av a  2  s.co m
* @param fullyQualifiedServerName Required. The fully qualified domain name
* of the Azure SQL Database Server where the operation is taking place.
* Example: a9s7f7s9d3.database.windows.net
* @param username Required. The administrator username for the Azure SQL
* Database Server.
* @param password Required. The administrator password for the Azure SQL
* Database Server.
* @param requestId Required. The request ID of the operation being queried.
* The request ID is obtained from the responses of the import and export
* operations.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Represents a list of import or export status values returned from
* GetStatus.
*/
@Override
public DacGetStatusResponse getStatus(String serverName, String fullyQualifiedServerName, String username,
        String password, String requestId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (fullyQualifiedServerName == null) {
        throw new NullPointerException("fullyQualifiedServerName");
    }
    if (username == null) {
        throw new NullPointerException("username");
    }
    if (password == null) {
        throw new NullPointerException("password");
    }
    if (requestId == null) {
        throw new NullPointerException("requestId");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/DacOperations/Status";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("servername=" + URLEncoder.encode(fullyQualifiedServerName, "UTF-8"));
    queryParameters.add("username=" + URLEncoder.encode(username, "UTF-8"));
    queryParameters.add("password=" + URLEncoder.encode(password, "UTF-8"));
    queryParameters.add("reqId=" + URLEncoder.encode(requestId, "UTF-8"));
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
* Gets the status of the import or export operation in the specified server
* with the corresponding request ID.  The request ID is provided in the
* responses of the import or export operation.
*
* @param serverName Required. The name of the server in which the import or
* export operation is taking place.//from   w w w .j ava2s .  c  om
* @param parameters Required. The parameters needed to get the status of an
* import or export operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Represents a list of import or export status values returned from
* GetStatus.
*/
@Override
public DacGetStatusResponse getStatusPost(String serverName, DacGetStatusParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPassword() == null) {
        throw new NullPointerException("parameters.Password");
    }
    if (parameters.getRequestId() == null) {
        throw new NullPointerException("parameters.RequestId");
    }
    if (parameters.getServerName() == null) {
        throw new NullPointerException("parameters.ServerName");
    }
    if (parameters.getUserName() == null) {
        throw new NullPointerException("parameters.UserName");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
* You can retrieve historical usage metrics for a site by issuing an HTTP
* GET request.  (see//from  w w  w  .  ja va2  s  .co m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param webHostingPlanName Required. The name of the web hosting plan.
* @param parameters Required. Parameters supplied to the Get Historical
* Usage Metrics Web hosting plan operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The Get Historical Usage Metrics Web hosting plan operation
* response.
*/
@Override
public WebHostingPlanGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName,
        String webHostingPlanName, WebHostingPlanGetHistoricalUsageMetricsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webHostingPlanName == null) {
        throw new NullPointerException("webHostingPlanName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/serverFarms/";
    url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
    url = url + "/metrics";
    ArrayList<String> queryParameters = new ArrayList<String>();
    if (parameters.getMetricNames() != null && parameters.getMetricNames().size() > 0) {
        queryParameters.add("names="
                + URLEncoder.encode(CollectionStringBuilder.join(parameters.getMetricNames(), ","), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getStartTime() != null) {
        queryParameters.add("StartTime="
                + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getEndTime() != null) {
        queryParameters.add("EndTime="
                + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
    }
    if (parameters.getTimeGrain() != null) {
        queryParameters.add("timeGrain=" + URLEncoder.encode(parameters.getTimeGrain(), "UTF-8"));
    }
    queryParameters.add("details=" + URLEncoder
            .encode(Boolean.toString(parameters.isIncludeInstanceBreakdown()).toLowerCase(), "UTF-8"));
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * Processes the cache configuration directives.
 * //from w w  w  .  j  av a 2s.  co  m
 * @param pluginId ID of the plugin
 * @param pluginConfig configuration element for the plugin
 * @param pluginBuilder builder for the plugin
 */
protected void processCacheConfig(String pluginId, Element pluginConfig, BeanDefinitionBuilder pluginBuilder) {
    boolean cacheResults = false;
    String cacheManagerId = "shibboleth.CacheManager";
    long cacheElementTtl = 4 * 60 * 60 * 1000;
    int maximumCachedElements = 500;

    List<Element> cacheConfigs = XMLHelper.getChildElementsByTagNameNS(pluginConfig,
            DataConnectorNamespaceHandler.NAMESPACE, "ResultCache");
    if (cacheConfigs != null && !cacheConfigs.isEmpty()) {
        Element cacheConfig = cacheConfigs.get(0);

        cacheResults = true;

        if (cacheConfig.hasAttributeNS(null, "cacheManagerRef")) {
            cacheManagerId = DatatypeHelper.safeTrim(cacheConfig.getAttributeNS(null, "cacheManagerRef"));
        }

        if (cacheConfig.hasAttributeNS(null, "elementTimeToLive")) {
            cacheElementTtl = SpringConfigurationUtils.parseDurationToMillis(
                    "elementTimeToLive on data connector " + pluginId,
                    cacheConfig.getAttributeNS(null, "elementTimeToLive"), 0);
        }

        if (cacheConfig.hasAttributeNS(null, "maximumCachedElements")) {
            maximumCachedElements = Integer.parseInt(
                    DatatypeHelper.safeTrim(cacheConfig.getAttributeNS(null, "maximumCachedElements")));
        }
    }

    if (pluginConfig.hasAttributeNS(null, "cacheResults")) {
        log.warn(
                "Data connection {}: use of 'cacheResults' attribute is deprecated.  Use <ResultCache> instead.",
                pluginId);
        cacheResults = XMLHelper
                .getAttributeValueAsBoolean(pluginConfig.getAttributeNodeNS(null, "cacheResults"));
    }

    if (cacheResults) {
        log.debug("Data connector {} is caching results: {}", pluginId, cacheResults);

        pluginBuilder.addPropertyReference("cacheManager", cacheManagerId);

        log.debug("Data connector {} cache element time to live: {}ms", pluginId, cacheElementTtl);
        pluginBuilder.addPropertyValue("cacheElementTimeToLive", cacheElementTtl);

        log.debug("Data connector {} maximum number of caches elements: {}", pluginId, maximumCachedElements);
        pluginBuilder.addPropertyValue("maximumCachedElements", maximumCachedElements);
    }

}

From source file:org.unitedid.shibboleth.config.attribute.resolver.dataConnector.MongoDbDataConnectorBeanDefinitionParser.java

/** {@inheritDoc} */
protected void doParse(String pluginId, Element pluginConfig, Map<QName, List<Element>> pluginConfigChildren,
        BeanDefinitionBuilder pluginBuilder, ParserContext parserContext) {
    super.doParse(pluginId, pluginConfig, pluginConfigChildren, pluginBuilder, parserContext);

    /**// ww w.  j av a 2 s  . c o  m
     * Data connector attributes (<resolver:DataConnector attr1="" attr2=""></resolver:DataConnector>)
     */
    String mongoDbName = pluginConfig.getAttributeNS(null, "mongoDbName");
    log.info("Data connector {} MONGODB DATABASE: {}", pluginId, mongoDbName);
    pluginBuilder.addPropertyValue("mongoDbName", mongoDbName);

    String mongoCollection = pluginConfig.getAttributeNS(null, "mongoCollection");
    log.info("Data connector {} MONGODB COLLECTION: {}", pluginId, mongoCollection);
    pluginBuilder.addPropertyValue("mongoCollection", mongoCollection);

    if (pluginConfig.hasAttributeNS(null, "mongoUser")) {
        String mongoUser = pluginConfig.getAttributeNS(null, "mongoUser");
        log.info("Data connector {} MONGODB USERNAME: {}", pluginId, mongoUser);
        pluginBuilder.addPropertyValue("mongoUser", mongoUser);
    }

    if (pluginConfig.hasAttributeNS(null, "mongoPassword")) {
        String mongoPassword = pluginConfig.getAttributeNS(null, "mongoPassword");
        pluginBuilder.addPropertyValue("mongoPassword", mongoPassword);
    }

    String preferredRead = "primaryPreferred";
    if (pluginConfig.hasAttributeNS(null, "preferredRead")) {
        preferredRead = pluginConfig.getAttributeNS(null, "preferredRead");
    }
    log.info("Data connector {} preferredRead type: {}", pluginId, preferredRead);
    pluginBuilder.addPropertyValue("preferredRead", preferredRead);

    boolean cacheResults = false;
    if (pluginConfig.hasAttributeNS(null, "cacheResults")) {
        cacheResults = XMLHelper
                .getAttributeValueAsBoolean(pluginConfig.getAttributeNodeNS(null, "cacheResults"));
    }
    log.info("Data connector {} cache results: {}", pluginId, cacheResults);
    pluginBuilder.addPropertyValue("cacheResults", cacheResults);

    /**
     * Mongodb host entries (<uid:MongoHost host="" port="" />)
     */
    List<ServerAddress> hosts = parseMongoHostNames(pluginId, pluginConfigChildren);
    log.debug("Data connector {} hosts {}", pluginId, hosts.toString());
    pluginBuilder.addPropertyValue("mongoHost", hosts);

    boolean usePersistentId = false;
    if (pluginConfigChildren.containsKey(PID_ELEMENT_NAME)) {
        Element e = pluginConfigChildren.get(PID_ELEMENT_NAME).get(0);
        pluginBuilder.addPropertyValue("pidGeneratedAttributeId",
                e.getAttributeNS(null, "generatedAttributeId"));
        pluginBuilder.addPropertyValue("pidSourceAttributeId", e.getAttributeNS(null, "sourceAttributeId"));
        usePersistentId = true;
    }
    log.info("Data connector {} running in persistentId mode: {}", pluginId, usePersistentId);
    pluginBuilder.addPropertyValue("usePersistentId", usePersistentId);

    List<MongoDbKeyAttributeMapper> keyAttributeMaps = parseAttributeMappings(pluginId, pluginConfigChildren);
    pluginBuilder.addPropertyValue("keyAttributeMap", keyAttributeMaps);

    if (!usePersistentId) {
        String queryTemplate = pluginConfigChildren.get(QUERY_TEMPLATE_ELEMENT_NAME).get(0).getTextContent();
        queryTemplate = DatatypeHelper.safeTrimOrNullString(queryTemplate);
        log.debug("Data connector {} query template: {}", pluginId, queryTemplate);
        pluginBuilder.addPropertyValue("queryTemplate", queryTemplate);
    }

    String templateEngineRef = pluginConfig.getAttributeNS(null, "templateEngine");
    pluginBuilder.addPropertyReference("templateEngine", templateEngineRef);
}

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

/**
 * Processes the cache configuration options.
 * /*w ww.jav  a 2s. c om*/
 * @param pluginId ID of the data connector
 * @param pluginConfig configuration element for the data connector
 * @param pluginConfigChildren child config elements for the data connect
 * @param pluginBuilder builder of the data connector
 * @param parserContext current configuration parsing context
 */
protected void processCacheConfig(String pluginId, Element pluginConfig,
        Map<QName, List<Element>> pluginConfigChildren, BeanDefinitionBuilder pluginBuilder,
        ParserContext parserContext) {
    boolean cacheResults = false;
    String cacheManagerId = "shibboleth.CacheManager";
    long cacheElementTtl = 4 * 60 * 60 * 1000;
    int maximumCachedElements = 500;

    List<Element> cacheConfigs = XMLHelper.getChildElementsByTagNameNS(pluginConfig,
            DataConnectorNamespaceHandler.NAMESPACE, "ResultCache");
    if (cacheConfigs != null && !cacheConfigs.isEmpty()) {
        Element cacheConfig = cacheConfigs.get(0);

        cacheResults = true;

        if (cacheConfig.hasAttributeNS(null, "cacheManagerRef")) {
            cacheManagerId = DatatypeHelper.safeTrim(cacheConfig.getAttributeNS(null, "cacheManagerRef"));
        }

        if (cacheConfig.hasAttributeNS(null, "elementTimeToLive")) {
            cacheElementTtl = SpringConfigurationUtils.parseDurationToMillis(
                    "elementTimeToLive on data connector " + pluginId,
                    cacheConfig.getAttributeNS(null, "elementTimeToLive"), 0);
        }

        if (cacheConfig.hasAttributeNS(null, "maximumCachedElements")) {
            maximumCachedElements = Integer.parseInt(
                    DatatypeHelper.safeTrim(cacheConfig.getAttributeNS(null, "maximumCachedElements")));
        }
    }

    if (pluginConfig.hasAttributeNS(null, "cacheResults")) {
        log.warn(
                "Data connection {}: use of 'cacheResults' attribute is deprecated.  Use <ResultCache> instead.",
                pluginId);
        cacheResults = XMLHelper
                .getAttributeValueAsBoolean(pluginConfig.getAttributeNodeNS(null, "cacheResults"));
    }

    if (cacheResults) {
        log.debug("Data connector {} is caching results: {}", pluginId, cacheResults);

        pluginBuilder.addPropertyReference("cacheManager", cacheManagerId);

        log.debug("Data connector {} cache element time to live: {}ms", pluginId, cacheElementTtl);
        pluginBuilder.addPropertyValue("cacheElementTimeToLive", cacheElementTtl);

        log.debug("Data connector {} maximum number of caches elements: {}", pluginId, maximumCachedElements);
        pluginBuilder.addPropertyValue("maximumCachedElements", maximumCachedElements);
    }

}

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

/**
* Get the available geo regions for this web space.
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations./*from  w w w.  j  a v a  2s  . co  m*/
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The List Geo Regions operation response.
*/
@Override
public WebSpacesListGeoRegionsResponse listGeoRegions()
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("properties=georegions");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

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

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

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

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

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

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

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

/**
* You can retrieve details for a specified web space name by issuing an
* HTTP GET request.  (see/*from www.j  av  a  2  s.  co m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @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 Web Space Details operation response.
*/
@Override
public WebSpacesGetResponse get(String webSpaceName)
        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);
        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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "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-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
        WebSpacesGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSpacesGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

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

                Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "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());
                        result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
                    }
                }

                Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "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());
                        result.setCurrentWorkerSize(currentWorkerSizeInstance);
                    }
                }

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

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

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

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

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

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

                Element workerSizeElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                if (workerSizeElement != null && workerSizeElement.getTextContent() != null
                        && !workerSizeElement.getTextContent().isEmpty()) {
                    WorkerSizeOptions workerSizeInstance;
                    workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement.getTextContent());
                    result.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.storage.StorageAccountOperationsImpl.java

/**
* The Check Name Availability operation checks if a storage account name is
* available for use in Azure.  (see//w  w  w.j a  v  a  2 s  .  c o m
* http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx for
* more information)
*
* @param accountName Required. The desired storage account name to check
* for availability.
* @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 to a storage account check name availability request.
*/
@Override
public CheckNameAvailabilityResponse checkNameAvailability(String accountName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // 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, "checkNameAvailabilityAsync", 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/operations/isavailable/";
    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
        CheckNameAvailabilityResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new CheckNameAvailabilityResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element availabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "AvailabilityResponse");
            if (availabilityResponseElement != null) {
                Element resultElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "Result");
                if (resultElement != null) {
                    boolean resultInstance;
                    resultInstance = DatatypeConverter
                            .parseBoolean(resultElement.getTextContent().toLowerCase());
                    result.setIsAvailable(resultInstance);
                }

                Element reasonElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "Reason");
                if (reasonElement != null) {
                    boolean isNil = false;
                    Attr nilAttribute = reasonElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute != null) {
                        isNil = "true".equals(nilAttribute.getValue());
                    }
                    if (isNil == false) {
                        String reasonInstance;
                        reasonInstance = reasonElement.getTextContent();
                        result.setReason(reasonInstance);
                    }
                }
            }

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