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.wwpass.connection.WWPassConnection.java

private static InputStream getReplyData(final InputStream rawXMLInput)
        throws IOException, WWPassProtocolException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom;/*  w w  w.j av a 2 s . c  om*/
    InputStream is = null;

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        is = rawXMLInput;

        dom = db.parse(is);

        Element docEle = dom.getDocumentElement();

        Node result = docEle.getElementsByTagName("result").item(0);
        boolean res = result.getTextContent().equalsIgnoreCase("true");

        Element data = (Element) docEle.getElementsByTagName("data").item(0);
        String encoding = data.getAttributes().getNamedItem("encoding").getTextContent();
        String strData;
        byte[] bb;
        if ("base64".equalsIgnoreCase(encoding)) {
            bb = (new Base64()).decode(data.getTextContent());
            strData = new String(bb, Charset.forName("UTF-8"));
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(bb);
        } else {
            strData = data.getTextContent();
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(strData.getBytes());
        }

    } catch (ParserConfigurationException pce) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + pce.getMessage());
    } catch (SAXException se) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + se.getMessage());
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.fujitsu.dc.test.jersey.cell.auth.ImplicitFlowTest.java

static void checkHtmlBody(DcResponse res, String messageId, String dataCellName, String dcOwner) {
        DOMParser parser = new DOMParser();
        InputSource body = null;/*from   w w  w . ja v  a  2 s.  com*/
        body = new InputSource(res.bodyAsStream());
        try {
            parser.parse(body);
        } catch (SAXException e) {
            fail(e.getMessage());
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Document document = parser.getDocument();
        NodeList nodeList = document.getElementsByTagName("script");
        assertEquals(AuthResourceUtils.getJavascript("ajax.js"), ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("title");
        assertEquals(DcCoreMessageUtils.getMessage("PS-AU-0001"), ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("body");
        String expectedAppUrl = UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1) + "__/profile.json";
        String expectedDataUrl = UrlUtils.cellRoot(dataCellName) + "__/profile.json";
        assertEquals("requestFile('GET', '" + expectedAppUrl + "' , '" + expectedDataUrl + "' ,true )",
                ((Element) nodeList.item(0)).getAttribute("onload"));

        nodeList = document.getElementsByTagName("h1");
        assertEquals(DcCoreMessageUtils.getMessage("PS-AU-0001"), ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("form");
        String expectedFormUrl = UrlUtils.cellRoot(dataCellName) + "__authz";
        assertEquals(expectedFormUrl, ((Element) nodeList.item(0)).getAttribute("action"));

        nodeList = document.getElementsByTagName("div");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            String id = element.getAttribute("id");
            if ("message".equals(id)) {
                assertEquals(DcCoreMessageUtils.getMessage(messageId).replaceAll("<br />", ""),
                        element.getTextContent());
            }
        }

        nodeList = document.getElementsByTagName("input");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            String id = element.getAttribute("id");
            if ("state".equals(id)) {
                assertEquals(DEFAULT_STATE, element.getAttribute("value"));
            } else if ("dc_target".equals(id)) {
                assertEquals("", element.getAttribute("value"));

            } else if ("dc_owner".equals(id)) {
                assertEquals(dcOwner, element.getAttribute("value"));
            } else if ("client_id".equals(id)) {
                assertEquals(UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1), element.getAttribute("value"));
            } else if ("redirect_uri".equals(id)) {
                assertEquals(UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1) + REDIRECT_HTML,
                        element.getAttribute("value"));
            }
        }
    }

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

/**
* Issues a recovery request for an Azure SQL Database.
*
* @param sourceServerName Required. The name of the Azure SQL Database
* Server on which the database was hosted.
* @param parameters Required. Additional parameters for the Create Recover
* Database Operation request./*from  ww w.j a  v  a2  s.c o  m*/
* @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 the Create Recover Database Operation
* request.
*/
@Override
public RecoverDatabaseOperationCreateResponse create(String sourceServerName,
        RecoverDatabaseOperationCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (sourceServerName == null) {
        throw new NullPointerException("sourceServerName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getSourceDatabaseName() == null) {
        throw new NullPointerException("parameters.SourceDatabaseName");
    }

    // 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("sourceServerName", sourceServerName);
        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(sourceServerName, "UTF-8");
    url = url + "/recoverdatabaseoperations";
    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 sourceDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "SourceDatabaseName");
    sourceDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getSourceDatabaseName()));
    serviceResourceElement.appendChild(sourceDatabaseNameElement);

    if (parameters.getTargetServerName() != null) {
        Element targetServerNameElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetServerName");
        targetServerNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetServerName()));
        serviceResourceElement.appendChild(targetServerNameElement);
    }

    if (parameters.getTargetDatabaseName() != null) {
        Element targetDatabaseNameElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetDatabaseName");
        targetDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetDatabaseName()));
        serviceResourceElement.appendChild(targetDatabaseNameElement);
    }

    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
        RecoverDatabaseOperationCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new RecoverDatabaseOperationCreateResponse();
            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) {
                RecoverDatabaseOperation serviceResourceInstance = new RecoverDatabaseOperation();
                result.setOperation(serviceResourceInstance);

                Element requestIDElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "RequestID");
                if (requestIDElement != null) {
                    String requestIDInstance;
                    requestIDInstance = requestIDElement.getTextContent();
                    serviceResourceInstance.setId(requestIDInstance);
                }

                Element sourceDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName");
                if (sourceDatabaseNameElement2 != null) {
                    String sourceDatabaseNameInstance;
                    sourceDatabaseNameInstance = sourceDatabaseNameElement2.getTextContent();
                    serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance);
                }

                Element targetServerNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "TargetServerName");
                if (targetServerNameElement2 != null) {
                    String targetServerNameInstance;
                    targetServerNameInstance = targetServerNameElement2.getTextContent();
                    serviceResourceInstance.setTargetServerName(targetServerNameInstance);
                }

                Element targetDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "TargetDatabaseName");
                if (targetDatabaseNameElement2 != null) {
                    String targetDatabaseNameInstance;
                    targetDatabaseNameInstance = targetDatabaseNameElement2.getTextContent();
                    serviceResourceInstance.setTargetDatabaseName(targetDatabaseNameInstance);
                }

                Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    String nameInstance;
                    nameInstance = nameElement.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:io.personium.test.jersey.cell.auth.ImplicitFlowTest.java

static void checkHtmlBody(PersoniumResponse res, String messageId, String dataCellName, String dcOwner) {
        DOMParser parser = new DOMParser();
        InputSource body = null;/*  w  w w .  jav  a 2  s  .c  om*/
        body = new InputSource(res.bodyAsStream());
        try {
            parser.parse(body);
        } catch (SAXException e) {
            fail(e.getMessage());
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Document document = parser.getDocument();
        NodeList nodeList = document.getElementsByTagName("script");
        assertEquals(AuthResourceUtils.getJavascript("ajax.js"), ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("title");
        assertEquals(PersoniumCoreMessageUtils.getMessage("PS-AU-0001"),
                ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("body");
        String expectedAppUrl = UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1) + "__/profile.json";
        String expectedDataUrl = UrlUtils.cellRoot(dataCellName) + "__/profile.json";
        assertEquals("requestFile('GET', '" + expectedAppUrl + "' , '" + expectedDataUrl + "' ,true )",
                ((Element) nodeList.item(0)).getAttribute("onload"));

        nodeList = document.getElementsByTagName("h1");
        assertEquals(PersoniumCoreMessageUtils.getMessage("PS-AU-0001"),
                ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("form");
        String expectedFormUrl = UrlUtils.cellRoot(dataCellName) + "__authz";
        assertEquals(expectedFormUrl, ((Element) nodeList.item(0)).getAttribute("action"));

        nodeList = document.getElementsByTagName("div");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            String id = element.getAttribute("id");
            if ("message".equals(id)) {
                assertEquals(PersoniumCoreMessageUtils.getMessage(messageId).replaceAll("<br />", ""),
                        element.getTextContent());
            }
        }

        nodeList = document.getElementsByTagName("input");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            String id = element.getAttribute("id");
            if ("state".equals(id)) {
                assertEquals(DEFAULT_STATE, element.getAttribute("value"));
            } else if ("p_target".equals(id)) {
                assertEquals("", element.getAttribute("value"));

            } else if ("p_owner".equals(id)) {
                assertEquals(dcOwner, element.getAttribute("value"));
            } else if ("client_id".equals(id)) {
                assertEquals(UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1), element.getAttribute("value"));
            } else if ("redirect_uri".equals(id)) {
                assertEquals(UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1) + REDIRECT_HTML,
                        element.getAttribute("value"));
            }
        }
    }

From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java

public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) {
    // svn diff -r 4000:HEAD --summarize --xml

    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();

    try {/*  w ww. j a va  2s  .c  o m*/
        ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "diff", "-r",
                startRevision + ":HEAD", "--summarize", "--xml");

        processBuilder.directory(new File(repoLocations + repoName));
        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        StringBuffer sb = new StringBuffer();

        while ((line = br.readLine()) != null) {
            Singleton.getLogger().info("svn diff: " + line);
            sb.append(Helpers.removeUTF8BOM(line));
        }

        Singleton.getLogger().info("Before XML parsing: " + sb.toString());

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
        doc.getDocumentElement().normalize();

        Element node = (Element) doc.getElementsByTagName("diff").item(0);
        node = (Element) node.getElementsByTagName("paths").item(0);

        NodeList nList = node.getElementsByTagName("path");

        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                String type = eElement.getAttribute("item");
                String path = eElement.getTextContent();

                if ("modified".equals(type) || "added".equals(type)) {
                    changedFiles.add(path);
                } else {
                    deletedFiles.add(path);
                }

            }
        }
    } catch (IOException | ParserConfigurationException | SAXException ex) {
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return new RepositoryChanged(true, changedFiles, deletedFiles);
}

From source file:org.freeeed.search.web.solr.SolrSearchService.java

/**
 * Parse the given DOM to SolrResult object.
 * /*ww w  .  j ava  2  s .c  om*/
 * @param query
 * @param solrDoc
 * @return
 */
private SolrResult buildResult(Document solrDoc) {
    SolrResult result = new SolrResult();

    NodeList responseList = solrDoc.getElementsByTagName("result");
    Element responseEl = (Element) responseList.item(0);
    int totalSize = Integer.parseInt(responseEl.getAttribute("numFound"));

    result.setTotalSize(totalSize);

    NodeList documentsList = responseEl.getElementsByTagName("doc");

    Map<String, SolrDocument> solrDocuments = new HashMap<String, SolrDocument>();
    for (int i = 0; i < documentsList.getLength(); i++) {
        Element documentEl = (Element) documentsList.item(i);

        Map<String, List<String>> data = new HashMap<String, List<String>>();

        NodeList fieldsList = documentEl.getChildNodes();
        for (int j = 0; j < fieldsList.getLength(); j++) {
            Element field = (Element) fieldsList.item(j);
            String name = field.getAttribute("name");
            List<String> value = new ArrayList<String>();

            //multivalues
            if (field.getNodeName().equals("arr")) {
                NodeList strList = field.getChildNodes();
                for (int k = 0; k < strList.getLength(); k++) {
                    Node strNode = strList.item(k);
                    value.add(strNode.getTextContent());
                }
            } else {
                value.add(field.getTextContent());
            }

            data.put(name, value);
        }

        SolrDocument doc = solrDocumentParser.createSolrDocument(data);
        solrDocuments.put(doc.getDocumentId(), doc);
    }

    result.setDocuments(solrDocuments);

    return result;
}

From source file:com.vinexs.tool.XML.java

private static Object getChildJSONObject(org.w3c.dom.Element tag) {
    int i, k;/*from   www. j a va  2  s.  co m*/

    //get attributes && child nodes
    NamedNodeMap attributes = tag.getAttributes();
    NodeList childNodes = tag.getChildNodes();
    int numAttr = attributes.getLength();
    int numChild = childNodes.getLength();

    //get element nodes
    Boolean hasTagChild = false;
    Map<String, ArrayList<Object>> childMap = new HashMap<>();
    for (i = 0; i < numChild; i++) {
        Node node = childNodes.item(i);
        //not process non-element node
        if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
            continue;
        }
        hasTagChild = true;
        org.w3c.dom.Element childTag = (org.w3c.dom.Element) node;
        String tagName = childTag.getTagName();
        if (!childMap.containsKey(tagName)) {
            childMap.put(tagName, new ArrayList<>());
        }
        childMap.get(tagName).add(getChildJSONObject(childTag));
    }
    if (numAttr == 0 && !hasTagChild) {
        // Return String
        return stringToValue(tag.getTextContent());
    } else {
        // Return JSONObject
        JSONObject data = new JSONObject();
        if (numAttr > 0) {
            for (i = 0; i < numAttr; i++) {
                Node attr = attributes.item(i);
                try {
                    data.put(attr.getNodeName(), stringToValue(attr.getNodeValue()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (hasTagChild) {
            for (Map.Entry<String, ArrayList<Object>> tagMap : childMap.entrySet()) {
                ArrayList<Object> tagList = tagMap.getValue();
                if (tagList.size() == 1) {
                    try {
                        data.put(tagMap.getKey(), tagList.get(0));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    JSONArray array = new JSONArray();
                    for (k = 0; k < tagList.size(); k++) {
                        array.put(tagList.get(k));
                    }
                    try {
                        data.put(tagMap.getKey(), array);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            try {
                data.put("content", stringToValue(tag.getTextContent()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return data;
    }
}

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

/**
* Retrieves the specified quota from the server.
*
* @param serverName Required. The name of the Azure SQL Database Server
* from which to retrieve the quota./*www  .  j  av a  2  s. com*/
* @param quotaName Required. The name of the quota to retrieve.
* @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 response structure for the Quota Get operation.
*/
@Override
public QuotaGetResponse get(String serverName, String quotaName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (quotaName == null) {
        throw new NullPointerException("quotaName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/serverquotas/";
    url = url + URLEncoder.encode(quotaName, "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
        QuotaGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new QuotaGetResponse();
            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) {
                Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "ServiceResource");
                if (serviceResourceElement2 != null) {
                    Quota serviceResourceInstance = new Quota();
                    result.setQuota(serviceResourceInstance);

                    Element valueElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                            "http://schemas.microsoft.com/windowsazure", "Value");
                    if (valueElement != null) {
                        String valueInstance;
                        valueInstance = valueElement.getTextContent();
                        serviceResourceInstance.setValue(valueInstance);
                    }

                    Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        String nameInstance;
                        nameInstance = nameElement.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.sql.QuotaOperationsImpl.java

/**
* Returns a list of quotas from the server.
*
* @param serverName Required. The name of the Azure SQL Database Server
* from which to get the quotas.//from  w ww.ja v  a  2 s. 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 Represents the response structure for the Quota List operation.
*/
@Override
public QuotaListResponse 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 + "/serverquotas";
    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
        QuotaListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new QuotaListResponse();
            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));
                    Quota serviceResourceInstance = new Quota();
                    result.getQuotas().add(serviceResourceInstance);

                    Element valueElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Value");
                    if (valueElement != null) {
                        String valueInstance;
                        valueInstance = valueElement.getTextContent();
                        serviceResourceInstance.setValue(valueInstance);
                    }

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