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:ambit.data.qmrf.QMRFObject.java

protected Document buildDocument() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);//from ww  w.  ja v  a2 s.  com
    factory.setValidating(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new SimpleErrorHandler(builder.getClass().getName()));
    Document doc = builder.newDocument();
    Element e = toXML(doc);
    doc.appendChild(e);
    return doc;
}

From source file:com.commander4j.messages.OutgoingDespatchConfirmation.java

public Boolean processMessage(Long transactionRef) {
    Boolean result = false;//from   w  w  w. j a  v  a2 s.c  o m
    String path = "";
    String defaultBatchStatus = "";

    JDBInterfaceLog il = new JDBInterfaceLog(getHostID(), getSessionID());
    JDBControl ctrl = new JDBControl(getHostID(), getSessionID());
    GenericMessageHeader gmh = new GenericMessageHeader();
    JDBInterface inter = new JDBInterface(getHostID(), getSessionID());
    JDBUom uoml = new JDBUom(getHostID(), getSessionID());
    String batchDateMode = ctrl.getKeyValue("EXPIRY DATE MODE");

    inter.getInterfaceProperties("Despatch Confirmation", "Output");
    String device = inter.getDevice();

    JDBDespatch desp = new JDBDespatch(getHostID(), getSessionID());
    desp.setTransactionRef(transactionRef);
    desp.getDespatchPropertiesFromTransactionRef();

    String sourceGLN = JUtility.replaceNullStringwithBlank(desp.getLocationDBFrom().getGLN());
    String destinationGLN = JUtility.replaceNullStringwithBlank(desp.getLocationDBTo().getGLN());
    Boolean suppressMessage = false;

    gmh.setMessageRef(desp.getTransactionRef().toString());
    gmh.setInterfaceType(inter.getInterfaceType());
    gmh.setMessageInformation("Despatch=" + desp.getDespatchNo());
    gmh.setInterfaceDirection(inter.getInterfaceDirection());
    gmh.setMessageDate(JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()));

    String noJourneyPrefix = ctrl.getKeyValueWithDefault("NO JOURNEY PREFIX", "NJ_",
            "Prefix for No Journey Messages");

    if (desp.getDespatchPalletCount() == 0) {
        setErrorMessage("Message Suppressed - 0 pallets assigned to despatch");
        suppressMessage = true;
    }

    if (sourceGLN.length() == 0) {
        setErrorMessage("Message Suppressed - No GLN Source (From) GLN for Location ["
                + desp.getLocationIDFrom() + "]");
        suppressMessage = true;
    }

    if (destinationGLN.length() == 0) {
        setErrorMessage("Message Suppressed - No GLN Destination (To) GLN for Location ["
                + desp.getLocationIDTo() + "]");
        suppressMessage = true;
    }

    if (suppressMessage == true) {
        result = true;
        il.write(gmh, GenericMessageHeader.msgStatusWarning, getErrorMessage(), "File Write", "");

    } else {
        if (inter.getFormat().equals("EANCOM")) {

            if (sourceGLN.endsWith("")) {

            }

            int segments = 0;
            int optional = 0;
            String document = "";
            String despdateShort = new java.text.SimpleDateFormat("yyMMdd:HHmm").format(desp.getDespatchDate());
            String despdateLong = new java.text.SimpleDateFormat("yyyyMMddHHmm").format(desp.getDespatchDate());

            document = document + "UNA:+.? 'UNB+UNOA:3+" + desp.getLocationDBFrom().getGLN() + ":14+"
                    + desp.getLocationDBTo().getGLN() + ":14+";
            document = document + despdateShort + "+" + desp.getDespatchNo() + "'";
            document = document + "UNH+" + desp.getDespatchNo() + "+DESADV:D:96A:EN:EAN005'";
            document = document + "BGM+351+" + desp.getDespatchNo() + "+9'";
            document = document + "DTM+11:" + despdateLong + ":203'";
            document = document + "RFF+LO:" + desp.getDespatchNo() + "'";
            document = document + "RFF+ZCO:'";

            if (desp.getLocationDBTo().getMsgJourneyRef().equals("Y")) {
                if (desp.getJourneyRef().equals("NO JOURNEY")) {
                    document = document + "RFF+SRN:" + noJourneyPrefix + desp.getDespatchNo() + "'";
                } else {
                    document = document + "RFF+SRN:" + desp.getJourneyRef() + "'";
                }
                optional++;
            }

            document = document + "RFF+ZAF:'";
            document = document + "RFF+ZPI:1'";
            document = document + "RFF+ZCH:'";
            document = document + "NAD+SF+" + desp.getLocationDBFrom().getGLN() + "::9'";

            if (desp.getLocationDBFrom().getStorageLocation().equals("") == false) {
                if (desp.getLocationDBTo().getStorageLocation().equals("") == false) {
                    document = document + "LOC+198+" + desp.getLocationDBFrom().getStorageLocation() + "::91'";
                    optional++;
                }
            }

            document = document + "NAD+ST+" + desp.getLocationDBTo().getGLN() + "::9'";

            if (desp.getLocationDBFrom().getStorageLocation().equals("") == false) {
                if (desp.getLocationDBTo().getStorageLocation().equals("") == false) {
                    document = document + "LOC+195+" + desp.getLocationDBTo().getStorageLocation() + "::91'";
                    optional++;
                }
            }

            document = document + "TDT+20++30+31+::9:"
                    + JUtility.stripEANCOMSpecialCharacters(
                            JUtility.replaceNullStringwithBlank(desp.getHaulier()))
                    + "+++:::" + JUtility.stripEANCOMSpecialCharacters(
                            JUtility.replaceNullStringwithBlank(desp.getTrailer()))
                    + "'";

            if (desp.getLoadNo().equals("")) {
                desp.setLoadNo("123");
            }

            document = document + "EQD+CN+"
                    + JUtility.replaceNullStringwithBlank(StringUtils.left(desp.getTrailer(), 10)) + "'";

            // NEXT 2 LINES COMMENTS NEED TO BE RESTORED FOR SAP EWM

            // Next line needs commenting pre SAP EWM
            document = document + "SEL+"
                    + JUtility.replaceNullStringwithBlank(StringUtils.left(desp.getLoadNo(), 10)) + "+CA'";
            document = document + "SEL+" + desp.getDespatchNo() + "+CU'";

            // Next line needs amending pre SAP EWM
            segments = 14 + optional;
            //segments = 13 + optional;

            JDBPalletHistory palhist = new JDBPalletHistory(getHostID(), getSessionID());
            ResultSet rs = palhist.getInterfacingData(transactionRef, "DESPATCH", "TO", Long.valueOf(0), "SSCC",
                    "asc");

            int x = 1;
            try {
                rs.beforeFirst();
                while (rs.next()) {
                    palhist.getPropertiesfromResultSet(rs);

                    document = document + "CPS+" + JUtility.padString(String.valueOf(x).trim(), false, 4, "0")
                            + "'";
                    document = document + "PAC+1++202'";
                    document = document + "PCI+33E'";
                    document = document + "GIN+BJ+" + palhist.getPallet().getSSCC() + "'";
                    document = document + "LIN+1++" + palhist.getPallet().getEAN() + ":EN'";
                    document = document + "PIA+1+" + palhist.getPallet().getVariant() + ":PV+"
                            + palhist.getPallet().getMaterial() + ":SA'";

                    NumberFormat formatter = new DecimalFormat("#.#");
                    String outqty = formatter.format(palhist.getPallet().getQuantity()); // -1234.567000

                    document = document + "QTY+12:" + outqty + ":" + palhist.getPallet().getUom() + "'";
                    document = document + "DLM+++0::9'";

                    //                  String batchExpiryLong = new java.text.SimpleDateFormat("yyyyMMdd").format(palhist.getPallet().getMaterialBatchExpiryDate());

                    String batchExpiryLong = "";
                    if (batchDateMode.equals("BATCH")) {
                        batchExpiryLong = new java.text.SimpleDateFormat("yyyyMMdd")
                                .format(palhist.getPallet().getMaterialBatchExpiryDate());
                    }

                    if (batchDateMode.equals("SSCC")) {
                        batchExpiryLong = new java.text.SimpleDateFormat("yyyyMMdd")
                                .format(palhist.getPallet().getBatchExpiry());
                    }

                    String dateOfManufactureLong = new java.text.SimpleDateFormat("yyyyMMdd")
                            .format(palhist.getPallet().getDateOfManufacture());

                    document = document + "DTM+361:" + batchExpiryLong + ":102'";
                    document = document + "DTM+94:" + dateOfManufactureLong + ":102'";
                    document = document + "RFF+AAJ:" + palhist.getPallet().getDespatchNo() + ":1'";

                    defaultBatchStatus = palhist.getPallet().getMaterialBatchStatus();

                    if (defaultBatchStatus.equals("Unrestricted")) {
                        document = document + "RFF+ZBR:'";
                    } else {
                        document = document + "RFF+ZBR:B'";
                    }

                    document = document + "RFF+ZRB:'";
                    document = document + "RFF+ZSR:'";
                    document = document + "RFF+ZRC:'";
                    document = document + "RFF+ZRT:'";
                    document = document + "PCI+36E'";
                    document = document + "GIN+BX+" + palhist.getPallet().getBatchNumber() + "'";

                    segments = segments + 18;

                    x++;
                }
                rs.close();

                segments = segments + 1;

                document = document + "UNT+" + String.valueOf(segments).trim() + "+" + desp.getDespatchNo()
                        + "'";
                document = document + "UNZ+1+" + desp.getDespatchNo() + "'";

                if (device.equals("Disk") | device.equals("Email")) {
                    path = inter.getRealPath();
                    if (fio.writeToDisk(path, document, transactionRef, "_"
                            + desp.getLocationIDTo().replace(" ", "_") + "_DespatchConfirmation.txt") == true) {
                        result = true;
                        il.write(gmh, GenericMessageHeader.msgStatusSuccess, "Processed OK", "File Write",
                                fio.getFilename());
                        setErrorMessage("");
                        if (device.equals("Email")) {
                            ogm = new JeMailOutGoingMessage(inter, transactionRef, fio);
                            ogm.sendEmail();
                        }
                    } else {
                        result = false;
                        il.write(gmh, GenericMessageHeader.msgStatusError, fio.getErrorMessage(), "File Write",
                                fio.getFilename());
                        setErrorMessage(fio.getErrorMessage());
                    }

                }

            } catch (SQLException e) {

            }

        }

        if (inter.getFormat().equals("XML")) {

            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();

                Document document = builder.newDocument();

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

                Element hostUniqueID = addElement(document, "hostRef",
                        Common.hostList.getHost(getHostID()).getUniqueID());
                message.appendChild(hostUniqueID);

                Element messageRef = addElement(document, "messageRef", String.valueOf(transactionRef));
                message.appendChild(messageRef);

                Element messageType = addElement(document, "interfaceType", "Despatch Confirmation");
                message.appendChild(messageType);

                Element messageInformation = addElement(document, "messageInformation",
                        "Despatch=" + desp.getDespatchNo());
                message.appendChild(messageInformation);

                Element messageDirection = addElement(document, "interfaceDirection", "Output");
                message.appendChild(messageDirection);

                Element messageDate = addElement(document, "messageDate",
                        JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()));
                message.appendChild(messageDate);

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

                Element noofpallets = addElement(document, "numberOfPallets",
                        String.valueOf(desp.getTotalPallets()));
                despatchConfirmation.appendChild(noofpallets);

                Element haulier = addElement(document, "haulier",
                        String.valueOf(JUtility.replaceNullStringwithBlank(desp.getHaulier())));
                despatchConfirmation.appendChild(haulier);

                Element trailer = addElement(document, "trailer",
                        String.valueOf(JUtility.replaceNullStringwithBlank(desp.getTrailer())));
                despatchConfirmation.appendChild(trailer);

                Element load = addElement(document, "loadNo",
                        String.valueOf(JUtility.replaceNullStringwithBlank(desp.getLoadNo())));
                despatchConfirmation.appendChild(load);

                Element journey = addElement(document, "journeyRef",
                        String.valueOf(JUtility.replaceNullStringwithBlank(desp.getJourneyRef())));
                despatchConfirmation.appendChild(journey);

                Element despatch = addElement(document, "despatchNo", desp.getDespatchNo());
                despatchConfirmation.appendChild(despatch);

                Element despatchDate = addElement(document, "despatchDate",
                        JUtility.getISOTimeStampStringFormat(desp.getDespatchDate()));
                despatchConfirmation.appendChild(despatchDate);

                Element locationFrom = addElement(document, "fromLocation", desp.getLocationIDFrom());
                despatchConfirmation.appendChild(locationFrom);

                Element locationFromPlant = addElement(document, "fromPlant",
                        desp.getLocationDBFrom().getPlant());
                despatchConfirmation.appendChild(locationFromPlant);

                Element locationFromWarehouse = addElement(document, "fromWarehouse",
                        desp.getLocationDBFrom().getWarehouse());
                despatchConfirmation.appendChild(locationFromWarehouse);

                Element locationFromStorageSection = addElement(document, "fromStorageSection",
                        desp.getLocationDBFrom().getStorageSection());
                despatchConfirmation.appendChild(locationFromStorageSection);

                Element locationFromStorageType = addElement(document, "fromStorageType",
                        desp.getLocationDBFrom().getStorageType());
                despatchConfirmation.appendChild(locationFromStorageType);

                Element locationFromStorageBin = addElement(document, "fromStorageBin",
                        desp.getLocationDBFrom().getStorageBin());
                despatchConfirmation.appendChild(locationFromStorageBin);

                Element locationFromGLN = addElement(document, "fromGLN", desp.getLocationDBFrom().getGLN());
                despatchConfirmation.appendChild(locationFromGLN);

                Element locationFromStorageLocation = addElement(document, "fromStorageLocation",
                        desp.getLocationDBFrom().getStorageLocation());
                despatchConfirmation.appendChild(locationFromStorageLocation);

                Element locationTo = addElement(document, "toLocation", desp.getLocationIDTo());
                despatchConfirmation.appendChild(locationTo);

                Element locationToPlant = addElement(document, "toPlant", desp.getLocationDBTo().getPlant());
                despatchConfirmation.appendChild(locationToPlant);

                Element locationToWarehouse = addElement(document, "toWarehouse",
                        desp.getLocationDBTo().getWarehouse());
                despatchConfirmation.appendChild(locationToWarehouse);

                Element locationToStorageSection = addElement(document, "toStorageSection",
                        desp.getLocationDBTo().getStorageSection());
                despatchConfirmation.appendChild(locationToStorageSection);

                Element locationToStorageType = addElement(document, "toStorageType",
                        desp.getLocationDBTo().getStorageType());
                despatchConfirmation.appendChild(locationToStorageType);

                Element locationToStorageBin = addElement(document, "toStorageBin",
                        desp.getLocationDBTo().getStorageBin());
                despatchConfirmation.appendChild(locationToStorageBin);

                Element locationToGLN = addElement(document, "toGLN", desp.getLocationDBTo().getGLN());
                despatchConfirmation.appendChild(locationToGLN);

                Element locationToStorageLocation = addElement(document, "toStorageLocation",
                        desp.getLocationDBTo().getStorageLocation());
                despatchConfirmation.appendChild(locationToStorageLocation);

                Element contents = (Element) document.createElement("contents");
                despatchConfirmation.appendChild(contents);

                JDBPalletHistory palhist = new JDBPalletHistory(getHostID(), getSessionID());
                ResultSet rs = palhist.getInterfacingData(transactionRef, "DESPATCH", "TO", Long.valueOf(0),
                        "SSCC", "asc");

                int x = 1;
                try {
                    rs.beforeFirst();
                    while (rs.next()) {
                        palhist.getPropertiesfromResultSet(rs);
                        Element pallet = (Element) document.createElement("pallet");

                        Element item = addElement(document, "item", String.valueOf(x));
                        pallet.appendChild(item);
                        x++;

                        Element sscc = addElement(document, "SSCC", palhist.getPallet().getSSCC());
                        pallet.appendChild(sscc);

                        Element processOrder = addElement(document, "processOrder",
                                palhist.getPallet().getProcessOrder());
                        pallet.appendChild(processOrder);

                        Element material = addElement(document, "material", palhist.getPallet().getMaterial());
                        pallet.appendChild(material);

                        Element materialDescription = addElement(document, "materialDescription",
                                palhist.getPallet().getMaterialObj().getDescription());
                        pallet.appendChild(materialDescription);

                        Element ean = addElement(document, "ean", palhist.getPallet().getEAN());
                        pallet.appendChild(ean);

                        Element variant = addElement(document, "variant", palhist.getPallet().getVariant());
                        pallet.appendChild(variant);

                        Element qty = addElement(document, "quantity",
                                palhist.getPallet().getQuantity().toString());
                        pallet.appendChild(qty);

                        String paluom = palhist.getPallet().getUom();
                        paluom = uoml.convertUom(inter.getUOMConversion(), paluom);

                        Element uom = addElement(document, "UOM", paluom);
                        pallet.appendChild(uom);

                        Element status = addElement(document, "status", palhist.getPallet().getStatus());
                        pallet.appendChild(status);

                        String expiryDateStr = "";
                        if (batchDateMode.equals("BATCH")) {
                            expiryDateStr = JUtility.getISOTimeStampStringFormat(
                                    palhist.getPallet().getMaterialBatchExpiryDate());
                        }

                        if (batchDateMode.equals("SSCC")) {
                            expiryDateStr = JUtility
                                    .getISOTimeStampStringFormat(palhist.getPallet().getBatchExpiry());
                        }

                        Element expiryDate = addElement(document, "bestBefore", expiryDateStr);
                        pallet.appendChild(expiryDate);

                        Element dom = addElement(document, "productionDate", JUtility
                                .getISOTimeStampStringFormat(palhist.getPallet().getDateOfManufacture()));
                        pallet.appendChild(dom);

                        Element batch = addElement(document, "batch", palhist.getPallet().getBatchNumber());
                        pallet.appendChild(batch);

                        Element batchStatus = addElement(document, "batchStatus",
                                palhist.getPallet().getMaterialBatchStatus());
                        pallet.appendChild(batchStatus);

                        contents.appendChild(pallet);

                    }
                    rs.close();
                } catch (SQLException e) {

                }

                Element messageData = (Element) document.createElement("messageData");
                messageData.appendChild(despatchConfirmation);

                message.appendChild(messageData);

                document.appendChild(message);

                JXMLDocument xmld = new JXMLDocument();
                xmld.setDocument(document);
                gmh.decodeHeader(xmld);

                if (device.equals("Disk") | device.equals("Email")) {
                    path = inter.getRealPath();
                    if (fio.writeToDisk(path, document, transactionRef, "_"
                            + desp.getLocationIDTo().replace(" ", "_") + "_DespatchConfirmation.xml") == true) {
                        result = true;
                        il.write(gmh, GenericMessageHeader.msgStatusSuccess, "Processed OK", "File Write",
                                fio.getFilename());
                        setErrorMessage("");

                        if (device.equals("Email")) {
                            ogm = new JeMailOutGoingMessage(inter, transactionRef, fio);
                            ogm.sendEmail();
                        }
                    } else {
                        result = false;
                        il.write(gmh, GenericMessageHeader.msgStatusError, fio.getErrorMessage(), "File Write",
                                fio.getFilename());
                        setErrorMessage(fio.getErrorMessage());
                    }

                }

            }

            catch (Exception ex) {
                logger.error("Error sending message. " + ex.getMessage());
                result = false;
            }
        }
    }

    return result;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 * Convert the result set into an XML structure.
 *
 * @param items//from w w w  .  j  a  v a 2 s.c  om
 * @param withHistory
 * @param locale
 * @param personBean
 * @param filterName
 * @param filterExpression
 * @param useProjectSpecificID
 * @param outfileName
 * @return
 */
public Document convertToDOM(List<ReportBean> items, boolean withHistory, Locale locale, TPersonBean personBean,
        String filterName, String filterExpression, boolean useProjectSpecificID, String outfileName) {
    Document doc = null;

    try {

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

        // root elements
        doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("pdfFile");
        doc.appendChild(rootElement);

        // set attribute to staff element
        Attr attr = doc.createAttribute("file");
        outfileName = outfileName.replace(".tex", ".pdf");
        attr.setValue(latexTmpDir + File.separator + outfileName);
        rootElement.setAttributeNode(attr);

    } catch (FactoryConfigurationError e) {
        LOGGER.error("Creating the DOM document failed with FactoryConfigurationError:" + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    } catch (ParserConfigurationException e) {
        LOGGER.error("Creating the DOM document failed with ParserConfigurationException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    }

    return doc;
}

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

/**
 * @param element//  w  w  w  .j  a  v a 2 s. c  o  m
 * @return
 * @throws ParserConfigurationException
 */
public org.dom4j.Element convert(org.w3c.dom.Element element) throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document doc1 = builder.newDocument();
    doc1.appendChild(doc1.importNode(element, true));
    // Convert w3c document to dom4j document
    org.dom4j.io.DOMReader reader = new org.dom4j.io.DOMReader();
    org.dom4j.Document doc2 = reader.read(doc1);

    return doc2.getRootElement();
}

From source file:de.interactive_instruments.ShapeChange.ShapeChangeResult.java

public ShapeChangeResult(Options o) {
    init();/* w ww.  j  a  v  a  2  s  . c  o m*/

    options = o;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
        DocumentBuilder db = dbf.newDocumentBuilder();
        document = db.newDocument();

        root = document.createElementNS(Options.SCRS_NS, "ShapeChangeResult");
        document.appendChild(root);
        root.setAttribute("resultCode", "0");
        root.setAttribute("xmlns:r", Options.SCRS_NS);
        root.setAttribute("start", (new Date()).toString());

        String version = "[dev]";
        InputStream stream = getClass().getResourceAsStream("/sc.properties");
        if (stream != null) {
            Properties properties = new Properties();
            properties.load(stream);
            version = properties.getProperty("sc.version");
        }
        root.setAttribute("version", version);

        messages = document.createElementNS(Options.SCRS_NS, "Messages");
        root.appendChild(messages);

        resultFiles = document.createElementNS(Options.SCRS_NS, "Results");
        root.appendChild(resultFiles);
    } catch (ParserConfigurationException e) {
        System.err.println("Bootstrap Error: XML parser was unable to be configured.");
        String m = e.getMessage();
        if (m != null) {
            System.err.println(m);
        }
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (Exception e) {
        System.err.println("Bootstrap Error: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(1);
    }

    outputFormat.setProperty("encoding", "UTF-8");
    outputFormat.setProperty("indent", "yes");
    outputFormat.setProperty("{http://xml.apache.org/xalan}indent-amount", "2");
}

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

/**
* Add a definition for a DNS server to an existing deployment. VM's in this
* deployment will be programmed to use this DNS server for all DNS
* resolutions// w  w  w. jav a  2 s .co  m
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param parameters Required. Parameters supplied to the Add DNS Server
* 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 beginAddingDNSServer(String serviceName, String deploymentName,
        DNSAddParameters 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, "beginAddingDNSServerAsync", 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 + "/dnsservers";
    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 dnsServerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "DnsServer");
    requestDoc.appendChild(dnsServerElement);

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

    if (parameters.getAddress() != null) {
        Element addressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Address");
        addressElement.appendChild(requestDoc.createTextNode(parameters.getAddress().getHostAddress()));
        dnsServerElement.appendChild(addressElement);
    }

    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:edu.isi.pfindr.servlets.QueryServlet.java

/**
 * get the XML string of the results of an SQL Query 
 * /*ww  w  .  ja  v a2 s .c  o m*/
 * @param request
 *            the servlet request
 * @param conn
 *            the DB connection
 * @return the XML string to be saved in a file
 */
@SuppressWarnings("unused")
private String saveXML(HttpServletRequest request, Connection conn) {
    String sql = request.getParameter("sql");
    JSONObject json;
    String phenotypes = "";
    try {
        // get the query results
        json = new JSONObject(sql);
        String sqlQuery = Utils.getPhenotypesSQL(json);
        logger.info(sqlQuery);
        PreparedStatement stmt = conn.prepareStatement(sqlQuery);
        Utils.loadValues(stmt, json, "", false);
        JSONArray group = new JSONArray(request.getParameter("template"));
        JSONArray rows = Utils.executeSQL(stmt);
        stmt.close();

        // create the document builder
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element root = doc.createElement("Phenotypes");
        doc.appendChild(root);

        // append the query results to the document
        JSONObject res = Utils.toJSONObject(group, rows);
        Utils.toXML(doc, root, res);

        // transform the document to an XML string
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        phenotypes = sw.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return phenotypes;
}

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

/**
* Updates a definition for an existing DNS server. Updates to address is
* the only change allowed. DNS server name cannot be changed
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param dnsServerName Required. The name of the dns server.
* @param parameters Required. Parameters supplied to the Update DNS Server
* operation.//w w  w  . j a  v  a2 s.co  m
* @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 beginUpdatingDNSServer(String serviceName, String deploymentName,
        String dnsServerName, DNSUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (dnsServerName == null) {
        throw new NullPointerException("dnsServerName");
    }
    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("dnsServerName", dnsServerName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingDNSServerAsync", 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 + "/dnsservers/";
    url = url + URLEncoder.encode(dnsServerName, "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", "2015-04-01");

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

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

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

    if (parameters.getAddress() != null) {
        Element addressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Address");
        addressElement.appendChild(requestDoc.createTextNode(parameters.getAddress().getHostAddress()));
        dnsServerElement.appendChild(addressElement);
    }

    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:elh.eus.absa.CorpusReader.java

/**
 * print annotations in Semeval-absa 2015 format
 *
 * @param savePath string : path for the file to save the data 
 * @throws ParserConfigurationException/*from  w  ww  .j ava2s  .c  o m*/
 */
public void print2Semeval2015format(String savePath) throws ParserConfigurationException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    org.w3c.dom.Document doc = docBuilder.newDocument();
    org.w3c.dom.Element rootElement = doc.createElement("Reviews");
    doc.appendChild(rootElement);

    for (String rev : getReviews().keySet()) {
        // review elements
        org.w3c.dom.Element review = doc.createElement("Review");
        rootElement.appendChild(review);

        // set id attribute to sentence element
        review.setAttribute("rid", rev);

        // Sentences element
        org.w3c.dom.Element sentences = doc.createElement("sentences");
        review.appendChild(sentences);

        List<String> processed = new ArrayList<String>();

        for (String sent : this.revSents.get(rev)) {
            if (processed.contains(sent)) {
                continue;
            } else {
                processed.add(sent);
            }
            //System.err.println("creating elements for sentence "+sent);

            // sentence elements
            org.w3c.dom.Element sentence = doc.createElement("sentence");
            sentences.appendChild(sentence);

            // set attribute to sentence element               
            sentence.setAttribute("id", sent);

            // text element of the current sentence
            org.w3c.dom.Element text = doc.createElement("text");
            sentence.appendChild(text);
            text.setTextContent(getSentences().get(sent));

            // Opinions element
            org.w3c.dom.Element opinions = doc.createElement("Opinions");
            sentence.appendChild(opinions);

            for (Opinion op : getSentenceOpinions(sent)) {
                if (op.getCategory().equalsIgnoreCase("NULL")) {
                    continue;
                }
                // opinion elements
                org.w3c.dom.Element opinion = doc.createElement("Opinion");
                opinions.appendChild(opinion);

                // set attributes to the opinion element               
                opinion.setAttribute("target", op.getTarget());
                opinion.setAttribute("category", op.getCategory());
                opinion.setAttribute("polarity", op.getPolarity());
                opinion.setAttribute("from", op.getFrom().toString());
                opinion.setAttribute("to", op.getTo().toString());
            }
        }
    }

    // write the content into xml file
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(savePath));

        // Output to console for testing
        //StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

        System.err.println("File saved to run.xml");

    } catch (TransformerException e) {
        System.err.println("CorpusReader: error when trying to print generated xml result file.");
        e.printStackTrace();
    }
}