Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

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)/* w  w w.  j a  v a 2  s  .  co 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:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

protected InputStream getToBeSignedStream(Document document, SignatureParameters parameters) {

    try {// w w w . ja va  2s .  c  o m

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);
        DOMXMLSignature signature = createSignature(parameters, doc, document, signContext, signatureValueId);

        /* Output document */
        if (LOG.isLoggable(Level.FINE)) {
            ByteArrayOutputStream logOutput = new ByteArrayOutputStream();
            Result result = new StreamResult(logOutput);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            Source source = new DOMSource(doc);
            xformer.transform(source, result);
            LOG.fine("Document after digest " + new String(logOutput.toByteArray()));
        }

        DOMSignedInfo domSignedInfo = (DOMSignedInfo) signature.getSignedInfo();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        domSignedInfo.canonicalize(signContext, output);
        output.close();

        return new ByteArrayInputStream(output.toByteArray());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.shareok.data.sagedata.SageJournalDataProcessorAbstract.java

@Override
/** //from w ww.ja va 2s  .c  o m
 * Convert the article data to dublin core xml metadata and save the the file
 * 
 * @param String fileName : the root folder contains all the uploading article data
 */
public void exportXmlByJournalData(String fileName) {

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("dublin_core");
        doc.appendChild(rootElement);

        // Add the type node:
        Element element = doc.createElement("dcvalue");
        element.appendChild(doc.createTextNode("Research Article"));
        rootElement.appendChild(element);

        Attr attr = doc.createAttribute("element");
        attr.setValue("type");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("none");
        element.setAttributeNode(attr);

        // Add the abstract node:
        String abs = journalData.getAbstractText();
        if (null != abs) {
            Element elementAbs = doc.createElement("dcvalue");
            elementAbs.appendChild(doc.createTextNode(abs));
            rootElement.appendChild(elementAbs);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("abstract");
            elementAbs.setAttributeNode(attr);
        }

        // Add the language node:
        String lang = journalData.getLanguage();
        if (null != lang) {
            Element elementLang = doc.createElement("dcvalue");
            elementLang.appendChild(doc.createTextNode(lang));
            rootElement.appendChild(elementLang);

            attr = doc.createAttribute("element");
            attr.setValue("language");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("iso");
            elementLang.setAttributeNode(attr);
        }

        // Add the title node:
        String tit = journalData.getTitle();
        if (null != tit) {
            Element elementTitle = doc.createElement("dcvalue");
            elementTitle.appendChild(doc.createTextNode(tit));
            rootElement.appendChild(elementTitle);

            attr = doc.createAttribute("element");
            attr.setValue("title");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementTitle.setAttributeNode(attr);
        }

        // Add the available date node:
        //            Element elementAvailable = doc.createElement("dcvalue");
        //            elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString()));
        //            rootElement.appendChild(elementAvailable);
        //            
        //            attr = doc.createAttribute("element");
        //            attr.setValue("date");
        //            elementAvailable.setAttributeNode(attr);
        //            
        //            attr = doc.createAttribute("qualifier");
        //            attr.setValue("available");
        //            elementAvailable.setAttributeNode(attr);

        // Add the issued date node:
        Date issueDate = journalData.getDateIssued();
        if (null != issueDate) {
            SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd");
            Element elementIssued = doc.createElement("dcvalue");
            elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate)));
            rootElement.appendChild(elementIssued);

            attr = doc.createAttribute("element");
            attr.setValue("date");
            elementIssued.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("issued");
            elementIssued.setAttributeNode(attr);
        }

        // Add the author nodes:
        String[] authorSet = journalData.getAuthors();
        if (null != authorSet && authorSet.length > 0) {
            for (String author : authorSet) {
                Element elementAuthor = doc.createElement("dcvalue");
                elementAuthor.appendChild(doc.createTextNode(author));
                rootElement.appendChild(elementAuthor);

                attr = doc.createAttribute("element");
                attr.setValue("contributor");
                elementAuthor.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("author");
                elementAuthor.setAttributeNode(attr);
            }
        }

        // Add the acknowledgements node:
        String ack = journalData.getAcknowledgements();
        if (null != ack) {
            Element elementAck = doc.createElement("dcvalue");
            elementAck.appendChild(doc.createTextNode(ack));
            rootElement.appendChild(elementAck);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementAck.setAttributeNode(attr);
        }

        // Add the author contributions node:
        String contrib = journalData.getAuthorContributions();
        if (null != contrib) {
            Element elementContribution = doc.createElement("dcvalue");
            elementContribution.appendChild(doc.createTextNode(contrib));
            rootElement.appendChild(elementContribution);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementContribution.setAttributeNode(attr);
        }

        // Add the publisher node:
        String puber = journalData.getPublisher();
        if (null != puber) {
            Element elementPublisher = doc.createElement("dcvalue");
            elementPublisher.appendChild(doc.createTextNode(puber));
            rootElement.appendChild(elementPublisher);

            attr = doc.createAttribute("element");
            attr.setValue("publisher");
            elementPublisher.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementPublisher.setAttributeNode(attr);
        }

        // Add the citation node:
        String cit = journalData.getCitation();
        if (null != cit) {
            Element elementCitation = doc.createElement("dcvalue");
            elementCitation.appendChild(doc.createTextNode(cit));
            rootElement.appendChild(elementCitation);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("citation");
            elementCitation.setAttributeNode(attr);
        }

        // Add the rights node:
        String rit = journalData.getRights();
        if (null != rit) {
            Element elementRights = doc.createElement("dcvalue");
            elementRights.appendChild(doc.createTextNode(rit));
            rootElement.appendChild(elementRights);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRights.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementRights.setAttributeNode(attr);
        }

        // Add the rights URI node:
        String ritUri = journalData.getRightsUri();
        if (null != ritUri) {
            Element elementRightsUri = doc.createElement("dcvalue");
            elementRightsUri.appendChild(doc.createTextNode(ritUri));
            rootElement.appendChild(elementRightsUri);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRightsUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRightsUri.setAttributeNode(attr);
        }

        // Add the rights requestable node:
        Element elementRightsRequestable = doc.createElement("dcvalue");
        elementRightsRequestable
                .appendChild(doc.createTextNode(Boolean.toString(journalData.isRightsRequestable())));
        rootElement.appendChild(elementRightsRequestable);

        attr = doc.createAttribute("element");
        attr.setValue("rights");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("requestable");
        elementRightsRequestable.setAttributeNode(attr);

        // Add the is part of node:
        String partOf = journalData.getIsPartOfSeries();
        if (null != partOf) {
            Element elementIsPartOf = doc.createElement("dcvalue");
            elementIsPartOf.appendChild(doc.createTextNode(partOf));
            rootElement.appendChild(elementIsPartOf);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementIsPartOf.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("ispartofseries");
            elementIsPartOf.setAttributeNode(attr);
        }

        // Add the relation uri node:
        String reUri = journalData.getRelationUri();
        if (null != reUri) {
            Element elementRelationUri = doc.createElement("dcvalue");
            elementRelationUri.appendChild(doc.createTextNode(reUri));
            rootElement.appendChild(elementRelationUri);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementRelationUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRelationUri.setAttributeNode(attr);
        }

        // Add the subject nodes:
        String[] subjectSet = journalData.getSubjects();
        if (null != subjectSet && subjectSet.length > 0) {
            for (String subject : subjectSet) {
                Element elementSubject = doc.createElement("dcvalue");
                elementSubject.appendChild(doc.createTextNode(subject));
                rootElement.appendChild(elementSubject);

                attr = doc.createAttribute("element");
                attr.setValue("subject");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("language");
                attr.setValue("en_US");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("none");
                elementSubject.setAttributeNode(attr);
            }
        }

        // Add the peerReview node:
        String review = journalData.getPeerReview();
        if (null != review) {
            Element elementPeerReview = doc.createElement("dcvalue");
            elementPeerReview.appendChild(doc.createTextNode(review));
            rootElement.appendChild(elementPeerReview);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreview");
            elementPeerReview.setAttributeNode(attr);
        }

        // Add the peer review notes node:
        String peer = journalData.getPeerReviewNotes();
        if (null != peer) {
            Element elementPeerReviewNotes = doc.createElement("dcvalue");
            elementPeerReviewNotes.appendChild(doc.createTextNode(peer));
            rootElement.appendChild(elementPeerReviewNotes);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreviewnotes");
            elementPeerReviewNotes.setAttributeNode(attr);
        }

        // Add the doi node:
        String doi = journalData.getDoi();
        if (null != doi) {
            Element elementDoi = doc.createElement("dcvalue");
            elementDoi.appendChild(doc.createTextNode(doi));
            rootElement.appendChild(elementDoi);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("doi");
            elementDoi.setAttributeNode(attr);
        }

        String folderPath = setOutputPath(fileName);
        String filePath = folderPath + "/dublin_core.xml";
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filePath));

        transformer.transform(source, result);

    } catch (ParserConfigurationException | TransformerException pce) {
        pce.printStackTrace();
    } catch (DOMException | BeansException e) {
        e.printStackTrace();
    }
}

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   w w w.ja va 2  s  .  c om
* 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:org.shareok.data.plosdata.PlosData.java

/**
 * Generate the metadata xml file/*ww w  .j ava 2 s.c  o m*/
 * @param fileName 
 */
public void exportXmlByDoiData(String fileName) {

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("dublin_core");
        doc.appendChild(rootElement);

        // Add the type node:
        Element element = doc.createElement("dcvalue");
        element.appendChild(doc.createTextNode("Research Article"));
        rootElement.appendChild(element);

        Attr attr = doc.createAttribute("element");
        attr.setValue("type");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("none");
        element.setAttributeNode(attr);

        // Add the abstract node:
        String abs = getAbstractText();
        if (null != abs) {
            Element elementAbs = doc.createElement("dcvalue");
            elementAbs.appendChild(doc.createTextNode(abs));
            rootElement.appendChild(elementAbs);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("abstract");
            elementAbs.setAttributeNode(attr);
        }

        // Add the language node:
        String lang = getLanguage();
        if (null != lang) {
            Element elementLang = doc.createElement("dcvalue");
            elementLang.appendChild(doc.createTextNode(lang));
            rootElement.appendChild(elementLang);

            attr = doc.createAttribute("element");
            attr.setValue("language");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("iso");
            elementLang.setAttributeNode(attr);
        }

        // Add the title node:
        String tit = getTitle();
        if (null != tit) {
            Element elementTitle = doc.createElement("dcvalue");
            elementTitle.appendChild(doc.createTextNode(tit));
            rootElement.appendChild(elementTitle);

            attr = doc.createAttribute("element");
            attr.setValue("title");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementTitle.setAttributeNode(attr);
        }

        // Add the available date node:
        //            Element elementAvailable = doc.createElement("dcvalue");
        //            elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString()));
        //            rootElement.appendChild(elementAvailable);
        //            
        //            attr = doc.createAttribute("element");
        //            attr.setValue("date");
        //            elementAvailable.setAttributeNode(attr);
        //            
        //            attr = doc.createAttribute("qualifier");
        //            attr.setValue("available");
        //            elementAvailable.setAttributeNode(attr);

        // Add the issued date node:
        Date issueDate = getDateIssued();
        if (null != issueDate) {
            SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd");
            Element elementIssued = doc.createElement("dcvalue");
            elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate)));
            rootElement.appendChild(elementIssued);

            attr = doc.createAttribute("element");
            attr.setValue("date");
            elementIssued.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("issued");
            elementIssued.setAttributeNode(attr);
        }

        // Add the author nodes:
        String[] authorSet = getAuthors();
        if (null != authorSet && authorSet.length > 0) {
            for (String author : authorSet) {
                Element elementAuthor = doc.createElement("dcvalue");
                elementAuthor.appendChild(doc.createTextNode(author));
                rootElement.appendChild(elementAuthor);

                attr = doc.createAttribute("element");
                attr.setValue("contributor");
                elementAuthor.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("author");
                elementAuthor.setAttributeNode(attr);
            }
        }

        // Add the acknowledgements node:
        String ack = getAcknowledgements();
        if (null != ack) {
            Element elementAck = doc.createElement("dcvalue");
            elementAck.appendChild(doc.createTextNode(ack));
            rootElement.appendChild(elementAck);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementAck.setAttributeNode(attr);
        }

        // Add the author contributions node:
        String contrib = getAuthorContributions();
        if (null != contrib) {
            Element elementContribution = doc.createElement("dcvalue");
            elementContribution.appendChild(doc.createTextNode(contrib));
            rootElement.appendChild(elementContribution);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementContribution.setAttributeNode(attr);
        }

        // Add the publisher node:
        String puber = getPublisher();
        if (null != puber) {
            Element elementPublisher = doc.createElement("dcvalue");
            elementPublisher.appendChild(doc.createTextNode(puber));
            rootElement.appendChild(elementPublisher);

            attr = doc.createAttribute("element");
            attr.setValue("publisher");
            elementPublisher.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementPublisher.setAttributeNode(attr);
        }

        // Add the citation node:
        String cit = getCitation();
        if (null != cit) {
            Element elementCitation = doc.createElement("dcvalue");
            elementCitation.appendChild(doc.createTextNode(cit));
            rootElement.appendChild(elementCitation);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("citation");
            elementCitation.setAttributeNode(attr);
        }

        // Add the rights node:
        String rit = getRights();
        if (null != rit) {
            Element elementRights = doc.createElement("dcvalue");
            elementRights.appendChild(doc.createTextNode(rit));
            rootElement.appendChild(elementRights);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRights.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementRights.setAttributeNode(attr);
        }

        // Add the rights URI node:
        String ritUri = getRightsUri();
        if (null != ritUri) {
            Element elementRightsUri = doc.createElement("dcvalue");
            elementRightsUri.appendChild(doc.createTextNode(ritUri));
            rootElement.appendChild(elementRightsUri);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRightsUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRightsUri.setAttributeNode(attr);
        }

        // Add the rights requestable node:
        Element elementRightsRequestable = doc.createElement("dcvalue");
        elementRightsRequestable.appendChild(doc.createTextNode(Boolean.toString(isRightsRequestable())));
        rootElement.appendChild(elementRightsRequestable);

        attr = doc.createAttribute("element");
        attr.setValue("rights");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("requestable");
        elementRightsRequestable.setAttributeNode(attr);

        // Add the is part of node:
        String partOf = getIsPartOfSeries();
        if (null != partOf) {
            Element elementIsPartOf = doc.createElement("dcvalue");
            elementIsPartOf.appendChild(doc.createTextNode(partOf));
            rootElement.appendChild(elementIsPartOf);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementIsPartOf.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("ispartofseries");
            elementIsPartOf.setAttributeNode(attr);
        }

        // Add the relation uri node:
        String reUri = getRelationUri();
        if (null != reUri) {
            Element elementRelationUri = doc.createElement("dcvalue");
            elementRelationUri.appendChild(doc.createTextNode(reUri));
            rootElement.appendChild(elementRelationUri);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementRelationUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRelationUri.setAttributeNode(attr);
        }

        // Add the subject nodes:
        String[] subjectSet = getSubjects();
        if (null != subjectSet && subjectSet.length > 0) {
            for (String subject : subjectSet) {
                Element elementSubject = doc.createElement("dcvalue");
                elementSubject.appendChild(doc.createTextNode(subject));
                rootElement.appendChild(elementSubject);

                attr = doc.createAttribute("element");
                attr.setValue("subject");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("language");
                attr.setValue("en_US");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("none");
                elementSubject.setAttributeNode(attr);
            }
        }

        // Add the peerReview node:
        String review = getPeerReview();
        if (null != review) {
            Element elementPeerReview = doc.createElement("dcvalue");
            elementPeerReview.appendChild(doc.createTextNode(review));
            rootElement.appendChild(elementPeerReview);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreview");
            elementPeerReview.setAttributeNode(attr);
        }

        // Add the peer review notes node:
        String peer = getPeerReviewNotes();
        if (null != peer) {
            Element elementPeerReviewNotes = doc.createElement("dcvalue");
            elementPeerReviewNotes.appendChild(doc.createTextNode(peer));
            rootElement.appendChild(elementPeerReviewNotes);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreviewnotes");
            elementPeerReviewNotes.setAttributeNode(attr);
        }

        // Add the doi node:
        String doi = getDoi();
        if (null != doi) {
            Element elementDoi = doc.createElement("dcvalue");
            elementDoi.appendChild(doc.createTextNode(doi));
            rootElement.appendChild(elementDoi);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("doi");
            elementDoi.setAttributeNode(attr);
        }

        // Generate the xml file:
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(fileName));

        transformer.transform(source, result);
    } catch (ParserConfigurationException | TransformerException pce) {
        pce.printStackTrace();
        System.exit(0);
    } catch (DOMException | BeansException e) {
        e.printStackTrace();
        System.exit(0);
    }
}

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

/**
* Sets IP Forwarding on a role./*from   ww  w .j  a  va  2 s.com*/
*
* @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:net.sf.jabref.logic.msbib.MSBibEntry.java

private Node getDOMrepresentation() {
    Node result = null;/*from  w w w .  ja v a  2  s.  c om*/
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        result = getDOMrepresentation(documentBuilder.newDocument());
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Could not create DocumentBuilder", e);
    }
    return result;
}

From source file:org.openmhealth.shim.healthvault.HealthvaultShim.java

@Override
public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException {
    final HealthVaultDataType healthVaultDataType;
    try {/*ww w.ja  v a2s  . c o  m*/
        healthVaultDataType = HealthVaultDataType
                .valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss");

    /***
     * Setup default date parameters
     */
    DateTime today = new DateTime();

    DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1)
            : shimDataRequest.getStartDate();
    String dateStart = startDate.toString(formatter);

    DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate();
    String dateEnd = endDate.toString(formatter);

    long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100
            : shimDataRequest.getNumToReturn();

    Request request = new Request();
    request.setMethodName("GetThings");
    request.setInfo("<info>" + "<group max=\"" + numToReturn + "\">" + "<filter>" + "<type-id>"
            + healthVaultDataType.getDataTypeId() + "</type-id>" + "<eff-date-min>" + dateStart
            + "</eff-date-min>" + "<eff-date-max>" + dateEnd + "</eff-date-max>" + "</filter>" + "<format>"
            + "<section>core</section>" + "<xml/>" + "</format>" + "</group>" + "</info>");

    RequestTemplate template = new RequestTemplate(connection);
    return template.makeRequest(shimDataRequest.getAccessParameters(), request,
            new Marshaller<ShimDataResponse>() {
                public ShimDataResponse marshal(InputStream istream) throws Exception {

                    /**
                     * XML Document mappings to JSON don't respect repeatable
                     * tags, they don't get properly serialized into collections.
                     * Thus, we pickup the 'things' via the 'group' root tag
                     * and create a new JSON document out of each 'thing' node.
                     */
                    XmlMapper xmlMapper = new XmlMapper();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(istream);
                    NodeList nodeList = doc.getElementsByTagName("thing");

                    /**
                     * Collect JsonNode from each 'thing' xml node.
                     */
                    List<JsonNode> thingList = new ArrayList<>();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        Document thingDoc = builder.newDocument();
                        Node newNode = thingDoc.importNode(node, true);
                        thingDoc.appendChild(newNode);
                        thingList.add(xmlMapper.readTree(convertDocumentToString(thingDoc)));
                    }

                    /**
                     * Rebuild JSON document structure to pass to deserializer.
                     */
                    String thingsJson = "{\"things\":[";
                    String thingsContent = "";
                    for (JsonNode thingNode : thingList) {
                        thingsContent += thingNode.toString() + ",";
                    }
                    thingsContent = "".equals(thingsContent) ? thingsContent
                            : thingsContent.substring(0, thingsContent.length() - 1);
                    thingsJson += thingsContent;
                    thingsJson += "]}";

                    /**
                     * Return raw re-built 'things' or a normalized JSON document.
                     */
                    ObjectMapper objectMapper = new ObjectMapper();
                    if (shimDataRequest.getNormalize()) {
                        SimpleModule module = new SimpleModule();
                        module.addDeserializer(ShimDataResponse.class, healthVaultDataType.getNormalizer());
                        objectMapper.registerModule(module);
                        return objectMapper.readValue(thingsJson, ShimDataResponse.class);
                    } else {
                        return ShimDataResponse.result(HealthvaultShim.SHIM_KEY,
                                objectMapper.readTree(thingsJson));
                    }
                }
            });
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue) {

    try {/* w  ww.  j a  va  2s .c om*/

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);

        DOMXMLSignature domSig = createSignature(parameters, doc, document, signContext, signatureValueId);

        String xpathString = "//ds:SignatureValue[@Id='" + signatureValueId + "']";
        Element signatureValueEl = XMLUtils.getElement(doc, xpathString);

        if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.ECDSA) {
            signatureValueEl.setTextContent(
                    new String(Base64.encode(SignatureECDSA.convertASN1toXMLDSIG(signatureValue))));
        } else if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.DSA) {
            signatureValueEl.setTextContent(new String(Base64.encode(convertASN1toXMLDSIG(signatureValue))));
        } else {
            signatureValueEl.setTextContent(new String(Base64.encode(signatureValue)));
        }

        UnsignedPropertiesType unsigned = createUnsignedXAdESProperties(parameters, domSig, null,
                signatureValueEl);
        if (unsigned != null) {
            JAXBContext xadesJaxbContext = JAXBContext.newInstance(getXades13ObjectFactory().getClass());
            Marshaller m = xadesJaxbContext.createMarshaller();
            JAXBElement<UnsignedPropertiesType> el = getXades13ObjectFactory()
                    .createUnsignedProperties(unsigned);
            m.marshal(el, getXAdESQualifyingProperties(parameters, doc));
        }

        /* Output document */
        ByteArrayOutputStream outputDoc = new ByteArrayOutputStream();
        Result output = new StreamResult(outputDoc);
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        Source source = new DOMSource(doc);
        xformer.transform(source, output);
        outputDoc.close();

        return new InMemoryDocument(outputDoc.toByteArray());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

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

/**
* Sets IP Forwarding on a network interface.
*
* @param serviceName Required./*from   w w  w .j av a  2  s . com*/
* @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();
        }
    }
}