Example usage for org.w3c.dom Document createElementNS

List of usage examples for org.w3c.dom Document createElementNS

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:ml.shifu.shifu.core.pmml.builder.impl.ZscoreLocalTransformCreator.java

/**
 * Create DerivedField for categorical variable
 * /* w ww .  java 2s. c o m*/
 * @param config
 *            - ColumnConfig for categorical variable
 * @param cutoff
 *            - cutoff for normalization
 * @param normType
 *            - the normalization method that is used to generate DerivedField
 * @return DerivedField for variable
 */
protected List<DerivedField> createCategoricalDerivedField(ColumnConfig config, double cutoff,
        ModelNormalizeConf.NormType normType) {
    Document document = null;
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        LOG.error("Fail to create document node.", e);
        throw new RuntimeException("Fail to create document node.", e);
    }

    String defaultValue = Normalizer.normalize(config, "doesn't exist at all...by paypal", cutoff, normType)
            .get(0).toString();
    String missingValue = Normalizer.normalize(config, null, cutoff, normType).get(0).toString();

    InlineTable inlineTable = new InlineTable();
    for (int i = 0; i < config.getBinCategory().size(); i++) {
        List<String> catVals = CommonUtils.flattenCatValGrp(config.getBinCategory().get(i));
        for (String cval : catVals) {
            String dval = Normalizer.normalize(config, cval, cutoff, normType).get(0).toString();

            Element out = document.createElementNS(NAME_SPACE_URI, ELEMENT_OUT);
            out.setTextContent(dval);

            Element origin = document.createElementNS(NAME_SPACE_URI, ELEMENT_ORIGIN);
            origin.setTextContent(cval);

            inlineTable.addRows(new Row().addContent(origin).addContent(out));
        }
    }

    MapValues mapValues = new MapValues("out").setDataType(DataType.DOUBLE).setDefaultValue(defaultValue)
            .addFieldColumnPairs(new FieldColumnPair(new FieldName(NormalUtils.getSimpleColumnName(config,
                    columnConfigList, segmentExpansions, datasetHeaders)), ELEMENT_ORIGIN))
            .setInlineTable(inlineTable).setMapMissingTo(missingValue);
    List<DerivedField> derivedFields = new ArrayList<DerivedField>();
    derivedFields.add(new DerivedField(OpType.CONTINUOUS, DataType.DOUBLE)
            .setName(FieldName.create(
                    genPmmlColumnName(NormalUtils.getSimpleColumnName(config.getColumnName()), normType)))
            .setExpression(mapValues));
    return derivedFields;
}

From source file:eu.europa.ec.markt.dss.applet.view.validationpolicy.EditView.java

private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath,
        final XmlDomAdapterNode clickedItem, final JTree tree) {
    final Element clickedElement = (Element) clickedItem.node;
    // popup menu for list -> add
    final JPopupMenu popup = new JPopupMenu();
    //delete node
    final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE"));
    menuItemToDelete.addActionListener(new ActionListener() {
        @Override//  w w  w.jav  a 2 s . c o m
        public void actionPerformed(ActionEvent actionEvent) {
            // find the order# of the child to delete
            final int index = clickedItem.getParent().index(clickedItem);

            Node oldChild = clickedElement.getParentNode().removeChild(clickedElement);
            if (index > -1) {
                validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild);
            }
        }
    });
    popup.add(menuItemToDelete);

    //Add node/value
    final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree();
    final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree);
    for (final XsdNode xsdChild : children) {
        final String xmlName = xsdChild.getLastNameOfPath();

        final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " "
                + xsdChild.getType().toString().toLowerCase() + ")");
        popup.add(menuItem);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Document document = getModel().getValidationPolicy().getDocument();

                final Node newElement;
                if (xsdChild.getType() == XsdNodeType.TEXT) {
                    // TEXT element always appended (last child)
                    newElement = clickedElement.appendChild(document.createTextNode("VALUE"));
                } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) {
                    newElement = document.createAttributeNS(null, xmlName);
                    ((Attr) newElement).setValue("VALUE");
                    clickedElement.setAttributeNode((Attr) newElement);
                } else if (xsdChild.getType() == XsdNodeType.ELEMENT) {
                    final Element childToAdd = document
                            .createElementNS("http://dss.markt.ec.europa.eu/validation/diagnostic", xmlName);
                    // find the correct possition to add the child
                    // Get all allowed children
                    Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree);
                    boolean toAddSeen = false;
                    Element elementIsToAddBeforeThisOne = null;
                    for (final XsdNode allowed : childrenMap.keySet()) {
                        if (!toAddSeen && allowed == xsdChild) {
                            toAddSeen = true;
                            continue;
                        }
                        if (toAddSeen) {
                            final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS(
                                    "http://dss.markt.ec.europa.eu/validation/diagnostic",
                                    allowed.getLastNameOfPath());
                            if (elementsByTagNameNS.getLength() > 0) {
                                // we found an element that is supposed to be after the one to add
                                elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0);
                                break;
                            }
                        }
                    }

                    if (elementIsToAddBeforeThisOne != null) {
                        newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne);
                    } else {
                        newElement = clickedElement.appendChild(childToAdd);
                    }
                } else {
                    throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType());
                }

                document.normalizeDocument();

                int indexOfAddedItem = 0;
                final int childCount = clickedItem.childCount();
                for (int i = 0; i < childCount; i++) {
                    if (clickedItem.child(i).node == newElement) {
                        indexOfAddedItem = i;
                        break;
                    }
                }

                TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath,
                        new int[] { indexOfAddedItem }, new Object[] { newElement });
                validationPolicyTreeModel.fireTreeNodesInserted(event);
                tree.expandPath(selectedPath);

                //Update model
                getModel().getValidationPolicy().setXmlDom(new XmlDom(document));
            }
        });

    }
    popup.show(tree, mouseEvent.getX(), mouseEvent.getY());
}

From source file:ml.shifu.shifu.core.pmml.PMMLTranslator.java

/**
 * Create @DerivedField for categorical variable
 * @param config - ColumnConfig for categorical variable
 * @param cutoff - cutoff for normalization
 * @return DerivedField for variable// w  w w  . j  a v a  2 s  . c o  m
 */
private DerivedField createCategoricalDerivedField(ColumnConfig config, double cutoff) {
    Document document = null;
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        LOG.error("Fail to create document node.", e);
        throw new RuntimeException("Fail to create document node.", e);
    }

    String defaultValue = "0.0";
    String missingValue = "0.0";

    InlineTable inlineTable = new InlineTable();
    for (int i = 0; i < config.getBinCategory().size(); i++) {
        String cval = config.getBinCategory().get(i);
        String dval = Normalizer.normalize(config, cval, cutoff).toString();

        Element out = document.createElementNS(NAME_SPACE_URI, ELEMENT_OUT);
        out.setTextContent(dval);

        Element origin = document.createElementNS(NAME_SPACE_URI, ELEMENT_ORIGIN);
        origin.setTextContent(cval);

        inlineTable.withRows(new Row().withContent(origin).withContent(out));
        if (StringUtils.isBlank(cval)) {
            missingValue = dval;
        }
    }

    MapValues mapValues = new MapValues("out").withDataType(DataType.DOUBLE).withDefaultValue(defaultValue)
            .withFieldColumnPairs(new FieldColumnPair(new FieldName(config.getColumnName()), ELEMENT_ORIGIN))
            .withInlineTable(inlineTable).withMapMissingTo(missingValue);

    return new DerivedField(OpType.CONTINUOUS, DataType.DOUBLE)
            .withName(FieldName.create(config.getColumnName() + ZSCORE_POSTFIX)).withExpression(mapValues);
}

From source file:eu.europa.esig.dss.applet.view.validationpolicy.EditView.java

private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath,
        final XmlDomAdapterNode clickedItem, final JTree tree) {
    final Element clickedElement = (Element) clickedItem.node;
    // popup menu for list -> add
    final JPopupMenu popup = new JPopupMenu();
    //delete node
    final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE"));
    menuItemToDelete.addActionListener(new ActionListener() {
        @Override/*  w w w .  j av a 2  s. c o  m*/
        public void actionPerformed(ActionEvent actionEvent) {
            // find the order# of the child to delete
            final int index = clickedItem.getParent().index(clickedItem);

            Node oldChild = clickedElement.getParentNode().removeChild(clickedElement);
            if (index > -1) {
                validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild);
            }
        }
    });
    popup.add(menuItemToDelete);

    //Add node/value
    final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree();
    final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree);
    for (final XsdNode xsdChild : children) {
        final String xmlName = xsdChild.getLastNameOfPath();

        final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " "
                + xsdChild.getType().toString().toLowerCase() + ")");
        popup.add(menuItem);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Document document = getModel().getValidationPolicy().getDocument();

                final Node newElement;
                if (xsdChild.getType() == XsdNodeType.TEXT) {
                    // TEXT element always appended (last child)
                    newElement = clickedElement.appendChild(document.createTextNode("VALUE"));
                } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) {
                    newElement = document.createAttributeNS(null, xmlName);
                    ((Attr) newElement).setValue("VALUE");
                    clickedElement.setAttributeNode((Attr) newElement);
                } else if (xsdChild.getType() == XsdNodeType.ELEMENT) {
                    final Element childToAdd = document
                            .createElementNS("http://dss.esig.europa.eu/validation/diagnostic", xmlName);
                    // find the correct possition to add the child
                    // Get all allowed children
                    Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree);
                    boolean toAddSeen = false;
                    Element elementIsToAddBeforeThisOne = null;
                    for (final XsdNode allowed : childrenMap.keySet()) {
                        if (!toAddSeen && (allowed == xsdChild)) {
                            toAddSeen = true;
                            continue;
                        }
                        if (toAddSeen) {
                            final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS(
                                    "http://dss.esig.europa.eu/validation/diagnostic",
                                    allowed.getLastNameOfPath());
                            if (elementsByTagNameNS.getLength() > 0) {
                                // we found an element that is supposed to be after the one to add
                                elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0);
                                break;
                            }
                        }
                    }

                    if (elementIsToAddBeforeThisOne != null) {
                        newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne);
                    } else {
                        newElement = clickedElement.appendChild(childToAdd);
                    }
                } else {
                    throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType());
                }

                document.normalizeDocument();

                int indexOfAddedItem = 0;
                final int childCount = clickedItem.childCount();
                for (int i = 0; i < childCount; i++) {
                    if (clickedItem.child(i).node == newElement) {
                        indexOfAddedItem = i;
                        break;
                    }
                }

                TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath,
                        new int[] { indexOfAddedItem }, new Object[] { newElement });
                validationPolicyTreeModel.fireTreeNodesInserted(event);
                tree.expandPath(selectedPath);

                //Update model
                getModel().getValidationPolicy().setXmlDom(new XmlDom(document));
            }
        });

    }
    popup.show(tree, mouseEvent.getX(), mouseEvent.getY());
}

From source file:com.microsoft.windowsazure.management.compute.ServiceCertificateOperationsImpl.java

/**
* The Begin Creating Service Certificate operation adds a certificate to a
* hosted service. This operation is an asynchronous operation. To
* determine whether the management service has finished processing the
* request, call Get Operation Status.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for
* more information)/*from w  w  w  .j  a  v  a  2s. c o  m*/
*
* @param serviceName Required. The DNS prefix name of your service.
* @param parameters Required. Parameters supplied to the Begin Creating
* Service Certificate operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreating(String serviceName, ServiceCertificateCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getCertificateFormat() == null) {
        throw new NullPointerException("parameters.CertificateFormat");
    }
    if (parameters.getData() == null) {
        throw new NullPointerException("parameters.Data");
    }

    // 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("serviceName", serviceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", 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/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/certificates";
    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 = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

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

    Element dataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Data");
    dataElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData())));
    certificateFileElement.appendChild(dataElement);

    Element certificateFormatElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "CertificateFormat");
    certificateFormatElement.appendChild(requestDoc.createTextNode(
            ComputeManagementClientImpl.certificateFormatToString(parameters.getCertificateFormat())));
    certificateFileElement.appendChild(certificateFormatElement);

    if (parameters.getPassword() != null) {
        Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Password");
        passwordElement.appendChild(requestDoc.createTextNode(parameters.getPassword()));
        certificateFileElement.appendChild(passwordElement);
    }

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

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        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.apache.cxf.cwiki.SiteExporter.java

public int getBlogVersion(String pageId) throws Exception {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getBlogEntry");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//  w w  w.  j  ava2 s  . co  m
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(pageId);
    doc.appendChild(el);
    doc = getDispatch().invoke(doc);

    Node nd = doc.getDocumentElement().getFirstChild();

    String version = DOMUtils.getChildContent(nd, "version");
    return Integer.parseInt(version);
}

From source file:com.microsoft.windowsazure.management.mediaservices.AccountOperationsImpl.java

/**
* The Create Media Services Account operation creates a new media services
* account in Windows Azure.  (see/*from ww w.  j ava  2 s .  co  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Create Media
* Services Account operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The Create Media Services Account operation response.
*/
@Override
public MediaServicesAccountCreateResponse create(MediaServicesAccountCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getAccountName() == null) {
        throw new NullPointerException("parameters.AccountName");
    }
    if (parameters.getAccountName().length() < 3) {
        throw new IllegalArgumentException("parameters.AccountName");
    }
    if (parameters.getAccountName().length() > 24) {
        throw new IllegalArgumentException("parameters.AccountName");
    }
    if (parameters.getBlobStorageEndpointUri() == null) {
        throw new NullPointerException("parameters.BlobStorageEndpointUri");
    }
    if (parameters.getRegion() == null) {
        throw new NullPointerException("parameters.Region");
    }
    if (parameters.getRegion().length() < 3) {
        throw new IllegalArgumentException("parameters.Region");
    }
    if (parameters.getRegion().length() > 256) {
        throw new IllegalArgumentException("parameters.Region");
    }
    if (parameters.getStorageAccountKey() == null) {
        throw new NullPointerException("parameters.StorageAccountKey");
    }
    if (parameters.getStorageAccountKey().length() < 14) {
        throw new IllegalArgumentException("parameters.StorageAccountKey");
    }
    if (parameters.getStorageAccountKey().length() > 256) {
        throw new IllegalArgumentException("parameters.StorageAccountKey");
    }
    if (parameters.getStorageAccountName() == null) {
        throw new NullPointerException("parameters.StorageAccountName");
    }
    if (parameters.getStorageAccountName().length() < 3) {
        throw new IllegalArgumentException("parameters.StorageAccountName");
    }
    if (parameters.getStorageAccountName().length() > 24) {
        throw new IllegalArgumentException("parameters.StorageAccountName");
    }
    for (char storageAccountNameChar : parameters.getStorageAccountName().toCharArray()) {
        if (Character.isLowerCase(storageAccountNameChar) == false
                && Character.isDigit(storageAccountNameChar) == false) {
            throw new IllegalArgumentException("parameters.StorageAccountName");
        }
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "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/mediaservices/Accounts";
    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", "2011-10-01");

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

    Element accountCreationRequestElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "AccountCreationRequest");
    requestDoc.appendChild(accountCreationRequestElement);

    Element accountNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "AccountName");
    accountNameElement.appendChild(requestDoc.createTextNode(parameters.getAccountName()));
    accountCreationRequestElement.appendChild(accountNameElement);

    Element blobStorageEndpointUriElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "BlobStorageEndpointUri");
    blobStorageEndpointUriElement
            .appendChild(requestDoc.createTextNode(parameters.getBlobStorageEndpointUri().toString()));
    accountCreationRequestElement.appendChild(blobStorageEndpointUriElement);

    Element regionElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "Region");
    regionElement.appendChild(requestDoc.createTextNode(parameters.getRegion()));
    accountCreationRequestElement.appendChild(regionElement);

    Element storageAccountKeyElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "StorageAccountKey");
    storageAccountKeyElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountKey()));
    accountCreationRequestElement.appendChild(storageAccountKeyElement);

    Element storageAccountNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "StorageAccountName");
    storageAccountNameElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountName()));
    accountCreationRequestElement.appendChild(storageAccountNameElement);

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

        // Create Result
        MediaServicesAccountCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new MediaServicesAccountCreateResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount();
                result.setAccount(accountInstance);

                JsonNode accountIdValue = responseDoc.get("AccountId");
                if (accountIdValue != null && accountIdValue instanceof NullNode == false) {
                    String accountIdInstance;
                    accountIdInstance = accountIdValue.getTextValue();
                    accountInstance.setAccountId(accountIdInstance);
                }

                JsonNode accountNameValue = responseDoc.get("AccountName");
                if (accountNameValue != null && accountNameValue instanceof NullNode == false) {
                    String accountNameInstance;
                    accountNameInstance = accountNameValue.getTextValue();
                    accountInstance.setAccountName(accountNameInstance);
                }

                JsonNode subscriptionValue = responseDoc.get("Subscription");
                if (subscriptionValue != null && subscriptionValue instanceof NullNode == false) {
                    String subscriptionInstance;
                    subscriptionInstance = subscriptionValue.getTextValue();
                    accountInstance.setSubscriptionId(subscriptionInstance);
                }
            }

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

/**
* Sets IP Forwarding on a role./*from  www.  j a v a2  s  .  c  o m*/
*
* @param serviceName Required.
* @param deploymentName Required.
* @param roleName Required.
* @param parameters Required. Parameters supplied to the Set IP Forwarding
* on role operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginSettingIPForwardingOnRole(String serviceName, String deploymentName,
        String roleName, IPForwardingSetParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (roleName == null) {
        throw new NullPointerException("roleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getState() == null) {
        throw new NullPointerException("parameters.State");
    }

    // 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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("roleName", roleName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginSettingIPForwardingOnRoleAsync", 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/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roles/";
    url = url + URLEncoder.encode(roleName, "UTF-8");
    url = url + "/ipforwarding";
    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 = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

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

    Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State");
    stateElement.appendChild(requestDoc.createTextNode(parameters.getState()));
    iPForwardingElement.appendChild(stateElement);

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

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        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.apache.cxf.cwiki.SiteExporter.java

private void checkVersion() throws ParserConfigurationException, IOException {
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getServerInfo");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//from  w w  w  . j  a v a  2 s.c om
    el2.setTextContent(loginToken);
    doc.appendChild(el);

    doc = getDispatch().invoke(doc);
    el = DOMUtils.getFirstElement(DOMUtils.getFirstElement(doc.getDocumentElement()));
    while (el != null) {
        if ("majorVersion".equals(el.getLocalName())) {
            String major = DOMUtils.getContent(el);
            if (Integer.parseInt(major) >= 5) {
                apiVersion = 2;
                ((java.io.Closeable) dispatch).close();
                dispatch = null;
            }
        }

        el = DOMUtils.getNextElement(el);
    }
}

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

/**
* Sets IP Forwarding on a network interface.
*
* @param serviceName Required.//from   ww  w.  j  a  v  a 2s .  c om
* @param deploymentName Required.
* @param roleName Required.
* @param networkInterfaceName Required.
* @param parameters Required. Parameters supplied to the Set IP Forwarding
* on network interface operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginSettingIPForwardingOnNetworkInterface(String serviceName,
        String deploymentName, String roleName, String networkInterfaceName,
        IPForwardingSetParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (roleName == null) {
        throw new NullPointerException("roleName");
    }
    if (networkInterfaceName == null) {
        throw new NullPointerException("networkInterfaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getState() == null) {
        throw new NullPointerException("parameters.State");
    }

    // 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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("roleName", roleName);
        tracingParameters.put("networkInterfaceName", networkInterfaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginSettingIPForwardingOnNetworkInterfaceAsync",
                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/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roles/";
    url = url + URLEncoder.encode(roleName, "UTF-8");
    url = url + "/networkinterfaces/";
    url = url + URLEncoder.encode(networkInterfaceName, "UTF-8");
    url = url + "/ipforwarding";
    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 = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

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

    Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State");
    stateElement.appendChild(requestDoc.createTextNode(parameters.getState()));
    iPForwardingElement.appendChild(stateElement);

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

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        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();
        }
    }
}