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:DOMProcessor.java

/** Reads the given XML file and converts it into a DOM.
  * @param fileName Name of XML file to convert.
  * @return True if converted successfully.
  *//*from   w w w . j  a v  a 2s . c om*/
public boolean readXML(String fileName) {
    // Create a DocumentBuilder using the DocumentBuilderFactory.
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    indent = 0;

    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        System.err.println("Problem finding an XML parser:\n" + e);
        return false;
    }

    // Try to parse the given file and store XML nodes in the DOM. 
    try {
        dom = db.parse(new File(fileName));
    } catch (SAXException e) {
        System.err.println("Problem parsing document: " + e.getMessage());
        dom = db.newDocument();
        return false;
    } catch (IOException e) {
        System.err.println("Problem reading " + fileName);
        return false;
    }
    return true;
}

From source file:curam.molsa.test.customfunctions.MOLSADOMReader.java

/**
 * Transforms an inbound DOM document according to a specific stylesheet.
 * /*  ww  w  . ja  v a 2  s  . c om*/
 * @param document
 * Contains the Inbound DOM document.
 * @param stylesheet
 * The file location of the stylesheet use to transform the document
 * @param rootElement
 * The expected root element of the transformed document
 * @return The transformed document
 */
public Document transformDocumentBasedOnXSL(final Document document, final String stylesheet,
        final String responseRootElement) throws ParserConfigurationException, SAXException, IOException {

    String xmlString = "";
    Document transformedDocument = null;
    final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    dbfac.setNamespaceAware(true);
    final DocumentBuilder builder = dbfac.newDocumentBuilder();

    try {
        final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(stylesheet);

        final Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(new StreamSource(inputStream));
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        final StringWriter stringWriter = new StringWriter();
        final StreamResult streamResult = new StreamResult(stringWriter);
        final DOMSource source = new DOMSource(document);
        transformer.transform(source, streamResult);
        xmlString = stringWriter.toString();

        if (xmlString.contains(responseRootElement)) {
            transformedDocument = builder.parse(new InputSource(new StringReader(xmlString)));
        } else {
            transformedDocument = builder.newDocument();
        }

    } catch (final TransformerConfigurationException tcExp) {
        tcExp.printStackTrace();
    } catch (final TransformerException tExp) {
        tExp.printStackTrace();
    }
    return transformedDocument;
}

From source file:com.photon.phresco.framework.rest.api.RepositoryService.java

private static Document constructGitTree(List<String> branchList, List<String> tagLists, String url,
        String appDirName) throws PhrescoException {
    try {//from   w w w.  j a v  a  2s  .c  o m
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
        Document doc = documentBuilder.newDocument();

        Element rootElement = doc.createElement(ROOT);
        doc.appendChild(rootElement);

        Element rootItem = doc.createElement(ITEM);
        rootItem.setAttribute(TYPE, FOLDER);
        rootItem.setAttribute(NAME, ROOT_ITEM);

        rootElement.appendChild(rootItem);

        Element urlItem = doc.createElement(ITEM);
        urlItem.setAttribute(TYPE, FOLDER);
        urlItem.setAttribute(NAME, url);

        rootItem.appendChild(urlItem);

        Element branchItem = doc.createElement(ITEM);
        branchItem.setAttribute(TYPE, FOLDER);
        branchItem.setAttribute(NAME, BRANCHES);
        branchItem.setAttribute(URL, url);
        urlItem.appendChild(branchItem);

        for (String branch : branchList) {
            String branchName = branch.substring(branch.lastIndexOf("/") + 1, branch.length());
            Element branchItems = doc.createElement(ITEM);
            branchItems.setAttribute(TYPE, FILE);
            branchItems.setAttribute(NAME, branchName);
            branchItems.setAttribute(URL, url);
            branchItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            branchItems.setAttribute(NATURE, BRANCHES);
            branchItem.appendChild(branchItems);
        }

        Element tagItem = doc.createElement(ITEM);
        tagItem.setAttribute(TYPE, FOLDER);
        tagItem.setAttribute(NAME, TAGS);
        tagItem.setAttribute(URL, url);
        urlItem.appendChild(tagItem);

        for (String tag : tagLists) {
            Element tagItems = doc.createElement(ITEM);
            tagItems.setAttribute(TYPE, FILE);
            tagItems.setAttribute(NAME, tag);
            tagItems.setAttribute(URL, url);
            tagItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            tagItems.setAttribute(NATURE, TAGS);
            tagItem.appendChild(tagItems);
        }

        return doc;
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    }
}

From source file:com.krawler.formbuilder.servlet.workflowHandler.java

private void createDocument() throws ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    dom = db.newDocument();
}

From source file:com.photon.phresco.framework.rest.api.RepositoryService.java

private static Document constructSvnTree(Map<String, List<String>> list, String url, String appDirName)
        throws PhrescoException {
    try {//from ww w  .  j  a va2  s . c o m
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
        Document doc = documentBuilder.newDocument();

        Element rootElement = doc.createElement(ROOT);
        doc.appendChild(rootElement);

        Element rootItem = doc.createElement(ITEM);
        rootItem.setAttribute(TYPE, FOLDER);
        rootItem.setAttribute(NAME, ROOT_ITEM);

        rootElement.appendChild(rootItem);

        Element urlItem = doc.createElement(ITEM);
        urlItem.setAttribute(TYPE, FOLDER);
        urlItem.setAttribute(NAME, url);

        rootItem.appendChild(urlItem);

        Element branchItem = doc.createElement(ITEM);
        branchItem.setAttribute(TYPE, FOLDER);
        branchItem.setAttribute(NAME, BRANCHES);
        branchItem.setAttribute(URL, url);
        urlItem.appendChild(branchItem);

        Element tagItem = doc.createElement(ITEM);
        tagItem.setAttribute(TYPE, FOLDER);
        tagItem.setAttribute(NAME, TAGS);
        tagItem.setAttribute(URL, url);
        urlItem.appendChild(tagItem);

        Element trunkItem = doc.createElement(ITEM);
        trunkItem.setAttribute(TYPE, FOLDER);
        trunkItem.setAttribute(NAME, TRUNK);
        trunkItem.setAttribute(URL, url);
        urlItem.appendChild(trunkItem);

        List<String> trunkList = list.get(TRUNK);
        for (String trunk : trunkList) {
            Element trunkItems = doc.createElement(ITEM);
            trunkItems.setAttribute(NAME, trunk);
            trunkItems.setAttribute(URL, url);
            trunkItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            trunkItems.setAttribute(NATURE, TRUNK);
            trunkItem.appendChild(trunkItems);
        }

        List<String> branchList = list.get(BRANCHES);
        for (String branch : branchList) {
            Element branchItems = doc.createElement(ITEM);
            branchItems.setAttribute(NAME, branch);
            branchItems.setAttribute(URL, url);
            branchItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            branchItems.setAttribute(NATURE, BRANCHES);
            branchItem.appendChild(branchItems);
        }

        List<String> tagList = list.get(TAGS);
        for (String tag : tagList) {
            Element tagItems = doc.createElement(ITEM);
            tagItems.setAttribute(NAME, tag);
            tagItems.setAttribute(URL, url);
            tagItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            tagItems.setAttribute(NATURE, TAGS);
            tagItem.appendChild(tagItems);
        }

        return doc;
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    }
}

From source file:com.microsoft.windowsazure.management.websites.ServerFarmOperationsImpl.java

/**
* You can create a server farm by issuing an HTTP POST request. Only one
* server farm per webspace is permitted. You can retrieve server farm
* details by using HTTP GET, change server farm properties by using HTTP
* PUT, and delete a server farm by using HTTP DELETE. A request body is
* required for server farm creation (HTTP POST) and server farm update
* (HTTP PUT). Warning: Creating a server farm changes your webspace's
* Compute Mode from Shared to Dedicated. You will be charged from the
* moment the server farm is created, even if all your sites are still
* running in Free mode.  (see//from   w  w  w.  j av a 2s  .  c  o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Parameters supplied to the Create Server Farm
* 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create Server Farm operation response.
*/
@Override
public ServerFarmCreateResponse create(String webSpaceName, ServerFarmCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
    }

    // Construct URL
    String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null
            ? this.getClient().getCredentials().getSubscriptionId().trim()
            : "") + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms";
    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;

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

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

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

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

    if (parameters.getCurrentNumberOfWorkers() != null) {
        Element currentNumberOfWorkersElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
        currentNumberOfWorkersElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers())));
        serverFarmElement.appendChild(currentNumberOfWorkersElement);
    }

    if (parameters.getCurrentWorkerSize() != null) {
        Element currentWorkerSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
        currentWorkerSizeElement
                .appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString()));
        serverFarmElement.appendChild(currentWorkerSizeElement);
    }

    Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
    nameElement.appendChild(requestDoc.createTextNode("DefaultServerFarm"));
    serverFarmElement.appendChild(nameElement);

    Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "NumberOfWorkers");
    numberOfWorkersElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
    serverFarmElement.appendChild(numberOfWorkersElement);

    Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "WorkerSize");
    workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
    serverFarmElement.appendChild(workerSizeElement);

    if (parameters.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Status");
        statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
        serverFarmElement.appendChild(statusElement);
    }

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

        // Create Result
        ServerFarmCreateResponse result = null;
        // Deserialize Response
        InputStream responseContent = httpResponse.getEntity().getContent();
        result = new ServerFarmCreateResponse();
        DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
        documentBuilderFactory2.setNamespaceAware(true);
        DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
        Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

        Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                "http://schemas.microsoft.com/windowsazure", "ServerFarm");
        if (serverFarmElement2 != null) {
            Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
            if (currentNumberOfWorkersElement2 != null) {
                int currentNumberOfWorkersInstance;
                currentNumberOfWorkersInstance = DatatypeConverter
                        .parseInt(currentNumberOfWorkersElement2.getTextContent());
                result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
            }

            Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
            if (currentWorkerSizeElement2 != null) {
                ServerFarmWorkerSize currentWorkerSizeInstance;
                currentWorkerSizeInstance = ServerFarmWorkerSize
                        .valueOf(currentWorkerSizeElement2.getTextContent());
                result.setCurrentWorkerSize(currentWorkerSizeInstance);
            }

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

            Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
            if (numberOfWorkersElement2 != null) {
                int numberOfWorkersInstance;
                numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent());
                result.setNumberOfWorkers(numberOfWorkersInstance);
            }

            Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "WorkerSize");
            if (workerSizeElement2 != null) {
                ServerFarmWorkerSize workerSizeInstance;
                workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent());
                result.setWorkerSize(workerSizeInstance);
            }

            Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Status");
            if (statusElement2 != null) {
                ServerFarmStatus statusInstance;
                statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent());
                result.setStatus(statusInstance);
            }
        }

        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.websites.ServerFarmOperationsImpl.java

/**
* You can create a server farm by issuing an HTTP POST request. Only one
* server farm per webspace is permitted. You can retrieve server farm
* details by using HTTP GET, change server farm properties by using HTTP
* PUT, and delete a server farm by using HTTP DELETE. A request body is
* required for server farm creation (HTTP POST) and server farm update
* (HTTP PUT). Warning: Creating a server farm changes your webspace's
* Compute Mode from Shared to Dedicated. You will be charged from the
* moment the server farm is created, even if all your sites are still
* running in Free mode.  (see/*ww w  .j a  v a2 s.  c o  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Parameters supplied to the Update Server Farm
* 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Update Server Farm operation response.
*/
@Override
public ServerFarmUpdateResponse update(String webSpaceName, ServerFarmUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
    }

    // Construct URL
    String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null
            ? this.getClient().getCredentials().getSubscriptionId().trim()
            : "") + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms/DefaultServerFarm";
    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;

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

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

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

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

    if (parameters.getCurrentNumberOfWorkers() != null) {
        Element currentNumberOfWorkersElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
        currentNumberOfWorkersElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers())));
        serverFarmElement.appendChild(currentNumberOfWorkersElement);
    }

    if (parameters.getCurrentWorkerSize() != null) {
        Element currentWorkerSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
        currentWorkerSizeElement
                .appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString()));
        serverFarmElement.appendChild(currentWorkerSizeElement);
    }

    Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
    nameElement.appendChild(requestDoc.createTextNode("DefaultServerFarm"));
    serverFarmElement.appendChild(nameElement);

    Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "NumberOfWorkers");
    numberOfWorkersElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
    serverFarmElement.appendChild(numberOfWorkersElement);

    Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "WorkerSize");
    workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
    serverFarmElement.appendChild(workerSizeElement);

    if (parameters.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Status");
        statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
        serverFarmElement.appendChild(statusElement);
    }

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

        // Create Result
        ServerFarmUpdateResponse result = null;
        // Deserialize Response
        InputStream responseContent = httpResponse.getEntity().getContent();
        result = new ServerFarmUpdateResponse();
        DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
        documentBuilderFactory2.setNamespaceAware(true);
        DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
        Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

        Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                "http://schemas.microsoft.com/windowsazure", "ServerFarm");
        if (serverFarmElement2 != null) {
            Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
            if (currentNumberOfWorkersElement2 != null) {
                int currentNumberOfWorkersInstance;
                currentNumberOfWorkersInstance = DatatypeConverter
                        .parseInt(currentNumberOfWorkersElement2.getTextContent());
                result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
            }

            Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
            if (currentWorkerSizeElement2 != null) {
                ServerFarmWorkerSize currentWorkerSizeInstance;
                currentWorkerSizeInstance = ServerFarmWorkerSize
                        .valueOf(currentWorkerSizeElement2.getTextContent());
                result.setCurrentWorkerSize(currentWorkerSizeInstance);
            }

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

            Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
            if (numberOfWorkersElement2 != null) {
                int numberOfWorkersInstance;
                numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent());
                result.setNumberOfWorkers(numberOfWorkersInstance);
            }

            Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "WorkerSize");
            if (workerSizeElement2 != null) {
                ServerFarmWorkerSize workerSizeInstance;
                workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent());
                result.setWorkerSize(workerSizeInstance);
            }

            Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Status");
            if (statusElement2 != null) {
                ServerFarmStatus statusInstance;
                statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent());
                result.setStatus(statusInstance);
            }
        }

        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:it.txt.access.capability.revocation.test.RevocationServiceTest.java

@Test
public void testPost()
        throws UnsupportedEncodingException, IOException, JAXBException, ParserConfigurationException,
        NullPointerException, CapabilitySchemaFactoryException, CapabilitySchemaValidationHandlerException,
        DatatypeConfigurationException, GeneralSecurityException, InterruptedException {
    IoTTestForPOST testa = new IoTTestForPOST();

    System.out.println("**********************************************************");
    System.out.println("*               CRP450 : CERTIFCATo                      *");
    System.out.println("**********************************************************");

    StringEntity input = new StringEntity(readFileAsString(System.getProperty("REVOCATION_FIRST")));
    String result = testa.testPost(input);
    assertEquals(StatusCode.CRP450, result);

    System.out.println("**********************************************************");
    System.out.println("*               CRP451 : MISSING ID                      *");
    System.out.println("**********************************************************");

    StringEntity input0 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP451")));
    String result0 = testa.testPost(input0);
    assertEquals(StatusCode.CRP451, result0);

    System.out.println("**********************************************************");
    System.out.println("*               CRP452 : MISSING ISSUER                  *");
    System.out.println("**********************************************************");

    StringEntity input1 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP452")));
    String result1 = testa.testPost(input1);
    assertEquals(StatusCode.CRP452, result1);

    System.out.println("************************************************************************************");
    System.out.println("*CRP453 : BAD ISSUER(the capRev issuer must be the subject of the authorising auCap*");
    System.out.println("************************************************************************************");

    StringEntity input2 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP453")));
    String result2 = testa.testPost(input2);
    assertEquals(StatusCode.CRP453, result2);

    System.out.println("************************************************************************************");
    System.out.println("*         CRP454 : BAD AUTHORISING CAPABILITY(w.r.t. the syntactic validity        *");
    System.out.println("************************************************************************************");

    StringEntity input3 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP454")));
    String result3 = testa.testPost(input3);
    assertEquals(StatusCode.CRP454, result3);
    ///* ww w  .  jav  a 2s  . com*/
    // //
    // System.out.println("************************************************************************************");
    // //
    // //
    // System.out.println("*        CRP455 : BAD SIGNER (the capRev issuer must be the certificate signer)    *");
    // //
    // //
    // System.out.println("************************************************************************************");
    //
    System.out.println("************************************************************************************");
    System.out.println("*                        CRP456 : BAD VALIDITY TIME FRAME                          *");
    System.out.println("************************************************************************************");

    StringEntity input5 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP456")));
    String result5 = testa.testPost(input5);
    assertEquals(StatusCode.CRP456, result5);

    System.out.println(
            "********************************************************************************************************************");
    System.out.println(
            "*CRP457 : BAD REVOKED (this happens when the revoked auCap is the same  revocation or resolving its pending status)*");
    System.out.println(
            "********************************************************************************************************************");

    StringEntity input6 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP457")));
    String result6 = testa.testPost(input6);
    assertEquals(StatusCode.CRP457, result6);

    System.out.println("************************************************************************************");
    System.out.println("*                   CRP458 : EXIPERED AUTHORISING CAPABILITY                       *");
    System.out.println("************************************************************************************");

    //create two capability with the 
    String revID = null;
    try {
        // Required initialization
        CapabilitySchemasLoader loader = new CapabilitySchemasLoader(null);
        String schemasPath = System.getProperty("PATH_CAPABILITY_SCHEMA");
        loader.loadCapabilityEntities(schemasPath);
        CapabilitySchemaFactory.getInstance(schemasPath);

        creator = new RevocationCreationByHand();
        creator.setAuthorisingCapability(new File(System.getProperty("AUCAP_CRP458")));
        creator.setAuthorisingCapabilityExpiration(new Date(new Date().getTime() + 2000));
        creator.setCertificatePsw(new char[] { 's', 'y', 's', 'm', 'g', 'r' });
        creator.setKeystore(new File(System.getProperty("KEYSTORE")));
        creator.setKeystorePsw(new char[] { 's', 'y', 's', 'm', 'g', 'r' });
        creator.setNotificationEmail("donato.andrisani@network.txtgroup.com");
        creator.setReason("Why? Because...");
        creator.setRevocationScope("ALL");
        creator.setRevokedCapability(new File(System.getProperty("REVCAP_CRP458")));
        creator.setRevokedCapabilityExpiration(new Date(new Date().getTime() + 10000));
        creator.setRevokedSinceDateTime(new Date());

        CreatedTokens tokens = creator.createRevocation();

        JAXBContext context = JAXBContext.newInstance(AccessRightsCapabilityType.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CapabilityNamespacesMapper());
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        System.out.println("#####----- Modified authorising capability -----#####");
        Document xmlDocument = docBuilder.newDocument();
        marshaller.marshal(tokens.getAuthorisingCapability(), xmlDocument);
        assertTrue("The signature of the authorising capability is not valid!",
                X509DocumentSigner.verifyXMLElementSign(xmlDocument.getDocumentElement()));
        System.out.println(XMLPrinter.printDocumentElement(xmlDocument.getDocumentElement(), true));
        System.out.println("#####--------------- ---------------#####\n\n");

        System.out.println("#####----- Modified revoked capability -----#####");
        xmlDocument = docBuilder.newDocument();
        marshaller.marshal(tokens.getRevokedCapability(), xmlDocument);
        assertTrue("The signature of the revoked capability is not valid!",
                X509DocumentSigner.verifyXMLElementSign(xmlDocument.getDocumentElement()));
        System.out.println(XMLPrinter.printDocumentElement(xmlDocument.getDocumentElement(), true));
        System.out.println("#####--------------- ---------------#####\n\n");

        context = JAXBContext.newInstance(CapabilityRevocationType.class);
        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CapabilityNamespacesMapper());
        System.out.println("#####----- Revocation -----#####");
        xmlDocument = docBuilder.newDocument();
        marshaller.marshal(tokens.getRevocationToken(), xmlDocument);
        assertTrue("The signature of the revocation is not valid!",
                X509DocumentSigner.verifyXMLElementSign(xmlDocument.getDocumentElement()));
        System.out.println(XMLPrinter.printDocumentElement(xmlDocument.getDocumentElement(), true));
        System.out.println("#####--------------- ---------------#####");
        DataMapper insertCapability = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"),
                System.getProperty("USER"), System.getProperty("PSW"), tokens.getAuthorisingCapability());
        DataMapper insertCapability1 = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"),
                System.getProperty("USER"), System.getProperty("PSW"), tokens.getRevokedCapability());
        context = JAXBContext.newInstance(CapabilityRevocationType.class);
        revID = tokens.getRevocationToken().getRevocationID();

        Writer writer = new FileWriter(
                "D:/PC-DONATO/workspace/RevocationService/revocationTest/revocationPOSTTest/output_458.xml");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CapabilityNamespacesMapper());
        try {
            marshaller.marshal(tokens.getRevocationToken(), writer);
            System.out.println("CREATO FILE");
        } finally {
            writer.close();
        }
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (CapabilitySchemaFactoryException e) {
        e.printStackTrace();
    } catch (CapabilitySchemaValidationHandlerException e) {
        e.printStackTrace();
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }

    StringEntity input7 = new StringEntity(readFileAsString(System.getProperty("OUTPUT_458")));
    String result7 = testa.testPost(input7);
    Thread.sleep(4000);
    PendingRevocationsManagement p = new PendingRevocationsManagement();
    p.processPendingCapabilityRevocation();

    ODatabaseDocumentTx capRevDb = new ODatabaseDocumentTx(Constants.revocationDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);

    String querySelRev = "select statusCode, status from " + Constants.REVOCATION_CLASS + " where "
            + Constants.REVOCATION_ID + " = '" + revID + "'";
    List<ODocument> rev = capRevDb.command(new OCommandSQL(querySelRev)).execute();
    ODocument element = rev.get(0);
    assertEquals(element.field(Constants.STATUS), "REJECTED");

    assertEquals(element.field(Constants.STATUS_CODE), StatusCode.CRP458);

    ODatabaseDocumentTx auCapDb = new ODatabaseDocumentTx(Constants.capabilityDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);

    String querySelPen = "select statusCode, status, resolvedOn from " + Constants.PENDING_CLASS + " where "
            + Constants.REVOCATION_ID + " = '" + revID + "'";

    List<ODocument> pen = auCapDb.command(new OCommandSQL(querySelPen)).execute();
    ODocument element0 = pen.get(0);

    assertEquals(element0.field(Constants.STATUS), "REJECTED");
    assertEquals(element0.field(Constants.STATUS_CODE), StatusCode.CRP458);
    assertNotNull(element0.field(Constants.RESOLVED_ON));

    create.clearAll();

    System.out.println("************************************************************************************");
    System.out.println("*                   CRP459 : EXPIRED REVOKED CAPABILITY                            *");
    System.out.println("************************************************************************************");

    try {
        // Required initialization
        CapabilitySchemasLoader loader = new CapabilitySchemasLoader(null);
        String schemasPath = System.getProperty("PATH_CAPABILITY_SCHEMA");
        loader.loadCapabilityEntities(schemasPath);
        CapabilitySchemaFactory.getInstance(schemasPath);

        creator = new RevocationCreationByHand();
        creator.setAuthorisingCapability(new File(System.getProperty("AUCAP_CRP458")));
        creator.setAuthorisingCapabilityExpiration(new Date(new Date().getTime() + 10000));
        creator.setCertificatePsw(new char[] { 's', 'y', 's', 'm', 'g', 'r' });
        creator.setKeystore(new File(System.getProperty("KEYSTORE")));
        creator.setKeystorePsw(new char[] { 's', 'y', 's', 'm', 'g', 'r' });
        creator.setNotificationEmail("alice@acme.com");
        creator.setReason("Why? Because...");
        creator.setRevocationScope("ALL");
        creator.setRevokedCapability(new File(System.getProperty("REVCAP_CRP458")));
        creator.setRevokedCapabilityExpiration(new Date(new Date().getTime() + 1000));
        creator.setRevokedSinceDateTime(new Date());

        CreatedTokens tokens = creator.createRevocation();

        JAXBContext context = JAXBContext.newInstance(AccessRightsCapabilityType.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CapabilityNamespacesMapper());
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        System.out.println("#####----- Modified authorising capability -----#####");
        Document xmlDocument = docBuilder.newDocument();
        marshaller.marshal(tokens.getAuthorisingCapability(), xmlDocument);
        assertTrue("The signature of the authorising capability is not valid!",
                X509DocumentSigner.verifyXMLElementSign(xmlDocument.getDocumentElement()));
        System.out.println(XMLPrinter.printDocumentElement(xmlDocument.getDocumentElement(), true));
        System.out.println("#####--------------- ---------------#####\n\n");

        System.out.println("#####----- Modified revoked capability -----#####");
        xmlDocument = docBuilder.newDocument();
        marshaller.marshal(tokens.getRevokedCapability(), xmlDocument);
        assertTrue("The signature of the revoked capability is not valid!",
                X509DocumentSigner.verifyXMLElementSign(xmlDocument.getDocumentElement()));
        System.out.println(XMLPrinter.printDocumentElement(xmlDocument.getDocumentElement(), true));
        System.out.println("#####--------------- ---------------#####\n\n");

        context = JAXBContext.newInstance(CapabilityRevocationType.class);
        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CapabilityNamespacesMapper());
        System.out.println("#####----- Revocation -----#####");
        xmlDocument = docBuilder.newDocument();
        marshaller.marshal(tokens.getRevocationToken(), xmlDocument);
        assertTrue("The signature of the revocation is not valid!",
                X509DocumentSigner.verifyXMLElementSign(xmlDocument.getDocumentElement()));
        System.out.println(XMLPrinter.printDocumentElement(xmlDocument.getDocumentElement(), true));
        System.out.println("#####--------------- ---------------#####");

        OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false);
        OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false);
        DataMapper insertCapability = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"),
                System.getProperty("USER"), System.getProperty("PSW"), tokens.getAuthorisingCapability());
        DataMapper insertCapability1 = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"),
                System.getProperty("USER"), System.getProperty("PSW"), tokens.getRevokedCapability());

        context = JAXBContext.newInstance(CapabilityRevocationType.class);
        revID = tokens.getRevocationToken().getRevocationID();

        Writer writer = new FileWriter(
                "D:/PC-DONATO/workspace/RevocationService/revocationTest/revocationPOSTTest/output_459.xml");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CapabilityNamespacesMapper());
        try {
            marshaller.marshal(tokens.getRevocationToken(), writer);
            System.out.println("CREATO FILE");
        } finally {
            writer.close();
        }
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (CapabilitySchemaFactoryException e) {
        e.printStackTrace();
    } catch (CapabilitySchemaValidationHandlerException e) {
        e.printStackTrace();
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }

    StringEntity input8 = new StringEntity(readFileAsString(System.getProperty("OUTPUT_459")));
    String result8 = testa.testPost(input8);

    Thread.sleep(5000);
    //      PendingRevocationsManagement p  = new PendingRevocationsManagement();
    p.processPendingCapabilityRevocation();

    capRevDb = new ODatabaseDocumentTx(Constants.revocationDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);

    querySelRev = "select statusCode, status from " + Constants.REVOCATION_CLASS + " where "
            + Constants.REVOCATION_ID + " = '" + revID + "'";
    rev = capRevDb.command(new OCommandSQL(querySelRev)).execute();
    element = rev.get(0);
    assertEquals(element.field(Constants.STATUS), "REJECTED");
    assertEquals(element.field(Constants.STATUS_CODE), StatusCode.CRP459);

    auCapDb = new ODatabaseDocumentTx(Constants.capabilityDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);

    querySelPen = "select statusCode, status, resolvedOn from " + Constants.PENDING_CLASS + " where "
            + Constants.REVOCATION_ID + " = '" + revID + "'";

    pen = auCapDb.command(new OCommandSQL(querySelPen)).execute();
    element0 = pen.get(0);
    assertEquals(element0.field(Constants.STATUS), "REJECTED");
    assertEquals(element0.field(Constants.STATUS_CODE), StatusCode.CRP459);
    assertNotNull(element0.field(Constants.RESOLVED_ON));
    assertEquals(StatusCode.CRP459, RevocationOutCome.code);

    create.clearAll();

    System.out.println("************************************************************************************");
    System.out.println("*      CRP400 : BAD REVOCATION (w.r.t. the compliance with the XML SCHEMA)         *");
    System.out.println("************************************************************************************");

    StringEntity input9 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP400")));
    String result9 = testa.testPost(input9);
    assertEquals(StatusCode.CRP400, result9);

    System.out.println(
            "**********************************************************************************************************");
    System.out.println(
            "*CRP403 : FORBIDDEN(AFTER RESOLUTION: the authorising auCAp has not the right thr revoke the given auCap)*");
    System.out.println(
            "**********************************************************************************************************");

    StreamSource xml = new StreamSource(System.getProperty("CAPABILITY1"));
    AccessRightsCapabilityType aucap = unMarshall(xml);
    DataMapper insertCapability = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"),
            System.getProperty("USER"), System.getProperty("PSW"), aucap);

    xml = new StreamSource(System.getProperty("CAPABILITY2"));
    aucap = unMarshall(xml);
    insertCapability = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"), System.getProperty("USER"),
            System.getProperty("PSW"), aucap);

    StringEntity input10 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP403")));
    String result10 = testa.testPost(input10);

    Thread.sleep(4000);

    p.processPendingCapabilityRevocation();
    assertEquals(StatusCode.CRP403, RevocationOutCome.code);

    insertCapability.clearAll();

    System.out.println(
            "**********************************************************************************************************");
    System.out.println(
            "*                                         CRP201 : ACCEPTED (side POST)                                  *");
    System.out.println(
            "**********************************************************************************************************");

    StringEntity input11 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP201")));
    String result11 = testa.testPost(input11);
    assertEquals(StatusCode.CRP202, result11);

    create.clearAll();

    System.out.println(
            "**********************************************************************************************************");
    System.out.println(
            "*                                         CRP409 : DUPLICATED                                            *");
    System.out.println(
            "**********************************************************************************************************");

    StringEntity prov = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP409")));
    String test = testa.testPost(prov);
    assertEquals(StatusCode.CRP202, test);

    System.out.println(
            "**********************************************************************************************************");
    System.out.println(
            "*                                         CRP201 : ACCEPTED (side RESOLUTION PENDING)                    *");
    System.out.println(
            "**********************************************************************************************************");

    xml = new StreamSource(System.getProperty("CAPABILITY22"));
    aucap = unMarshall(xml);
    insertCapability = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"), System.getProperty("USER"),
            System.getProperty("PSW"), aucap);

    xml = new StreamSource(System.getProperty("CAPABILITY33"));
    aucap = unMarshall(xml);
    insertCapability = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"), System.getProperty("USER"),
            System.getProperty("PSW"), aucap);

    input11 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP201")));
    result11 = testa.testPost(input11);
    Thread.sleep(4000);
    p.processPendingCapabilityRevocation();
    assertEquals(StatusCode.CRP201, RevocationOutCome.code);

    capRevDb = new ODatabaseDocumentTx(Constants.revocationDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);

    querySelRev = "select statusCode, status  from " + Constants.REVOCATION_CLASS + " where "
            + Constants.REVOCATION_ID + " = '_e49af3ee828b03a32c39df493cf4c674'";
    rev = capRevDb.command(new OCommandSQL(querySelRev)).execute();
    element = rev.get(0);

    assertEquals(element.field(Constants.STATUS), "ACCEPTED");
    assertEquals(element.field(Constants.STATUS_CODE), StatusCode.CRP201);

    auCapDb = new ODatabaseDocumentTx(Constants.capabilityDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);
    String queryPend = "select statusCode, status, capabilityID, resolvedOn  from " + Constants.PENDING_CLASS
            + " where " + Constants.REVOCATION_ID + " = '_e49af3ee828b03a32c39df493cf4c674'";
    List<ODocument> res = auCapDb.command(new OCommandSQL(queryPend)).execute();
    ODocument elem = res.get(0);

    String Revoked_Index_Sel = "select from index:" + Constants.REVOKED_INDEX_NAME;
    List<ODocument> Revoked_Index = auCapDb.command(new OCommandSQL(Revoked_Index_Sel)).execute();

    assertEquals(elem.field(Constants.STATUS), "ACCEPTED");
    assertEquals(elem.field(Constants.STATUS_CODE), StatusCode.CRP201);
    assertNotNull(elem.field(Constants.RESOLVED_ON));
    assertNotNull(Revoked_Index);

    System.out.println(
            "**********************************************************************************************************");
    System.out.println(
            "*                                         CRP200 :  WAS ACCEPTED                                         *");
    System.out.println(
            "**********************************************************************************************************");

    xml = new StreamSource(System.getProperty("CAPABILITY11"));
    aucap = unMarshall(xml);
    insertCapability = new DataMapper(System.getProperty("CAPABILITY_DB_PATH"), System.getProperty("USER"),
            System.getProperty("PSW"), aucap);

    StringEntity input12 = new StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP200")));
    String result12 = testa.testPost(input12);

    Thread.sleep(5000);
    p.processPendingCapabilityRevocation();
    assertEquals(StatusCode.CRP200, RevocationOutCome.code);

    capRevDb = new ODatabaseDocumentTx(Constants.revocationDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);

    querySelRev = "select statusCode, status  from " + Constants.REVOCATION_CLASS + " where "
            + Constants.REVOCATION_ID + " = '_a1192622c7f69af47a906ef7ef1a4b15'";
    rev = capRevDb.command(new OCommandSQL(querySelRev)).execute();
    element = rev.get(0);

    assertEquals(element.field(Constants.STATUS), "WAS_ACCEPTED");
    assertEquals(element.field(Constants.STATUS_CODE), StatusCode.CRP200);

    auCapDb = new ODatabaseDocumentTx(Constants.capabilityDBUrl).open(Constants.iUserName,
            Constants.iUserPassword);
    queryPend = "select statusCode, status, capabilityID, resolvedOn  from " + Constants.PENDING_CLASS
            + " where " + Constants.REVOCATION_ID + " = '_a1192622c7f69af47a906ef7ef1a4b15'";
    res = auCapDb.command(new OCommandSQL(queryPend)).execute();
    elem = res.get(0);

    assertEquals(elem.field(Constants.STATUS), "WAS_ACCEPTED");
    assertEquals(elem.field(Constants.STATUS_CODE), StatusCode.CRP200);
    assertNotNull(elem.field(Constants.RESOLVED_ON));

    //       System.out.println("**********************************************************************************************************");
    //       System.out.println("*                                       CRP500 :  INTERNAL SERVER ERROR                                  *");
    //       System.out.println("**********************************************************************************************************");
    //      
    //       OServerAdmin admin = new
    //       OServerAdmin(System.getProperty("REVOCATION_DB_PATH_ERRATO"));
    //       admin.connect(Constants.iUserName, Constants.iUserPassword);
    //       admin.dropDatabase();
    //      
    //       StringEntity input13 = new
    //       StringEntity(readFileAsString(System.getProperty("REVOCATION_CRP500")));
    //       String result13 = testa.testPost(input13);
    //       assertEquals(StatusCode.CRP500, result13);
    create.clearAll();
}

From source file:com.microsoft.windowsazure.management.scheduler.CloudServiceOperationsImpl.java

/**
* Create a cloud service./*from  ww  w  .  j  ava  2  s . c  o  m*/
*
* @param cloudServiceName Required. The cloud service name.
* @param parameters Required. Parameters supplied to the Create cloud
* service 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 cloudServiceName, CloudServiceCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (cloudServiceName == null) {
        throw new NullPointerException("cloudServiceName");
    }
    if (cloudServiceName.length() > 100) {
        throw new IllegalArgumentException("cloudServiceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() == null) {
        throw new NullPointerException("parameters.Description");
    }
    if (parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getGeoRegion() == null) {
        throw new NullPointerException("parameters.GeoRegion");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }

    // 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("cloudServiceName", cloudServiceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/CloudServices/";
    url = url + URLEncoder.encode(cloudServiceName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

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

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

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

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
    cloudServiceElement.appendChild(labelElement);

    Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Description");
    descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
    cloudServiceElement.appendChild(descriptionElement);

    Element geoRegionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "GeoRegion");
    geoRegionElement.appendChild(requestDoc.createTextNode(parameters.getGeoRegion()));
    cloudServiceElement.appendChild(geoRegionElement);

    if (parameters.getEmail() != null) {
        Element emailElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Email");
        emailElement.appendChild(requestDoc.createTextNode(parameters.getEmail()));
        cloudServiceElement.appendChild(emailElement);
    }

    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:be.fedict.eid.tsl.TrustServiceList.java

private void marshall() throws JAXBException, ParserConfigurationException {
    /*/*www  .  ja  v  a  2s . c o  m*/
     * Assign a unique XML Id to the TSL for signing purposes.
     */
    String tslId = "tsl-" + UUID.randomUUID().toString();
    TrustStatusListType trustStatusList = getTrustStatusList();
    trustStatusList.setId(tslId);

    /*
     * TSLTag
     */
    trustStatusList.setTSLTag(TSL_TAG);

    /*
     * Scheme Information - TSL version identifier.
     */
    TSLSchemeInformationType schemeInformation = trustStatusList.getSchemeInformation();
    if (null == schemeInformation) {
        schemeInformation = this.objectFactory.createTSLSchemeInformationType();
        trustStatusList.setSchemeInformation(schemeInformation);
    }
    schemeInformation.setTSLVersionIdentifier(BigInteger.valueOf(4));

    /*
     * Scheme Information - TSL sequence number
     */
    if (null == schemeInformation.getTSLSequenceNumber()) {
        schemeInformation.setTSLSequenceNumber(BigInteger.valueOf(1));
    }

    /*
     * Scheme Information - TSL Type
     */
    schemeInformation.setTSLType(TSL_TYPE);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.fedict.eid.tsl.jaxb.ecc.ObjectFactory.class, be.fedict.eid.tsl.jaxb.tslx.ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    LOG.debug("marshaller type: " + marshaller.getClass().getName());
    marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new TSLNamespacePrefixMapper());
    ObjectFactory objectFactory = new ObjectFactory();
    JAXBElement<TrustStatusListType> trustStatusListElement = objectFactory
            .createTrustServiceStatusList(trustStatusList);
    marshaller.marshal(trustStatusListElement, document);

    this.tslDocument = document;
}