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.miz.apis.thetvdb.TheTVDbService.java

@Override
public List<String> getCovers(String id) {
    ArrayList<String> covers = new ArrayList<String>();

    try {//from   w ww  .  ja v a  2  s . c om
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + id + "/banners.xml");
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("Banners");
        if (nodeList.getLength() > 0) {
            Node firstNode = nodeList.item(0);
            if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element firstElement = (Element) firstNode;
                NodeList list, list2;
                Element element;

                list = firstElement.getChildNodes();
                list2 = firstElement.getChildNodes();
                nodeList = doc.getElementsByTagName("Banner");
                if (nodeList.getLength() > 0) {
                    try {
                        list = firstElement.getElementsByTagName("BannerType");
                        list2 = firstElement.getElementsByTagName("BannerPath");

                        for (int i = 0; i < list.getLength(); i++) {
                            element = (Element) list.item(i);
                            if (element.getTextContent().equals("poster"))
                                covers.add(
                                        "http://thetvdb.com/banners/_cache/" + list2.item(i).getTextContent());
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    } catch (Exception e) {
    }

    return covers;
}

From source file:com.miz.apis.thetvdb.TheTVDbService.java

@Override
public List<String> getBackdrops(String id) {
    ArrayList<String> backdrops = new ArrayList<String>();

    try {/*from   www  .  j a va2s. co m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + id + "/banners.xml");
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("Banners");
        if (nodeList.getLength() > 0) {

            Node firstNode = nodeList.item(0);

            if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element firstElement = (Element) firstNode;
                NodeList list, list2;
                Element element;

                list = firstElement.getChildNodes();
                list2 = firstElement.getChildNodes();
                nodeList = doc.getElementsByTagName("Banner");
                if (nodeList.getLength() > 0) {
                    try {
                        list = firstElement.getElementsByTagName("BannerType");
                        list2 = firstElement.getElementsByTagName("BannerPath");
                        for (int i = 0; i < list.getLength(); i++) {
                            element = (Element) list.item(i);
                            if (element.getTextContent().equals("fanart"))
                                backdrops.add(
                                        "http://thetvdb.com/banners/_cache/" + list2.item(i).getTextContent());
                        }
                    } catch (Exception e) {
                    } // No such tag
                }
            }
        }
    } catch (Exception e) {
    }

    return backdrops;
}

From source file:com.microsoft.windowsazure.management.network.ClientRootCertificateOperationsImpl.java

/**
* The List Client Root Certificates operation returns a list of all the
* client root certificates that are associated with the specified virtual
* network in Azure.  (see//from w w  w  .  ja v a 2  s.c o m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx for
* more information)
*
* @param networkName Required. The name of the virtual network for this
* gateway.
* @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 for the List Client Root Certificates operation.
*/
@Override
public ClientRootCertificateListResponse list(String networkName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (networkName == null) {
        throw new NullPointerException("networkName");
    }

    // 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("networkName", networkName);
        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/networking/";
    url = url + URLEncoder.encode(networkName, "UTF-8");
    url = url + "/gateway/clientrootcertificates";
    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("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2015-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
        ClientRootCertificateListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ClientRootCertificateListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element clientRootCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ClientRootCertificates");
            if (clientRootCertificatesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(clientRootCertificatesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ClientRootCertificate")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element clientRootCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(clientRootCertificatesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ClientRootCertificate")
                            .get(i1));
                    ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificateInstance = new ClientRootCertificateListResponse.ClientRootCertificate();
                    result.getClientRootCertificates().add(clientRootCertificateInstance);

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

                    Element subjectElement = XmlUtility.getElementByTagNameNS(clientRootCertificatesElement,
                            "http://schemas.microsoft.com/windowsazure", "Subject");
                    if (subjectElement != null) {
                        String subjectInstance;
                        subjectInstance = subjectElement.getTextContent();
                        clientRootCertificateInstance.setSubject(subjectInstance);
                    }

                    Element thumbprintElement = XmlUtility.getElementByTagNameNS(clientRootCertificatesElement,
                            "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                    if (thumbprintElement != null) {
                        String thumbprintInstance;
                        thumbprintInstance = thumbprintElement.getTextContent();
                        clientRootCertificateInstance.setThumbprint(thumbprintInstance);
                    }
                }
            }

        }
        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.prism.schema.DomToSchemaPostProcessor.java

private String getDefaultNamespace(XSType xsType) {
    Element annoElement = SchemaProcessorUtil.getAnnotationElement(xsType.getAnnotation(), A_DEFAULT_NAMESPACE);
    if (annoElement != null) {
        return annoElement.getTextContent();
    }//from   w  w w.j a  v a  2 s.c om
    if (xsType.getBaseType() != null && !xsType.getBaseType().equals(xsType)) {
        return getDefaultNamespace(xsType.getBaseType());
    }
    return null;
}

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

/**
 * @param appearanceElem/*from   w w w  . j  a  v a2  s  .c o  m*/
 * @param formField
 * @return
 */
private boolean isFieldChanged(Element appearanceElem, FormField formField) {
    String formFieldId = formField.getId();
    Element fieldElement = XmlUtils.findFirstElement("field[@id='" + formFieldId + "']", appearanceElem);
    if (fieldElement == null) {
        return true;
    }
    if (compareAttributeList(fieldElement, formField.getAttributes())) {
        return true;
    }
    Control control = formField.getControl();
    Element controlElement = XmlUtils.findFirstElement("control", fieldElement);
    if (compareObject(control, controlElement)) {
        return true;
    }

    if (control != null) {
        if (compareString(controlElement.getAttribute("template"), control.getTemplate())) {
            return true;
        }
        if (compareObject(control.getParams(), controlElement.getChildNodes())) {
            return true;
        }
        if (control.getParams() != null) {
            for (ControlParam param : control.getParams()) {
                Element paramElement = XmlUtils.findFirstElement("control[@name='" + param.getName() + "']",
                        controlElement);
                if (paramElement == null || compareString(paramElement.getTextContent(), param.getValue())) {
                    return true;
                }
            }
        }
    }

    Element constraintsElement = XmlUtils.findFirstElement("constraint-handlers", fieldElement);
    Map<String, ConstraintHandlerDefinition> constraints = formField.getConstraintDefinitionMap();

    if (compareObject(constraintsElement, constraints)) {
        return true;
    }

    if (constraints != null) {
        if (constraints.size() != constraintsElement.getChildNodes().getLength()) {
            return true;
        }

        for (String constraintId : constraints.keySet()) {
            ConstraintHandlerDefinition constraint = constraints.get(constraintId);
            Element constraintElement = XmlUtils
                    .findFirstElement("constraint[@type='" + constraint.getType() + "']", fieldElement);
            if (constraintElement == null) {
                return true;
            }
            if (compareString(constraintElement.getAttribute("event"), constraint.getEvent())
                    || compareString(constraintElement.getAttribute("message"), constraint.getMessage())
                    || compareString(constraintElement.getAttribute("message-id"), constraint.getMessageId())
                    || compareString(constraintElement.getAttribute("validation-handler"),
                            constraint.getValidationHandler())) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java

private PrismReferenceDefinition processObjectReferenceDefinition(XSType xsType, QName elementName,
        XSAnnotation annotation, ComplexTypeDefinition containingCtd, XSParticle elementParticle,
        boolean inherited) throws SchemaException {
    QName typeName = new QName(xsType.getTargetNamespace(), xsType.getName());
    QName primaryElementName = elementName;
    Element objRefAnnotationElement = SchemaProcessorUtil.getAnnotationElement(annotation, A_OBJECT_REFERENCE);
    boolean hasExplicitPrimaryElementName = (objRefAnnotationElement != null
            && !StringUtils.isEmpty(objRefAnnotationElement.getTextContent()));
    if (hasExplicitPrimaryElementName) {
        primaryElementName = DOMUtil.getQNameValue(objRefAnnotationElement);
    }/* w  w w . j  av a  2  s  .c o m*/
    PrismReferenceDefinition definition = null;
    if (containingCtd != null) {
        definition = containingCtd.findItemDefinition(primaryElementName, PrismReferenceDefinition.class);
    }
    if (definition == null) {
        SchemaDefinitionFactory definitionFactory = getDefinitionFactory();
        definition = definitionFactory.createReferenceDefinition(primaryElementName, typeName, containingCtd,
                prismContext, annotation, elementParticle);
        definition.setInherited(inherited);
        if (containingCtd != null) {
            containingCtd.add(definition);
        }
    }
    if (hasExplicitPrimaryElementName) {
        // The elements that have explicit type name determine the target type name (if not yet set)
        if (definition.getTargetTypeName() == null) {
            definition.setTargetTypeName(typeName);
        }
        if (definition.getCompositeObjectElementName() == null) {
            definition.setCompositeObjectElementName(elementName);
        }
    } else {
        // The elements that use default element names override type definition
        // as there can be only one such definition, therefore the behavior is deterministic
        definition.setTypeName(typeName);
    }
    Element targetTypeAnnotationElement = SchemaProcessorUtil.getAnnotationElement(annotation,
            A_OBJECT_REFERENCE_TARGET_TYPE);
    if (targetTypeAnnotationElement != null
            && !StringUtils.isEmpty(targetTypeAnnotationElement.getTextContent())) {
        // Explicit definition of target type overrides previous logic
        QName targetType = DOMUtil.getQNameValue(targetTypeAnnotationElement);
        definition.setTargetTypeName(targetType);
    }
    setMultiplicity(definition, elementParticle, annotation, false);
    Boolean composite = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, A_COMPOSITE);
    if (composite != null) {
        definition.setComposite(composite);
    }

    parseItemDefinitionAnnotations(definition, annotation);
    //        extractDocumentation(definition, annotation);
    return definition;
}

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

/**
* The Get Management Certificate operation retrieves information about the
* management certificate with the specified thumbprint. Management
* certificates, which are also known as subscription certificates,
* authenticate clients attempting to connect to resources associated with
* your Azure subscription.  (see// w  ww. j  a  v a  2 s .c  om
* http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx for
* more information)
*
* @param thumbprint Required. The thumbprint value of the certificate to
* retrieve information about.
* @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 Management Certificate operation response.
*/
@Override
public ManagementCertificateGetResponse get(String thumbprint)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (thumbprint == null) {
        throw new NullPointerException("thumbprint");
    }

    // 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("thumbprint", thumbprint);
        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 + "/certificates/";
    url = url + URLEncoder.encode(thumbprint, "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
        ManagementCertificateGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ManagementCertificateGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element subscriptionCertificateElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate");
            if (subscriptionCertificateElement != null) {
                Element subscriptionCertificatePublicKeyElement = XmlUtility.getElementByTagNameNS(
                        subscriptionCertificateElement, "http://schemas.microsoft.com/windowsazure",
                        "SubscriptionCertificatePublicKey");
                if (subscriptionCertificatePublicKeyElement != null) {
                    byte[] subscriptionCertificatePublicKeyInstance;
                    subscriptionCertificatePublicKeyInstance = subscriptionCertificatePublicKeyElement
                            .getTextContent() != null
                                    ? Base64.decode(subscriptionCertificatePublicKeyElement.getTextContent())
                                    : null;
                    result.setPublicKey(subscriptionCertificatePublicKeyInstance);
                }

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

                Element subscriptionCertificateDataElement = XmlUtility.getElementByTagNameNS(
                        subscriptionCertificateElement, "http://schemas.microsoft.com/windowsazure",
                        "SubscriptionCertificateData");
                if (subscriptionCertificateDataElement != null) {
                    byte[] subscriptionCertificateDataInstance;
                    subscriptionCertificateDataInstance = subscriptionCertificateDataElement
                            .getTextContent() != null
                                    ? Base64.decode(subscriptionCertificateDataElement.getTextContent())
                                    : null;
                    result.setData(subscriptionCertificateDataInstance);
                }

                Element createdElement = XmlUtility.getElementByTagNameNS(subscriptionCertificateElement,
                        "http://schemas.microsoft.com/windowsazure", "Created");
                if (createdElement != null) {
                    Calendar createdInstance;
                    createdInstance = DatatypeConverter.parseDateTime(createdElement.getTextContent());
                    result.setCreated(createdInstance);
                }
            }

        }
        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.compute.VirtualMachineExtensionOperationsImpl.java

/**
* The List Resource Extensions operation lists the resource extensions that
* are available to add to a Virtual Machine. In Azure, a process can run
* as a resource extension of a Virtual Machine. For example, Remote
* Desktop Access or the Azure Diagnostics Agent can run as resource
* extensions to the Virtual Machine.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx for
* more information)//w  w  w  . ja va  2 s.c  om
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The List Resource Extensions operation response.
*/
@Override
public VirtualMachineExtensionListResponse list()
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/resourceextensions";
    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", "2015-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
        VirtualMachineExtensionListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualMachineExtensionListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element resourceExtensionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ResourceExtensions");
            if (resourceExtensionsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element resourceExtensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                            .get(i1));
                    VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension();
                    result.getResourceExtensions().add(resourceExtensionInstance);

                    Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Publisher");
                    if (publisherElement != null) {
                        String publisherInstance;
                        publisherInstance = publisherElement.getTextContent();
                        resourceExtensionInstance.setPublisher(publisherInstance);
                    }

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

                    Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Version");
                    if (versionElement != null) {
                        String versionInstance;
                        versionInstance = versionElement.getTextContent();
                        resourceExtensionInstance.setVersion(versionInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent();
                        resourceExtensionInstance.setLabel(labelInstance);
                    }

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

                    Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PublicConfigurationSchema");
                    if (publicConfigurationSchemaElement != null) {
                        String publicConfigurationSchemaInstance;
                        publicConfigurationSchemaInstance = publicConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(publicConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPublicConfigurationSchema(publicConfigurationSchemaInstance);
                    }

                    Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PrivateConfigurationSchema");
                    if (privateConfigurationSchemaElement != null) {
                        String privateConfigurationSchemaInstance;
                        privateConfigurationSchemaInstance = privateConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(privateConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPrivateConfigurationSchema(privateConfigurationSchemaInstance);
                    }

                    Element sampleConfigElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SampleConfig");
                    if (sampleConfigElement != null) {
                        String sampleConfigInstance;
                        sampleConfigInstance = sampleConfigElement.getTextContent() != null
                                ? new String(Base64.decode(sampleConfigElement.getTextContent()))
                                : null;
                        resourceExtensionInstance.setSampleConfig(sampleConfigInstance);
                    }

                    Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "ReplicationCompleted");
                    if (replicationCompletedElement != null
                            && replicationCompletedElement.getTextContent() != null
                            && !replicationCompletedElement.getTextContent().isEmpty()) {
                        boolean replicationCompletedInstance;
                        replicationCompletedInstance = DatatypeConverter
                                .parseBoolean(replicationCompletedElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setReplicationCompleted(replicationCompletedInstance);
                    }

                    Element eulaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement != null) {
                        URI eulaInstance;
                        eulaInstance = new URI(eulaElement.getTextContent());
                        resourceExtensionInstance.setEula(eulaInstance);
                    }

                    Element privacyUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement.getTextContent());
                        resourceExtensionInstance.setPrivacyUri(privacyUriInstance);
                    }

                    Element homepageUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "HomepageUri");
                    if (homepageUriElement != null) {
                        URI homepageUriInstance;
                        homepageUriInstance = new URI(homepageUriElement.getTextContent());
                        resourceExtensionInstance.setHomepageUri(homepageUriInstance);
                    }

                    Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsJsonExtension");
                    if (isJsonExtensionElement != null && isJsonExtensionElement.getTextContent() != null
                            && !isJsonExtensionElement.getTextContent().isEmpty()) {
                        boolean isJsonExtensionInstance;
                        isJsonExtensionInstance = DatatypeConverter
                                .parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsJsonExtension(isJsonExtensionInstance);
                    }

                    Element isInternalExtensionElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "IsInternalExtension");
                    if (isInternalExtensionElement != null
                            && isInternalExtensionElement.getTextContent() != null
                            && !isInternalExtensionElement.getTextContent().isEmpty()) {
                        boolean isInternalExtensionInstance;
                        isInternalExtensionInstance = DatatypeConverter
                                .parseBoolean(isInternalExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsInternalExtension(isInternalExtensionInstance);
                    }

                    Element disallowMajorVersionUpgradeElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "DisallowMajorVersionUpgrade");
                    if (disallowMajorVersionUpgradeElement != null
                            && disallowMajorVersionUpgradeElement.getTextContent() != null
                            && !disallowMajorVersionUpgradeElement.getTextContent().isEmpty()) {
                        boolean disallowMajorVersionUpgradeInstance;
                        disallowMajorVersionUpgradeInstance = DatatypeConverter.parseBoolean(
                                disallowMajorVersionUpgradeElement.getTextContent().toLowerCase());
                        resourceExtensionInstance
                                .setDisallowMajorVersionUpgrade(disallowMajorVersionUpgradeInstance);
                    }

                    Element supportedOSElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SupportedOS");
                    if (supportedOSElement != null) {
                        String supportedOSInstance;
                        supportedOSInstance = supportedOSElement.getTextContent();
                        resourceExtensionInstance.setSupportedOS(supportedOSInstance);
                    }

                    Element companyNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "CompanyName");
                    if (companyNameElement != null) {
                        String companyNameInstance;
                        companyNameInstance = companyNameElement.getTextContent();
                        resourceExtensionInstance.setCompanyName(companyNameInstance);
                    }

                    Element publishedDateElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement != null && publishedDateElement.getTextContent() != null
                            && !publishedDateElement.getTextContent().isEmpty()) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement.getTextContent());
                        resourceExtensionInstance.setPublishedDate(publishedDateInstance);
                    }

                    Element regionsElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Regions");
                    if (regionsElement != null) {
                        String regionsInstance;
                        regionsInstance = regionsElement.getTextContent();
                        resourceExtensionInstance.setRegions(regionsInstance);
                    }
                }
            }

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

/**
* Returns information about a specific operation by using the operation
* Guid.//from  w w w  .  j a v a  2  s .  c o  m
*
* @param serverName Required. The name of the Azure SQL Database Server
* where the database is hosted.
* @param operationGuid Required. The Guid of the Azure SQL Database
* operation to be obtained.
* @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 Represents the database operation for a given operation Guid.
*/
@Override
public DatabaseOperationGetResponse get(String serverName, String operationGuid)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (operationGuid == null) {
        throw new NullPointerException("operationGuid");
    }

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

    // Construct URL
    String 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 + "/databaseoperations/";
    url = url + URLEncoder.encode(operationGuid, "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", "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
        DatabaseOperationGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseOperationGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

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

                Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "Id");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    serviceResourceInstance.setId(idInstance);
                }

                Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "StateId");
                if (stateIdElement != null) {
                    int stateIdInstance;
                    stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent());
                    serviceResourceInstance.setStateId(stateIdInstance);
                }

                Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "SessionActivityId");
                if (sessionActivityIdElement != null) {
                    String sessionActivityIdInstance;
                    sessionActivityIdInstance = sessionActivityIdElement.getTextContent();
                    serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance);
                }

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

                Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "PercentComplete");
                if (percentCompleteElement != null) {
                    int percentCompleteInstance;
                    percentCompleteInstance = DatatypeConverter
                            .parseInt(percentCompleteElement.getTextContent());
                    serviceResourceInstance.setPercentComplete(percentCompleteInstance);
                }

                Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "ErrorCode");
                if (errorCodeElement != null) {
                    int errorCodeInstance;
                    errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent());
                    serviceResourceInstance.setErrorCode(errorCodeInstance);
                }

                Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "Error");
                if (errorElement != null) {
                    String errorInstance;
                    errorInstance = errorElement.getTextContent();
                    serviceResourceInstance.setError(errorInstance);
                }

                Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "ErrorSeverity");
                if (errorSeverityElement != null) {
                    int errorSeverityInstance;
                    errorSeverityInstance = DatatypeConverter.parseInt(errorSeverityElement.getTextContent());
                    serviceResourceInstance.setErrorSeverity(errorSeverityInstance);
                }

                Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "ErrorState");
                if (errorStateElement != null) {
                    int errorStateInstance;
                    errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent());
                    serviceResourceInstance.setErrorState(errorStateInstance);
                }

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

                Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "LastModifyTime");
                if (lastModifyTimeElement != null) {
                    Calendar lastModifyTimeInstance;
                    lastModifyTimeInstance = DatatypeConverter
                            .parseDateTime(lastModifyTimeElement.getTextContent());
                    serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance);
                }

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

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

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "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.prism.schema.DomToSchemaPostProcessor.java

private void setMultiplicity(ItemDefinition itemDef, XSParticle particle, XSAnnotation annotation,
        boolean topLevel) {
    if (topLevel || particle == null) {
        ((ItemDefinitionImpl) itemDef).setMinOccurs(0);
        Element maxOccursAnnotation = SchemaProcessorUtil.getAnnotationElement(annotation, A_MAX_OCCURS);
        if (maxOccursAnnotation != null) {
            String maxOccursString = maxOccursAnnotation.getTextContent();
            int maxOccurs = XsdTypeMapper.multiplicityToInteger(maxOccursString);
            ((ItemDefinitionImpl) itemDef).setMaxOccurs(maxOccurs);
        } else {//  w w w .  j  a  v  a 2  s .  c  om
            ((ItemDefinitionImpl) itemDef).setMaxOccurs(-1);
        }
    } else {
        // itemDef.setMinOccurs(particle.getMinOccurs());
        // itemDef.setMaxOccurs(particle.getMaxOccurs());
        ((ItemDefinitionImpl) itemDef).setMinOccurs(particle.getMinOccurs().intValue());
        ((ItemDefinitionImpl) itemDef).setMaxOccurs(particle.getMaxOccurs().intValue());
    }
}