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.phresco.pom.util.PomProcessor.java

/**
 * Gets the plugin configuration value./*from  ww w .ja v  a2 s. c o  m*/
 *
 * @param pluginGroupId the plugin group id
 * @param pluginArtifactId the plugin artifact id
 * @param tagName the tag name
 * @return the plugin configuration value
 * @throws PhrescoPomException the phresco pom exception
 */
public String getPluginConfigurationValue(String pluginGroupId, String pluginArtifactId, String tagName)
        throws PhrescoPomException {
    Plugin plugin = getPlugin(pluginGroupId, pluginArtifactId);
    Configuration configuration = plugin.getConfiguration();
    if (model.getBuild() != null && model.getBuild().getPlugins() != null && configuration != null) {
        for (Element config : configuration.getAny()) {
            if (tagName.equals(config.getTagName())) {
                return config.getTextContent();
            }
        }
    }
    return "";
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected List<Map<String, Object>> getSummaries(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it//from w  w w.java 2 s . c  om
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();
        nodes = response.getElementsByTagName("DocSum");
        for (int i = 0; i < nodes.getLength(); ++i) {
            Element n = (Element) nodes.item(i);
            Map<String, Object> doc = new HashMap<String, Object>();
            doc.put("id", n.getElementsByTagName("Id").item(0).getTextContent());
            NodeList items = n.getElementsByTagName("Item");
            for (int j = 0; j < items.getLength(); ++j) {
                Element item = (Element) items.item(j);
                if ("List".equals(item.getAttribute("Type"))) {
                    NodeList subitems = item.getElementsByTagName("Item");
                    if (subitems.getLength() > 0) {
                        List<String> values = new ArrayList<String>(subitems.getLength());
                        for (int k = 0; k < subitems.getLength(); ++k) {
                            values.add(subitems.item(k).getTextContent());
                        }
                        doc.put(item.getAttribute("Name"), values);
                    }
                } else {
                    String value = item.getTextContent();
                    if (StringUtils.isNotEmpty(value)) {
                        doc.put(item.getAttribute("Name"), value);
                    }
                }
            }
            result.add(doc);
        }
        return result;
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return Collections.emptyList();
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // =====================================================================================
    initialize(request);/*w ww  .j a  v  a  2  s  .c o  m*/

    int userId = 0;
    int groupId = 0;
    String user = "";

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    Connection c = null;
    try {
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /// uuid: celui de la ressource

    /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]

    String origin = request.getRequestURL().toString();

    /// Rcupration des paramtres
    String url = request.getPathInfo();
    String[] token = url.split("/");
    String uuid = token[1];

    String size = request.getParameter("size");
    if (size == null)
        size = "S";

    String lang = request.getParameter("lang");
    if (lang == null) {
        lang = "fr";
    }

    /// Vrification des droits d'accs
    if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid);
    }

    String data;
    String fileid = "";
    try {
        data = dataProvider.getResNode(uuid, userId, groupId);

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Cherche si on a dj envoy quelque chose
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//filename[@lang=\"" + lang + "\"]";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        String filename = "";
        if (nodelist.getLength() > 0)
            filename = nodelist.item(0).getTextContent();

        if (!"".equals(filename)) {
            /// Already have one, per language
            String filterId = "//fileid[@lang='" + lang + "']";
            NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET);
            if (idlist.getLength() != 0) {
                Element fileNode = (Element) idlist.item(0);
                fileid = fileNode.getTextContent();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }

    int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch
    if (last < 0)
        last = 0;
    fileid = fileid.substring(last);
    /// request.getHeader("REFERRER");

    /// criture des donnes
    String urlTarget = "http://" + server + "/" + fileid;
    //      String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

    // Unpack form, fetch binary data and send
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    /*
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    //*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    String json = "";
    HttpURLConnection connection = null;
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if ("uploadfile".equals(item.getFieldName())) {
                // Send raw data
                InputStream inputData = item.getInputStream();

                /*
                URL urlConn = new URL(urlTarget);
                connection = (HttpURLConnection) urlConn.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);                 /// We don't want to cache data
                connection.setInstanceFollowRedirects(false);   /// Let client follow any redirection
                String method = request.getMethod();
                connection.setRequestMethod(method);
                        
                String context = request.getContextPath();
                connection.setRequestProperty("app", context);
                //*/

                String fileName = item.getName();
                long filesize = item.getSize();
                String contentType = item.getContentType();

                //               /*
                connection = CreateConnection(urlTarget, request);
                connection.setRequestProperty("filename", uuid);
                connection.setRequestProperty("content-type", "application/octet-stream");
                connection.setRequestProperty("content-length", Long.toString(filesize));
                //*/
                connection.connect();

                OutputStream outputData = connection.getOutputStream();
                IOUtils.copy(inputData, outputData);

                /// Those 2 lines are needed, otherwise, no request sent
                int code = connection.getResponseCode();
                String msg = connection.getResponseMessage();

                InputStream objReturn = connection.getInputStream();
                StringWriter idResponse = new StringWriter();
                IOUtils.copy(objReturn, idResponse);
                fileid = idResponse.toString();

                connection.disconnect();

                /// Construct Json
                StringWriter StringOutput = new StringWriter();
                JsonWriter writer = new JsonWriter(StringOutput);
                writer.beginObject();
                writer.name("files");
                writer.beginArray();
                writer.beginObject();

                writer.name("name").value(fileName);
                writer.name("size").value(filesize);
                writer.name("type").value(contentType);
                writer.name("url").value(origin);
                writer.name("fileid").value(fileid);
                //                               writer.name("deleteUrl").value(ref);
                //                                       writer.name("deleteType").value("DELETE");
                writer.endObject();

                writer.endArray();
                writer.endObject();

                writer.close();

                json = StringOutput.toString();

                /*
                DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream());
                byte[] buffer = new byte[1024];
                int dataSize;
                while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
                {
                   datawriter.write(buffer, 0, dataSize);
                }
                datawriter.flush();
                datawriter.close();
                //*/
                //               outputData.close();
                //               inputData.close();

                break;
            }
        }
    } catch (FileUploadException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
    HttpURLConnection connection = CreateConnection( urlTarget, request );
            
    connection.setRequestProperty("referer", origin);
            
    /// Send post data
    ServletInputStream inputData = request.getInputStream();
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            
    byte[] buffer = new byte[1024];
    int dataSize;
    while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
    {
       writer.write(buffer, 0, dataSize);
    }
    inputData.close();
    writer.close();
            
    /// So we can forward some Set-Cookie
    String ref = request.getHeader("referer");
            
    /// Prend le JSON du fileserver
    InputStream in = connection.getInputStream();
            
    InitAnswer(connection, response, ref);
            
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    StringBuilder builder = new StringBuilder();
    for( String line = null; (line = reader.readLine()) != null; )
       builder.append(line).append("\n");
    //*/

    /// Envoie la mise  jour au backend
    /*
    try
    {
       PostForm.updateResource(session.getId(), backend, uuid, lang, json);
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
    //*/

    connection.disconnect();
    /// Renvoie le JSON au client
    response.setContentType("application/json");
    PrintWriter respWriter = response.getWriter();
    respWriter.write(json);

    //      RetrieveAnswer(connection, response, ref);
    dataProvider.disconnect();
}

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

private KalturaApiException getExceptionOnAPIError(Element result) throws KalturaApiException {
    Element errorElement = getElementByXPath(result, "error");
    if (errorElement == null) {
        return null;
    }//from   w  w  w.ja v  a 2s .  c  o  m

    Element messageElement = getElementByXPath(errorElement, "message");
    Element codeElement = getElementByXPath(errorElement, "code");
    if (messageElement == null || codeElement == null) {
        return null;
    }

    return new KalturaApiException(messageElement.getTextContent(), codeElement.getTextContent());
}

From source file:com.joliciel.frenchTreebank.search.XmlPatternSearchImpl.java

private ComponentWordNode getComponentWordNode(Node node) {
    Element element = (Element) node;
    String tag = node.getNodeName();
    if (tag != "w")
        throw new TreebankException("Only w elements are allowed beneath a w element");
    String categoryCode = element.getAttribute("cat");
    String word = element.getTextContent();
    LOG.debug("component w: cat=" + categoryCode + ", word=" + word);
    ComponentWordNode componentWordNode = new ComponentWordNode(categoryCode, word, phraseSubunitCounter++);
    return componentWordNode;
}

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

private BorhanApiException getExceptionOnAPIError(Element result) throws BorhanApiException {
    Element errorElement = getElementByXPath(result, "error");
    if (errorElement == null) {
        return null;
    }/*from   w  ww .  j  ava 2s. c  o  m*/

    Element messageElement = getElementByXPath(errorElement, "message");
    Element codeElement = getElementByXPath(errorElement, "code");
    if (messageElement == null || codeElement == null) {
        return null;
    }

    return new BorhanApiException(messageElement.getTextContent(), codeElement.getTextContent());
}

From source file:com.cloud.test.regression.ApiCommand.java

public boolean setParam(HashMap<String, String> param) {
    if ((this.responseBody == null) && (this.commandType == CommandType.HTTP)) {
        s_logger.error("Response body is empty");
        return false;
    }/*from w  ww.j av a 2 s .  c om*/
    Boolean result = true;

    if (this.getCommandType() == CommandType.MYSQL) {
        Set<?> set = this.setParam.entrySet();
        Iterator<?> it = set.iterator();
        while (it.hasNext()) {
            Map.Entry<?, ?> me = (Map.Entry<?, ?>) it.next();
            String key = (String) me.getKey();
            String value = (String) me.getValue();
            try {
                String itemName = null;
                while (this.result.next()) {
                    itemName = this.result.getString(value);
                }
                if (itemName != null) {
                    param.put(key, itemName);
                } else {
                    s_logger.error("Following return parameter is missing: " + value);
                    result = false;
                }
            } catch (Exception ex) {
                s_logger.error("Unable to set parameter " + value, ex);
            }
        }
    } else if (this.getCommandType() == CommandType.HTTP) {
        if (this.list == false) {
            Set<?> set = this.setParam.entrySet();
            Iterator<?> it = set.iterator();

            while (it.hasNext()) {
                Map.Entry<?, ?> me = (Map.Entry<?, ?>) it.next();
                String key = (String) me.getKey();
                String value = (String) me.getValue();
                // set parameters needed for the future use
                NodeList itemName = this.responseBody.getElementsByTagName(value);
                if ((itemName != null) && (itemName.getLength() != 0)) {
                    for (int i = 0; i < itemName.getLength(); i++) {
                        Element itemNameElement = (Element) itemName.item(i);
                        if (itemNameElement.getChildNodes().getLength() <= 1) {
                            param.put(key, itemNameElement.getTextContent());
                            break;
                        }
                    }
                } else {
                    s_logger.error("Following return parameter is missing: " + value);
                    result = false;
                }
            }
        } else {
            Set<?> set = this.setParam.entrySet();
            Iterator<?> it = set.iterator();
            NodeList returnLst = this.responseBody.getElementsByTagName(this.listName.getTextContent());
            Node requiredNode = returnLst.item(Integer.parseInt(this.listId.getTextContent()));

            if (requiredNode.getNodeType() == Node.ELEMENT_NODE) {
                Element fstElmnt = (Element) requiredNode;

                while (it.hasNext()) {
                    Map.Entry<?, ?> me = (Map.Entry<?, ?>) it.next();
                    String key = (String) me.getKey();
                    String value = (String) me.getValue();
                    NodeList itemName = fstElmnt.getElementsByTagName(value);
                    if ((itemName != null) && (itemName.getLength() != 0)) {
                        Element itemNameElement = (Element) itemName.item(0);
                        if (itemNameElement.getChildNodes().getLength() <= 1) {
                            param.put(key, itemNameElement.getTextContent());
                        }
                    } else {
                        s_logger.error("Following return parameter is missing: " + value);
                        result = false;
                    }
                }
            }
        }
    }
    return result;
}

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

/**
* The Delete Client Root Certificate operation deletes a previously
* uploaded client root certificate from Azure.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx for
* more information)//from  w  w  w .  jav  a2s  .c  o  m
*
* @param networkName Required. The name of the virtual network for this
* gateway.
* @param certificateThumbprint Required. The X509 certificate thumbprint.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public GatewayOperationResponse delete(String networkName, String certificateThumbprint)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException {
    // Validate
    if (networkName == null) {
        throw new NullPointerException("networkName");
    }
    if (certificateThumbprint == null) {
        throw new NullPointerException("certificateThumbprint");
    }

    // 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);
        tracingParameters.put("certificateThumbprint", certificateThumbprint);
        CloudTracing.enter(invocationId, this, "deleteAsync", 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/";
    url = url + URLEncoder.encode(certificateThumbprint, "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
    CustomHttpDelete httpRequest = new CustomHttpDelete(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
        GatewayOperationResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new GatewayOperationResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
            if (gatewayOperationAsyncResponseElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setOperationId(idInstance);
                }
            }

        }
        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.network.ClientRootCertificateOperationsImpl.java

/**
* The Upload Client Root Certificate operation is used to upload a new
* client root certificate to Azure.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx for
* more information)//  www .j  a v a2 s  .  c om
*
* @param networkName Required. The name of the virtual network for this
* gateway.
* @param parameters Required. Parameters supplied to the Upload Client Root
* Certificate Virtual Network Gateway operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public GatewayOperationResponse create(String networkName, ClientRootCertificateCreateParameters parameters)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException {
    // Validate
    if (networkName == null) {
        throw new NullPointerException("networkName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getCertificate() == null) {
        throw new NullPointerException("parameters.Certificate");
    }

    // 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);
        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/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
    HttpPost httpRequest = new HttpPost(url);

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

    // Serialize Request
    String requestContent = parameters.getCertificate();
    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_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
            if (gatewayOperationAsyncResponseElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setOperationId(idInstance);
                }
            }

        }
        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:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

/**
 * @param element//from   ww w  .j a va2  s.co  m
 * @return
 */
protected ManagedList<Object> prepareBaseDirectoryList(Element element) {
    ManagedList<Object> list = new ManagedList<Object>();
    Element locationElement = selectSingleChildElement(element, "location", true);
    if (locationElement != null) {
        List<Element> selectChildElements = selectChildElements(locationElement, "*");
        for (Element location : selectChildElements) {
            String tag = location.getLocalName();
            if ("environment-variable".equals(tag)) {
                list.add(prepareLocation(location.getTextContent(), EnvironmentVariableDirectory.class));
            } else if ("system-property".equals(tag)) {
                list.add(prepareLocation(location.getTextContent(), SystemPropertyDirectory.class));
            } else if ("home".equals(tag)) {
                list.add(prepareHomeLocation(element, location.getAttribute("path")));
            } else if ("platform".equals(tag)) {
                list.add(preparePlatformLocation(location.getTextContent()));
            } else if ("webapp".equals(tag)) {
                list.add(prepareWebappLocation(element, location.getAttribute("path")));
            } else if ("resource".equals(tag)) {
                list.add(prepareResourceLocation(element, location.getAttribute("location")));
            } else {
                throw new IllegalArgumentException(String.format("Unknown location type '%s'", tag));
            }
        }
    } else {
        list.add(prepareHomeLocation(element, null));
        PlatformDirectory[] values = PlatformDirectory.values();
        for (PlatformDirectory platformDirectory : values) {
            list.add(platformDirectory);
        }
        // home, webapp (if available) and platforms
        if (ClassUtils.isPresent("org.springframework.web.context.WebApplicationContext",
                this.getClass().getClassLoader())) {
            list.add(prepareWebappLocation(element, null));
        }
    }
    return list;
}