Example usage for org.w3c.dom Document appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:act.installer.pubchem.PubchemParser.java

/**
 * Incrementally parses a stream of XML events from a PubChem file, extracting the next available PC-Compound entry
 * as a Chemical object./*from   www . j a  v  a  2s  .  c om*/
 * @param eventReader The xml event reader we are parsing the XML from
 * @return The constructed chemical
 * @throws XMLStreamException
 * @throws XPathExpressionException
 */
public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader)
        throws XMLStreamException, JaxenException {
    Document bufferDoc = null;
    Element currentElement = null;
    StringBuilder textBuffer = null;
    /* With help from
     * http://stackoverflow.com/questions/7998733/loading-local-chunks-in-dom-while-parsing-a-large-xml-file-in-sax-java
     */
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            String eventName = event.asStartElement().getName().getLocalPart();
            if (COMPOUND_DOC_TAG.equals(eventName)) {
                // Create a new document if we've found the start of a compound object.
                bufferDoc = documentBuilder.newDocument();
                currentElement = bufferDoc.createElement(eventName);
                bufferDoc.appendChild(currentElement);
            } else if (currentElement != null) { // Wait until we've found a compound entry to start slurping up data.
                // Create a new child element and push down the current pointer when we find a new node.
                Element newElement = bufferDoc.createElement(eventName);
                currentElement.appendChild(newElement);
                currentElement = newElement;
            } // If we aren't in a PC-Compound tree, we just let the elements pass by.
            break;

        case XMLStreamConstants.CHARACTERS:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            Characters chars = event.asCharacters();
            // Ignore only whitespace strings, which just inflate the size of the DOM.  Text coalescing makes this safe.
            if (chars.isWhiteSpace()) {
                continue;
            }

            // Rely on the XMLEventStream to coalesce consecutive text events.
            Text textNode = bufferDoc.createTextNode(chars.getData());
            currentElement.appendChild(textNode);
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            eventName = event.asEndElement().getName().getLocalPart();
            Node parentNode = currentElement.getParentNode();
            if (parentNode instanceof Element) {
                currentElement = (Element) parentNode;
            } else if (parentNode instanceof Document && eventName.equals(COMPOUND_DOC_TAG)) {
                // We're back at the top of the node stack!  Convert the buffered document into a Chemical.
                PubchemEntry entry = extractPCCompoundFeatures(bufferDoc);
                if (entry != null) {
                    return entry.asChemical();
                } else {
                    // Skip this entry if we can't process it correctly by resetting the world and continuing on.
                    bufferDoc = null;
                    currentElement = null;
                }
            } else {
                // This should not happen, but is here as a sanity check.
                throw new RuntimeException(String.format("Parent of XML element %s is of type %d, not Element",
                        currentElement.getTagName(), parentNode.getNodeType()));
            }
            break;

        // TODO: do we care about attributes or other XML structures?
        }
    }

    // Return null when we run out of chemicals, just like readLine().
    return null;
}

From source file:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java

public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems) throws VerticalAdminException {

    User user = securityService.getLoggedInAdminConsoleUser();
    boolean createContentObject = false;
    String xmlData = null;//from  www .  j av  a 2s  . com
    Document doc;
    String queryParam = "";
    String script = "";

    int menuKey = formItems.getInt("menukey");

    if (request.getParameter("key") == null || request.getParameter("key").equals("")) {
        // Blank form, make dummy document
        doc = XMLTool.createDocument("contentobjects");
        createContentObject = true;
    } else {
        int cobKey = Integer.parseInt(request.getParameter("key"));

        xmlData = admin.getContentObject(cobKey);

        doc = XMLTool.domparse(xmlData);

        NodeList coNodes = doc.getElementsByTagName("contentobject");
        Element contentobject = (Element) coNodes.item(0);
        String contentKeyStr = contentobject.getAttribute("contentkey");
        if (contentKeyStr != null && contentKeyStr.length() > 0) {
            int contentKey = Integer.parseInt(contentKeyStr);

            String contentXML = admin.getContent(user, contentKey, 0, 0, 0);
            Document contentDoc = XMLTool.domparse(contentXML);
            NodeList contentNodes = contentDoc.getElementsByTagName("content");
            Element content = (Element) contentNodes.item(0);
            content = (Element) doc.importNode(content, true);
            contentobject.appendChild(content);
        }

        String menuItemsXML;
        menuItemsXML = admin.getMenuItemsByContentObject(user, cobKey);
        Document menuItemsDoc = XMLTool.domparse(menuItemsXML);
        contentobject.appendChild(doc.importNode(menuItemsDoc.getDocumentElement(), true));

        // Henter ut pagetemplates/frameworks som bruker dette contentobject
        String pageTemplatesXML = admin.getPageTemplatesByContentObject(cobKey);
        Document pageTemplatesDoc = XMLTool.domparse(pageTemplatesXML);
        contentobject.appendChild(doc.importNode(pageTemplatesDoc.getDocumentElement(), true));

        Element objectstylesheetElem = XMLTool.getElement(contentobject, "objectstylesheet");
        ResourceKey objectStyleSheetKey = new ResourceKey(objectstylesheetElem.getAttribute("key"));

        ResourceFile res = resourceService.getResourceFile(objectStyleSheetKey);
        objectstylesheetElem.setAttribute("exist", res == null ? "false" : "true");

        if (res != null) {
            try {
                Document styleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                objectstylesheetElem.setAttribute("valid", "true");

                Element styleSheetRoot = styleSheetDoc.getDocumentElement();
                String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                styleSheetRoot.removeAttribute("xmlns:xsl");
                styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                Element elem = XMLTool.createElement(doc, contentobject, "objectstylesheet_xsl");
                elem.appendChild(doc.importNode(styleSheetRoot, true));
            } catch (XMLException e) {
                objectstylesheetElem.setAttribute("valid", "false");
            }
        }

        Element borderstylesheetElem = XMLTool.getElement(contentobject, "borderstylesheet");
        if (borderstylesheetElem != null) {
            ResourceKey borderStyleSheetKey = ResourceKey.parse(borderstylesheetElem.getAttribute("key"));
            if (borderStyleSheetKey != null) {
                res = resourceService.getResourceFile(borderStyleSheetKey);
                borderstylesheetElem.setAttribute("exist", res == null ? "false" : "true");
                if (res != null) {
                    try {
                        Document borderStyleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                        borderstylesheetElem.setAttribute("valid", "true");

                        Element styleSheetRoot = borderStyleSheetDoc.getDocumentElement();
                        String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                        styleSheetRoot.removeAttribute("xmlns:xsl");
                        styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                        Element elem = XMLTool.createElement(doc, contentobject, "borderstylesheet_xsl");
                        elem.appendChild(doc.importNode(styleSheetRoot, true));
                    } catch (XMLException e) {
                        borderstylesheetElem.setAttribute("valid", "false");
                    }
                }
            }
        }
    }

    if (xmlData != null) {
        Map subelems = XMLTool.filterElements(doc.getDocumentElement().getChildNodes());
        if (subelems.get("contentobject") != null) {
            Element tempElem = (Element) subelems.get("contentobject");
            Map contentobjectmap = XMLTool.filterElements(tempElem.getChildNodes());

            Element contentobjectdata = (Element) contentobjectmap.get("contentobjectdata");
            Map queryparammap = XMLTool.filterElements(contentobjectdata.getChildNodes());
            tempElem = (Element) queryparammap.get("datasources");

            Document queryParamDoc = XMLTool.createDocument();
            tempElem = (Element) queryParamDoc.importNode(tempElem, true);
            queryParamDoc.appendChild(tempElem);

            StringWriter sw = new StringWriter();
            queryParamDoc.normalize();
            XMLTool.printDocument(sw, queryParamDoc, 0);
            queryParam = sw.toString();

            // Find the script data
            Element scriptElem = (Element) queryparammap.get("script");
            if (scriptElem != null) {
                script = XMLTool.getElementText(scriptElem);
            }

            Element[] paramElems = XMLTool.getElements(contentobjectdata, "stylesheetparam");
            for (Element paramElem1 : paramElems) {
                String type = paramElem1.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem1);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem1.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem1);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem1.setAttribute("valuename", name);
                }
            }

            paramElems = XMLTool.getElements(contentobjectdata, "borderparam");
            for (Element paramElem : paramElems) {
                String type = paramElem.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem.setAttribute("valuename", name);
                }
            }
        }
    }

    ExtendedMap parameters = new ExtendedMap();

    // Get default css if present
    ResourceKey defaultCSS = admin.getDefaultCSSByMenu(menuKey);
    if (defaultCSS != null) {
        parameters.put("defaultcsskey", defaultCSS.toString());
        parameters.put("defaultcsskeyExist",
                resourceService.getResourceFile(defaultCSS) == null ? "false" : "true");
    }

    VerticalAdminLogger.debug(this.getClass(), 0, doc);

    addCommonParameters(admin, user, request, parameters, -1, menuKey);

    if (createContentObject) {
        parameters.put("create", "1");
        parameters.put("queryparam", "<?xml version=\"1.0\" ?>\n<datasources/>");
    } else {
        parameters.put("create", "0");
        queryParam = StringUtil.formatXML(queryParam, 2);
        parameters.put("queryparam", queryParam);
    }

    parameters.put("menukey", String.valueOf(menuKey));

    parameters.put("page", String.valueOf(request.getParameter("page")));

    String subop = formItems.getString("subop", "");
    if ("popup".equals(subop)) {
        URL redirectURL = new URL("adminpage");
        redirectURL.setParameter("op", "callback");
        redirectURL.setParameter("callback", formItems.getString("callback"));
        redirectURL.setParameter("page", 991);
        redirectURL.setParameter("key", Integer.parseInt(request.getParameter("key")));
        redirectURL.setParameter("fieldname", formItems.getString("fieldname"));
        redirectURL.setParameter("fieldrow", formItems.getString("fieldrow"));
        parameters.put("referer", redirectURL.toString());
        parameters.put("subop", "popup");
    } else {
        parameters.put("referer", request.getHeader("referer"));
    }

    parameters.put("subop", subop);
    parameters.put("fieldname", formItems.getString("fieldname", null));
    parameters.put("fieldrow", formItems.getString("fieldrow", null));
    parameters.put("script", script);

    addAccessLevelParameters(user, parameters);

    UserEntity defaultRunAsUser = siteDao.findByKey(menuKey).resolveDefaultRunAsUser();
    String defaultRunAsUserName = "NA";
    if (defaultRunAsUser != null) {
        defaultRunAsUserName = defaultRunAsUser.getDisplayName();
    }
    parameters.put("defaultRunAsUser", defaultRunAsUserName);

    transformXML(request, response, doc, "contentobject_form.xsl", parameters);
}

From source file:com.seajas.search.attender.service.template.TemplateService.java

/**
 * Create a results template result./*  w w w.  ja  va2s.c o  m*/
 * 
 * @param language
 * @param queryString
 * @param query
 * @param uuid
 * @param searchResults
 * @return TemplateResult
 */
public TemplateResult createResults(final String language, final String queryString, final String query,
        final String subscriberUUID, final String profileUUID, final List<SearchResult> searchResults)
        throws ScriptException {
    Template template = templateDAO.findTemplate(TemplateType.Results, language);

    if (template == null) {
        logger.warn("Could not retrieve results template for language " + language
                + " - falling back to default language " + attenderService.getDefaultApplicationLanguage());

        template = templateDAO.findTemplate(TemplateType.Confirmation,
                attenderService.getDefaultApplicationLanguage());

        if (template == null) {
            logger.error("Could not retrieve fall-back results template for language "
                    + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

            return null;
        }
    }

    // Create an input document

    Document document;

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        documentBuilderFactory.setCoalescing(true);
        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        document = documentBuilder.newDocument();

        Element results = document.createElement("results");

        results.setAttribute("templateLanguage", language);
        results.setAttribute("profileQuery", query);
        results.setAttribute("subscriberUUID", subscriberUUID);
        results.setAttribute("profileUUID", profileUUID);
        results.setAttribute("queryString", queryString);

        for (SearchResult searchResult : searchResults)
            results.appendChild(searchResult.toElement(document));

        document.appendChild(results);

        // Plain text

        Transformer textTransformer = getTransformer(template, true);
        StringWriter textWriter = new StringWriter();

        textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        textTransformer.transform(new DOMSource(document), new StreamResult(textWriter));

        // HTML

        Transformer htmlTransformer = getTransformer(template, false);
        StringWriter htmlWriter = new StringWriter();

        htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        htmlTransformer.transform(new DOMSource(document), new StreamResult(htmlWriter));

        return new TemplateResult(textWriter.toString(), htmlWriter.toString());
    } catch (ScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:com.wavemaker.tools.project.LocalDeploymentManager.java

private void updateTomcatDeployConfig(Map<String, Object> properties) {
    LocalFolder projectDir = (LocalFolder) properties.get(PROJECT_DIR_PROPERTY);
    String deployName = (String) properties.get(DEPLOY_NAME_PROPERTY);
    LocalFile tomcatConfigXml = (LocalFile) projectDir.getFile(deployName + ".xml");
    if (tomcatConfigXml.exists()) {
        tomcatConfigXml.delete();//from w w  w.  ja  v a  2  s  .  c  o  m
    }
    tomcatConfigXml.createIfMissing();
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        NodeList nodeList = doc.getElementsByTagName("Context");

        if (nodeList != null && nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getParentNode() != null) {
                    node.getParentNode().removeChild(node);
                }
            }
        }

        Element context = doc.createElement("Context");
        context.setAttribute("antiJARLocking", "true'");
        context.setAttribute("antiResourceLocking", "false");
        context.setAttribute("privileged", "true");
        String docBase = ((LocalFolder) properties.get(BUILD_WEBAPPROOT_PROPERTY)).getLocalFile()
                .getAbsolutePath();
        context.setAttribute("docBase", docBase);

        doc.appendChild(context);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();

        Source source = new DOMSource(doc);
        Result dest = new StreamResult(tomcatConfigXml.getLocalFile());
        tFormer.transform(source, dest);

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

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  av  a  2 s  .  c  o  m*/
*
* @param serviceName Required. The DNS prefix name of your service.
* @param parameters Required. Parameters supplied to the Begin Creating
* Service Certificate operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreating(String serviceName, ServiceCertificateCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getCertificateFormat() == null) {
        throw new NullPointerException("parameters.CertificateFormat");
    }
    if (parameters.getData() == null) {
        throw new NullPointerException("parameters.Data");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serviceName", serviceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters);
    }

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

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

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

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

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

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

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

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

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * Writes an exam to an XML file/*w  w  w  . j av  a  2  s. c o  m*/
 *
 * @param exam      the exam to be written
 * @param examFile  the target file
 * @param password  the passphrase locking the restricted content
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeExam(@Nonnull Exam exam, @Nonnull File examFile, @Nonnull String password,
        boolean overwrite) throws VaSolSimException {
    logger.info("beginning exam export -> " + exam.getTestName());

    logger.debug("checking export destination...");

    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        logger.trace("exam file exists, checking overwrite...");

        //can't overwrite
        if (!overwrite) {
            logger.error("file already present and cannot overwrite");
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            logger.trace("overwriting...");
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                logger.error("internal file presence check failed", e);
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        logger.trace("exam file does not exist, creating...");

        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            logger.error("could not create empty directories for export");
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            logger.trace("creating files...");
            if (!examFile.createNewFile()) {
                logger.error("could not create empty file for export");
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            logger.error("io error on empty file creation", e);
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    logger.debug("initializing weak cryptography scheme...");

    /*
     * initialize the cryptography system
     */
    String encryptedHash;
    Cipher encryptionCipher;
    try {
        logger.trace("hashing password into key...");
        //hash the password
        byte[] hash;
        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(password.getBytes());
        hash = GenericUtils.validate512HashTo128Hash(msgDigest.digest());

        logger.trace("initializing cipher");
        encryptionCipher = GenericUtils.initCrypto(hash, Cipher.ENCRYPT_MODE);

        encryptedHash = GenericUtils
                .convertBytesToHexString(GenericUtils.applyCryptographicCipher(hash, encryptionCipher));
    } catch (NoSuchAlgorithmException e) {
        logger.error("FAILED. could not initialize crypto", e);
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    }

    logger.debug("initializing the document builder...");

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        logger.trace("create document builder factory instance -> create new doc");
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        logger.trace("set document properties");
        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        logger.error("parser was not configured correctly", e);
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        logger.error("transformer was not configured properly");
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    logger.debug("building document...");

    /*
     * build exam info
     */
    logger.trace("attaching root...");
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    logger.trace("attaching info...");
    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    logger.trace("attaching exam info...");
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);
    GenericUtils.appendSubNode(XML_DATE_ELEMENT_NAME, exam.getDate(), info, examDoc);

    //start security xml section
    logger.trace("attaching security...");
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_ENCRYPTED_VALIDATION_HASH_ELEMENT_NAME, encryptedHash, security, examDoc);
    GenericUtils.appendSubNode(XML_PARAMETRIC_INITIALIZATION_VECTOR_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(encryptionCipher.getIV()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsDestinationEmail() == null ? GenericUtils.NO_EMAIL.getBytes()
                            : exam.getStatsDestinationEmail().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderEmail() == null ? GenericUtils.NO_EMAIL.getBytes()
                            : exam.getStatsSenderEmail().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_PASSWORD_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderPassword() == null ? GenericUtils.NO_DATA.getBytes()
                            : exam.getStatsSenderPassword().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderSMTPAddress() == null ? GenericUtils.NO_SMTP.getBytes()
                            : exam.getStatsSenderSMTPAddress().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    Integer.toString(exam.getStatsSenderSMTPPort()).getBytes(), encryptionCipher)),
            security, examDoc);

    logger.debug("checking exam content integrity...");
    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.checkExamIntegrity(exam).size() == 0) {
        logger.debug("exporting exam content...");
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);
            logger.trace("exporting question set -> " + qSet.getName());

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResourceType() != GenericUtils.ResourceType.NONE && qSet.getResources() != null) {
                logger.debug("exporting question set resources...");
                for (BufferedImage img : qSet.getResources()) {
                    if (img != null) {
                        try {
                            logger.trace("writing image...");
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            ImageIO.write(img, "png", out);
                            out.flush();
                            GenericUtils.appendCDATASubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                    new String(Base64.encodeBase64(out.toByteArray())), qSetElement, examDoc);
                        } catch (IOException e) {
                            throw new VaSolSimException(
                                    "Error: cannot write images to byte array for transport");
                        }
                    }
                }
            }

            //TODO export problem in this subroutine
            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);
                logger.trace("exporting question -> " + question.getName());

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                logger.trace("question id -> " + setIndex);
                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                logger.trace("question name -> " + question.getName());
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(),
                        qElement, examDoc);
                logger.trace("question test -> " + question.getQuestion());
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                logger.trace("question answer scramble -> " + Boolean.toString(question.getScrambleAnswers()));
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                logger.trace("question answer order matters -> "
                        + Boolean.toString(question.getAnswerOrderMatters()));
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                logger.debug("exporting correct answer choices...");
                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    logger.trace("exporting correct answer choice(s) -> " + answer.getAnswerText());
                    GenericUtils
                            .appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH,
                                    GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                                            answer.getAnswerText().getBytes(), encryptionCipher)),
                                    qElement, examDoc);
                }

                logger.debug("exporting answer choices...");
                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    if (question.getAnswerChoices().get(questionIndex).isActive()) {
                        AnswerChoice ac = question.getAnswerChoices().get(questionIndex);
                        logger.trace("exporting answer choice -> " + ac.getAnswerText());

                        Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                        qElement.appendChild(acElement);

                        logger.trace("answer choice id -> " + questionIndex);
                        GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                                Integer.toString(questionIndex + 1), acElement, examDoc);
                        logger.trace("answer choice visible id -> " + ac.getVisibleChoiceID());
                        GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                                ac.getVisibleChoiceID(), acElement, examDoc);
                        logger.trace("answer text -> " + ac.getAnswerText());
                        GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                                examDoc);
                    }
                }
            }
        }
    } else {
        logger.error("integrity check failed");
        PopupManager.showMessage(errorsToOutput(GenericUtils.checkExamIntegrity(exam)));
        return false;
    }

    logger.debug("transforming exam...");
    try {
        examTransformer.transform(new DOMSource(examDoc), new StreamResult(examFile));
    } catch (TransformerException e) {
        logger.error("exam export failed (transformer error)", e);
        return false;
    }
    logger.debug("transformation done");

    logger.info("exam export successful");
    return true;
}

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

/**
* Sets IP Forwarding on a role.//from   ww  w. j  av  a2  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:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

/**
 * Gets the data from a specific set of URL's and converts the information
 * to the format usefull to the REQUEST_TYPE. Once the information is
 * collected and converted the method calls for a write in the DataWrapper,
 * which will sent the data to the client requested for this information.
 *
 * @param dw DataWrapper object containing the clients request information
 * @param urls StringBuffer with the urls where kaartenbalie should connect
 * to to recieve the requested data.//  w  w w.java  2  s. co  m
 * @param overlay A boolean setting the overlay to true or false. If false
 * is chosen the images are placed under eachother.
 *
 * @return byte[]
 *
 * @throws Exception
 */
protected void getOnlineData(DataWrapper dw, ArrayList urlWrapper, boolean overlay, String REQUEST_TYPE)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedImage[] bi = null;

    //The list is given in the opposit ranking. Therefore we first need to swap the list.
    int size = urlWrapper.size();
    ArrayList swaplist = new ArrayList(size);
    for (int i = size - 1; i >= 0; i--) {
        swaplist.add(urlWrapper.get(i));
        log.debug("Outgoing url: " + ((ServiceProviderRequest) urlWrapper.get(i)).getProviderRequestURI());
    }
    urlWrapper = swaplist;

    /* To save time, this method checks first if the ArrayList contains more then one url
     * If it contains only one url then the method doesn't have to load the image into the G2D
     * environment, which saves a lot of time and capacity because it doesn't have to decode
     * and recode the image.
     */
    long startprocestime = System.currentTimeMillis();

    DataMonitoring rr = dw.getRequestReporting();
    if (urlWrapper.size() > 1) {
        if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetMap)) {
            /*
             * Log the time in ms from the start of the clientrequest.. (Reporting)
             */
            Operation o = new Operation();
            o.setType(Operation.SERVER_TRANSFER);
            o.setMsSinceRequestStart(new Long(rr.getMSSinceStart()));

            ImageManager imagemanager = new ImageManager(urlWrapper, dw);
            imagemanager.process();
            long endprocestime = System.currentTimeMillis();
            Long time = new Long(endprocestime - startprocestime);
            dw.setHeader("X-Kaartenbalie-ImageServerResponseTime", time.toString());

            o.setDuration(time);
            rr.addRequestOperation(o);

            imagemanager.sendCombinedImages(dw);
        } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetFeatureInfo)) {

            /*
             * Create a DOM document and copy all the information of the several GetFeatureInfo
             * responses into one document. This document has the same layout as the received
             * documents and will hold all the information of the specified objects.
             * After combining these documents, the new document will be sent onto the request.
             */
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(false);
            dbf.setNamespaceAware(true);
            dbf.setIgnoringElementContentWhitespace(true);

            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document destination = builder.newDocument();
            Element rootElement = destination.createElement("msGMLOutput");
            destination.appendChild(rootElement);
            rootElement.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
            rootElement.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
            rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            Document source = null;
            for (int i = 0; i < urlWrapper.size(); i++) {
                ServiceProviderRequest wmsRequest = (ServiceProviderRequest) urlWrapper.get(i);
                String url = wmsRequest.getProviderRequestURI();
                // code below could be used to get bytes received
                //InputStream is = new URL(url).openStream();
                //CountingInputStream cis = new CountingInputStream(is);
                //source = builder.parse(cis);
                source = builder.parse(url); //what if url points to non MapServer service?
                copyElements(source, destination);

                wmsRequest.setBytesSent(new Long(url.getBytes().length));
                wmsRequest.setProviderRequestURI(url);
                wmsRequest.setMsSinceRequestStart(new Long(rr.getMSSinceStart()));
                wmsRequest.setBytesReceived(new Long(-1));
                //wmsRequest.setBytesReceived(new Long(cis.getByteCount()));
                wmsRequest.setResponseStatus(new Integer(-1));
                rr.addServiceProviderRequest(wmsRequest);
            }

            OutputFormat format = new OutputFormat(destination);
            format.setIndenting(true);
            XMLSerializer serializer = new XMLSerializer(baos, format);
            serializer.serialize(destination);
            dw.write(baos);
        } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_DescribeLayer)) {

            //TODO: implement and refactor so there is less code duplication with getFeatureInfo
            /*
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setValidating(false);
              dbf.setNamespaceAware(true);
              dbf.setIgnoringElementContentWhitespace(true);
                    
              DocumentBuilder builder = dbf.newDocumentBuilder();
              Document destination = builder.newDocument();
                     
              //root element is different
              Element rootElement = destination.createElement("WMS_DescribeLayerResponse");
              destination.appendChild(rootElement);
              //set version attribute
              Document source = null;
              for (int i = 0; i < urlWrapper.size(); i++) {
              ServiceProviderRequest dlRequest = (ServiceProviderRequest) urlWrapper.get(i);
              String url = dlRequest.getProviderRequestURI();
              source = builder.parse(url);
              copyElements(source,destination);
              }*/

            throw new Exception(REQUEST_TYPE + " request with more then one service url is not supported yet!");
        }

    } else {
        //urlWrapper not > 1, so only 1 url or zero urls
        if (!urlWrapper.isEmpty()) {
            getOnlineData(dw, (ServiceProviderRequest) urlWrapper.get(0), REQUEST_TYPE);
        } else {
            if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetFeatureInfo)) {
                log.error(KBConfiguration.FEATUREINFO_EXCEPTION);
                throw new Exception(KBConfiguration.FEATUREINFO_EXCEPTION);
            } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetLegendGraphic)) {
                log.error(KBConfiguration.LEGENDGRAPHIC_EXCEPTION);
                throw new Exception(KBConfiguration.LEGENDGRAPHIC_EXCEPTION);
            }
        }
    }
}

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

/**
* Sets IP Forwarding on a network interface.
*
* @param serviceName Required.//ww w.j a  v a 2  s .  c  o  m
* @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();
        }
    }
}

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

/**
* Add an internal load balancer to a an existing deployment. When used by
* an input endpoint, the internal load balancer will provide an additional
* private VIP that can be used for load balancing to the roles in this
* deployment.//from  w w  w  .j a v a  2 s.c  o m
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param parameters Required. Parameters supplied to the Create Load
* Balancer 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 error information regarding the failure.
*/
@Override
public OperationStatusResponse beginCreating(String serviceName, String deploymentName,
        LoadBalancerCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        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 + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/loadbalancers";
    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 loadBalancerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "LoadBalancer");
    requestDoc.appendChild(loadBalancerElement);

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        loadBalancerElement.appendChild(nameElement);
    }

    if (parameters.getFrontendIPConfiguration() != null) {
        Element frontendIpConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIpConfiguration");
        loadBalancerElement.appendChild(frontendIpConfigurationElement);

        if (parameters.getFrontendIPConfiguration().getType() != null) {
            Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Type");
            typeElement
                    .appendChild(requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getType()));
            frontendIpConfigurationElement.appendChild(typeElement);
        }

        if (parameters.getFrontendIPConfiguration().getSubnetName() != null) {
            Element subnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SubnetName");
            subnetNameElement.appendChild(
                    requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getSubnetName()));
            frontendIpConfigurationElement.appendChild(subnetNameElement);
        }

        if (parameters.getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress() != null) {
            Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
            staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(parameters
                    .getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress().getHostAddress()));
            frontendIpConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement);
        }
    }

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