Example usage for org.w3c.dom Element getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

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

Usage

From source file:com.kaltura.client.KalturaClientBase.java

public KalturaMultiResponse doMultiRequest() throws KalturaApiException {
    Element multiRequestResult = doQueue();

    KalturaMultiResponse multiResponse = new KalturaMultiResponse();

    for (int i = 0; i < multiRequestResult.getChildNodes().getLength(); i++) {
        Element arrayNode = (Element) multiRequestResult.getChildNodes().item(i);

        try {//  w w w  .  ja v a  2 s  .  c om
            KalturaApiException exception = getExceptionOnAPIError(arrayNode);
            if (exception != null) {
                multiResponse.add(exception);
            } else if (getElementByXPath(arrayNode, "objectType") != null) {
                multiResponse.add(KalturaObjectFactory.create(arrayNode, requestReturnType.get(i)));
            } else if (getElementByXPath(arrayNode, "item/objectType") != null) {
                multiResponse.add(ParseUtils.parseArray(requestReturnType.get(i), arrayNode));
            } else {
                multiResponse.add(arrayNode.getTextContent());
            }
        } catch (KalturaApiException e) {
            multiResponse.add(e);
        }
    }

    // Cleanup
    this.requestReturnType = null;
    return multiResponse;
}

From source file:com.borhan.client.BorhanClientBase.java

public BorhanMultiResponse doMultiRequest() throws BorhanApiException {
    Element multiRequestResult = doQueue();

    BorhanMultiResponse multiResponse = new BorhanMultiResponse();

    for (int i = 0; i < multiRequestResult.getChildNodes().getLength(); i++) {
        Element arrayNode = (Element) multiRequestResult.getChildNodes().item(i);

        try {/*w  ww . j  a  v  a  2  s .c  o m*/
            BorhanApiException exception = getExceptionOnAPIError(arrayNode);
            if (exception != null) {
                multiResponse.add(exception);
            } else if (getElementByXPath(arrayNode, "objectType") != null) {
                multiResponse.add(BorhanObjectFactory.create(arrayNode, requestReturnType.get(i)));
            } else if (getElementByXPath(arrayNode, "item/objectType") != null) {
                multiResponse.add(ParseUtils.parseArray(requestReturnType.get(i), arrayNode));
            } else {
                multiResponse.add(arrayNode.getTextContent());
            }
        } catch (BorhanApiException e) {
            multiResponse.add(e);
        }
    }

    // Cleanup
    this.requestReturnType = null;
    return multiResponse;
}

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

/**
* Returns a list of server-level Firewall Rules for an Azure SQL Database
* Server./*from w  w w.ja  v a  2s.c o  m*/
*
* @param serverName Required. The name of the Azure SQL Database Server
* from which to list the Firewall Rules.
* @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 from a request to List Firewall Rules.
*/
@Override
public FirewallRuleListResponse list(String serverName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/firewallrules";
    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
        FirewallRuleListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new FirewallRuleListResponse();
            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));
                    FirewallRule serviceResourceInstance = new FirewallRule();
                    result.getFirewallRules().add(serviceResourceInstance);

                    Element startIPAddressElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                    if (startIPAddressElement != null) {
                        InetAddress startIPAddressInstance;
                        startIPAddressInstance = InetAddress.getByName(startIPAddressElement.getTextContent());
                        serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                    }

                    Element endIPAddressElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                    if (endIPAddressElement != null) {
                        InetAddress endIPAddressInstance;
                        endIPAddressInstance = InetAddress.getByName(endIPAddressElement.getTextContent());
                        serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                    }

                    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.evolveum.midpoint.testing.model.client.sample.AbstractTestForExchangeConnector.java

protected void dumpAttributes(ShadowType shadowType) {
    ShadowAttributesType attributes = shadowType.getAttributes();
    System.out.println("Attributes for " + shadowType.getObjectClass().getLocalPart() + " "
            + getOrig(shadowType.getName()) + " {" + attributes.getAny().size() + " entries):");
    for (Object item : attributes.getAny()) {
        if (item instanceof Element) {
            Element e = (Element) item;
            System.out.println(" - " + e.getLocalName() + ": " + e.getTextContent());
        } else if (item instanceof JAXBElement) {
            JAXBElement je = (JAXBElement) item;
            String typeInfo = je.getValue() instanceof String ? ""
                    : (" (" + je.getValue().getClass().getSimpleName() + ")");
            System.out.println(" - " + je.getName().getLocalPart() + ": " + je.getValue() + typeInfo);
        } else {//from   w  w  w  .ja  v a  2s .  c  o  m
            System.out.println(" - " + item);
        }
    }
}

From source file:com.microsoft.windowsazure.management.SubscriptionOperationsImpl.java

/**
* The List Subscription Operations operation returns a list of create,
* update, and delete operations that were performed on a subscription
* during the specified timeframe.  (see// w  ww  .  j a v  a 2s. com
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the List Subscription
* Operations 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 List Subscription Operations operation response.
*/
@Override
public SubscriptionListOperationsResponse listOperations(SubscriptionListOperationsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "listOperationsAsync", 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 + "/operations";
    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("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"));
    queryParameters.add("EndTime="
            + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
    if (parameters.getObjectIdFilter() != null) {
        queryParameters.add("ObjectIdFilter=" + URLEncoder.encode(parameters.getObjectIdFilter(), "UTF-8"));
    }
    if (parameters.getOperationStatus() != null) {
        queryParameters.add("OperationResultFilter="
                + URLEncoder.encode(parameters.getOperationStatus().toString(), "UTF-8"));
    }
    if (parameters.getContinuationToken() != null) {
        queryParameters
                .add("ContinuationToken=" + URLEncoder.encode(parameters.getContinuationToken(), "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-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
        SubscriptionListOperationsResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new SubscriptionListOperationsResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element subscriptionOperationCollectionElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "SubscriptionOperationCollection");
            if (subscriptionOperationCollectionElement != null) {
                Element continuationTokenElement = XmlUtility.getElementByTagNameNS(
                        subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure",
                        "ContinuationToken");
                if (continuationTokenElement != null) {
                    String continuationTokenInstance;
                    continuationTokenInstance = continuationTokenElement.getTextContent();
                    result.setContinuationToken(continuationTokenInstance);
                }

                Element subscriptionOperationsSequenceElement = XmlUtility.getElementByTagNameNS(
                        subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure",
                        "SubscriptionOperations");
                if (subscriptionOperationsSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(subscriptionOperationsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element subscriptionOperationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(subscriptionOperationsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation")
                                .get(i1));
                        SubscriptionListOperationsResponse.SubscriptionOperation subscriptionOperationInstance = new SubscriptionListOperationsResponse.SubscriptionOperation();
                        result.getSubscriptionOperations().add(subscriptionOperationInstance);

                        Element operationIdElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationId");
                        if (operationIdElement != null) {
                            String operationIdInstance;
                            operationIdInstance = operationIdElement.getTextContent();
                            subscriptionOperationInstance.setOperationId(operationIdInstance);
                        }

                        Element operationObjectIdElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationObjectId");
                        if (operationObjectIdElement != null) {
                            String operationObjectIdInstance;
                            operationObjectIdInstance = operationObjectIdElement.getTextContent();
                            subscriptionOperationInstance.setOperationObjectId(operationObjectIdInstance);
                        }

                        Element operationNameElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationName");
                        if (operationNameElement != null) {
                            String operationNameInstance;
                            operationNameInstance = operationNameElement.getTextContent();
                            subscriptionOperationInstance.setOperationName(operationNameInstance);
                        }

                        Element operationParametersSequenceElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationParameters");
                        if (operationParametersSequenceElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(operationParametersSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "OperationParameter")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element operationParametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(operationParametersSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure",
                                                "OperationParameter")
                                        .get(i2));
                                String operationParametersKey = XmlUtility.getElementByTagNameNS(
                                        operationParametersElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement",
                                        "Name").getTextContent();
                                String operationParametersValue = XmlUtility.getElementByTagNameNS(
                                        operationParametersElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement",
                                        "Value").getTextContent();
                                subscriptionOperationInstance.getOperationParameters()
                                        .put(operationParametersKey, operationParametersValue);
                            }
                        }

                        Element operationCallerElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationCaller");
                        if (operationCallerElement != null) {
                            SubscriptionListOperationsResponse.OperationCallerDetails operationCallerInstance = new SubscriptionListOperationsResponse.OperationCallerDetails();
                            subscriptionOperationInstance.setOperationCaller(operationCallerInstance);

                            Element usedServiceManagementApiElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "UsedServiceManagementApi");
                            if (usedServiceManagementApiElement != null) {
                                boolean usedServiceManagementApiInstance;
                                usedServiceManagementApiInstance = DatatypeConverter.parseBoolean(
                                        usedServiceManagementApiElement.getTextContent().toLowerCase());
                                operationCallerInstance
                                        .setUsedServiceManagementApi(usedServiceManagementApiInstance);
                            }

                            Element userEmailAddressElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "UserEmailAddress");
                            if (userEmailAddressElement != null) {
                                String userEmailAddressInstance;
                                userEmailAddressInstance = userEmailAddressElement.getTextContent();
                                operationCallerInstance.setUserEmailAddress(userEmailAddressInstance);
                            }

                            Element subscriptionCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "SubscriptionCertificateThumbprint");
                            if (subscriptionCertificateThumbprintElement != null) {
                                String subscriptionCertificateThumbprintInstance;
                                subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement
                                        .getTextContent();
                                operationCallerInstance.setSubscriptionCertificateThumbprint(
                                        subscriptionCertificateThumbprintInstance);
                            }

                            Element clientIPElement = XmlUtility.getElementByTagNameNS(operationCallerElement,
                                    "http://schemas.microsoft.com/windowsazure", "ClientIP");
                            if (clientIPElement != null) {
                                InetAddress clientIPInstance;
                                clientIPInstance = InetAddress.getByName(clientIPElement.getTextContent());
                                operationCallerInstance.setClientIPAddress(clientIPInstance);
                            }
                        }

                        Element operationStatusElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationStatus");
                        if (operationStatusElement != null) {
                            String operationStatusInstance;
                            operationStatusInstance = operationStatusElement.getTextContent();
                            subscriptionOperationInstance.setOperationStatus(operationStatusInstance);
                        }

                        Element operationStartedTimeElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationStartedTime");
                        if (operationStartedTimeElement != null) {
                            Calendar operationStartedTimeInstance;
                            operationStartedTimeInstance = DatatypeConverter
                                    .parseDateTime(operationStartedTimeElement.getTextContent());
                            subscriptionOperationInstance.setOperationStartedTime(operationStartedTimeInstance);
                        }

                        Element operationCompletedTimeElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationCompletedTime");
                        if (operationCompletedTimeElement != null) {
                            Calendar operationCompletedTimeInstance;
                            operationCompletedTimeInstance = DatatypeConverter
                                    .parseDateTime(operationCompletedTimeElement.getTextContent());
                            subscriptionOperationInstance
                                    .setOperationCompletedTime(operationCompletedTimeInstance);
                        }
                    }
                }
            }

        }
        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.bluexml.xforms.controller.mapping.MappingToolFormsToAlfresco.java

/**
 * Collect fields. //$$ TRACE LOG/*from w w w.  ja  v a 2 s  . c  o m*/
 * 
 * @param formName
 *            the name of the current form, used for messages.
 * @param rootElt
 *            the root element of the instance
 * @param formType
 *            the form type
 * @param classType
 *            the class type
 * @param alfClass
 *            the GenericClass to be filled
 * @param isMassTagging
 *            if <code>true</code>, only fields that have a value will end in the GenericClass
 */
private void collectFields(String formName, Element rootElt, List<FormFieldType> fields, GenericClass alfClass,
        Map<String, String> initParams, boolean isMassTagging) {
    for (FormFieldType fieldType : fields) {
        String uniqueName = fieldType.getUniqueName();
        String alfrescoName = fieldType.getAlfrescoName();
        Element fieldElement = DOMUtil.getChild(rootElt, uniqueName);
        if (fieldElement == null) {
            throw new RuntimeException("No DOM element was found in the instance for field: " + uniqueName
                    + "' (" + alfrescoName + "). Probably another form has the same id as this one ('"
                    + formName + "') or there's a bug in the XForms engine.");
        }

        // whether the attribute will make it into the genericClass object
        boolean gotValue = false;
        //
        GenericAttribute attribute = alfrescoObjectFactory.createGenericAttribute();
        attribute.setQualifiedName(alfrescoName);
        String type = fieldType.getType();
        String inputTextContent = fieldElement.getTextContent();
        boolean readOnly = isReadOnly(fieldType);
        if (loggertrace.isTraceEnabled()) {
            logger.debug("Received value '" + inputTextContent + "' for attribute '" + alfrescoName
                    + "' with type '" + type + "'. Read-only status '" + readOnly + "'. isFileField: "
                    + (fieldType instanceof FileFieldType) + " . isServletRequest: N/A");
        }

        //
        // convert the XForms field value to an attribute (possibly multiple) value
        if (isMultiple(fieldType)) {
            gotValue = convertXformsMultipleAttributeToAlfresco(attribute, inputTextContent, fieldElement, type,
                    fieldType.getStaticEnumType(), initParams, isMassTagging);
        } else {
            if ((isMassTagging == false)
                    || (isMassTagging && (StringUtils.trimToNull(inputTextContent) != null))) {
                String alfrescoValue = null;
                // if applicable, take the user format into account
                if (isAmendable(type, isReadOnly(fieldType), false)) {
                    inputTextContent = getReadOnlyDateOrTimeModifiedValue(type, inputTextContent);
                }
                if (type.equals("DateTime")) {
                    String date;
                    String time;
                    if (readOnly) {
                        date = extractDateFromDateTimeModified(inputTextContent);
                        time = extractTimeFromDateTimeModified(inputTextContent);
                    } else {
                        date = DOMUtil.getChild(fieldElement, "date").getTextContent();
                        time = DOMUtil.getChild(fieldElement, "time").getTextContent();
                    }
                    alfrescoValue = getDateTimeFromDateAndTime(date, time);
                } else if (isSearchEnum(fieldType)) {
                    alfrescoValue = DOMUtil.getChild(fieldElement, MsgId.INT_INSTANCE_SIDEID.getText())
                            .getTextContent();
                } else if (isSelectionCapable(fieldType)) {
                    alfrescoValue = DOMUtil
                            .getElementInDescentByName(fieldElement, MsgId.INT_INSTANCE_SIDEID.getText())
                            .getTextContent();
                } else {
                    alfrescoValue = convertXformsAttributeToAlfresco(inputTextContent, type,
                            fieldType.getStaticEnumType(), initParams, isMassTagging);
                }
                ValueType valueType = alfrescoObjectFactory.createValueType();
                valueType.setValue(alfrescoValue);
                attribute.getValue().add(valueType);
                gotValue = true;
            }
        }
        //
        // mark FileFields with their destination. Useful for the webscript and for the upload
        // processing by the controller.
        if ((fieldType instanceof FileFieldType) && (isMassTagging == false)) {
            FileFieldType fileField = (FileFieldType) fieldType;
            String destination = isInRepository(fileField) ? MsgId.INT_UPLOAD_DEST_REPO.getText()
                    : MsgId.INT_UPLOAD_DEST_FILE.getText();
            attribute.setUploadTo(destination);

            // we need a name for the node (in case of upload to the repository)
            ValueType valueTypeNameAndExt = alfrescoObjectFactory.createValueType();
            String nameAndExt = fieldElement.getAttribute("file");
            valueTypeNameAndExt.setValue(nameAndExt);
            attribute.getValue().add(valueTypeNameAndExt);

            // we also want the MIME type; not needed but it won't hurt
            ValueType valueTypeMIME = alfrescoObjectFactory.createValueType();
            String mimetype = fieldElement.getAttribute("type");
            valueTypeMIME.setValue(mimetype);
            attribute.getValue().add(valueTypeMIME);
        }

        if ((isMassTagging == false) || (isMassTagging && gotValue)) {
            alfClass.getAttributes().getAttribute().add(attribute);
        }
    }

    // if applicable, append the implicit attribute that will keep info about the node content
    Element nodeContentElt = DOMUtil.getChild(rootElt, MsgId.INT_INSTANCE_SIDE_NODE_CONTENT.getText());
    if ((isMassTagging == false) && (nodeContentElt != null)) {
        GenericAttribute contentAttr = alfrescoObjectFactory.createGenericAttribute();
        contentAttr.setQualifiedName(MsgId.INT_INSTANCE_SIDE_NODE_CONTENT.getText());
        contentAttr.setSkipMe("true"); // <-- this is MANDATORY!

        ValueType pathValue = alfrescoObjectFactory.createValueType();
        ValueType nameValue = alfrescoObjectFactory.createValueType();
        ValueType mimeValue = alfrescoObjectFactory.createValueType();

        String path = nodeContentElt.getTextContent();
        pathValue.setValue(path);

        String nameAndExt = nodeContentElt.getAttribute("file");
        nameValue.setValue(nameAndExt);

        String mimetype = nodeContentElt.getAttribute("type");
        mimeValue.setValue(mimetype);

        contentAttr.getValue().add(pathValue);
        contentAttr.getValue().add(nameValue);
        contentAttr.getValue().add(mimeValue);

        // append the attribute for content
        alfClass.getAttributes().getAttribute().add(contentAttr);
    }
}

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

/**
* Adds a new server-level Firewall Rule for an Azure SQL Database Server.
*
* @param serverName Required. The name of the Azure SQL Database Server to
* which this rule will be applied./*  ww w .ja va2s . co  m*/
* @param parameters Required. The parameters for the Create Firewall Rule
* operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Contains the response to a Create Firewall Rule operation.
*/
@Override
public FirewallRuleCreateResponse create(String serverName, FirewallRuleCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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, "createAsync", 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 + "/firewallrules";
    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 serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceResource");
    requestDoc.appendChild(serviceResourceElement);

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

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

    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_CREATED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

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

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

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

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

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

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

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

From source file:com.microsoft.windowsazure.management.AffinityGroupOperationsImpl.java

/**
* The List Affinity Groups operation lists the affinity groups associated
* with the specified subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for
* more information)// www . jav  a  2s  . c o  m
*
* @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 Affinity Groups operation response.
*/
@Override
public AffinityGroupListResponse 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 + "/affinitygroups";
    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
        AffinityGroupListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new AffinityGroupListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element affinityGroupsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "AffinityGroups");
            if (affinityGroupsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(affinityGroupsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "AffinityGroup")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element affinityGroupsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(affinityGroupsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "AffinityGroup")
                            .get(i1));
                    AffinityGroupListResponse.AffinityGroup affinityGroupInstance = new AffinityGroupListResponse.AffinityGroup();
                    result.getAffinityGroups().add(affinityGroupInstance);

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

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

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

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

                    Element capabilitiesSequenceElement = XmlUtility.getElementByTagNameNS(
                            affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Capabilities");
                    if (capabilitiesSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(capabilitiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Capability")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element capabilitiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(capabilitiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Capability")
                                    .get(i2));
                            affinityGroupInstance.getCapabilities().add(capabilitiesElement.getTextContent());
                        }
                    }

                    Element createdTimeElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                            "http://schemas.microsoft.com/windowsazure", "CreatedTime");
                    if (createdTimeElement != null && createdTimeElement.getTextContent() != null
                            && !createdTimeElement.getTextContent().isEmpty()) {
                        Calendar createdTimeInstance;
                        createdTimeInstance = DatatypeConverter
                                .parseDateTime(createdTimeElement.getTextContent());
                        affinityGroupInstance.setCreatedTime(createdTimeInstance);
                    }

                    Element computeCapabilitiesElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                            "http://schemas.microsoft.com/windowsazure", "ComputeCapabilities");
                    if (computeCapabilitiesElement != null) {
                        ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities();
                        affinityGroupInstance.setComputeCapabilities(computeCapabilitiesInstance);

                        Element virtualMachinesRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                "VirtualMachinesRoleSizes");
                        if (virtualMachinesRoleSizesSequenceElement != null) {
                            for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                    .size(); i3 = i3 + 1) {
                                org.w3c.dom.Element virtualMachinesRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .get(i3));
                                computeCapabilitiesInstance.getVirtualMachinesRoleSizes()
                                        .add(virtualMachinesRoleSizesElement.getTextContent());
                            }
                        }

                        Element webWorkerRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                "WebWorkerRoleSizes");
                        if (webWorkerRoleSizesSequenceElement != null) {
                            for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                    .size(); i4 = i4 + 1) {
                                org.w3c.dom.Element webWorkerRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .get(i4));
                                computeCapabilitiesInstance.getWebWorkerRoleSizes()
                                        .add(webWorkerRoleSizesElement.getTextContent());
                            }
                        }
                    }
                }
            }

        }
        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.FirewallRuleOperationsImpl.java

/**
* Updates an existing server-level Firewall Rule for an Azure SQL Database
* Server.//  ww w. j  ava 2 s .  com
*
* @param serverName Required. The name of the Azure SQL Database Server
* that has the Firewall Rule to be updated.
* @param ruleName Required. The name of the Firewall Rule to be updated.
* @param parameters Required. The parameters for the Update Firewall Rule
* operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the firewall rule update response.
*/
@Override
public FirewallRuleUpdateResponse update(String serverName, String ruleName,
        FirewallRuleUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (ruleName == null) {
        throw new NullPointerException("ruleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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("ruleName", ruleName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
    }

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

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

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

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

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

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

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

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

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

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

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

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

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

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

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