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:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static String getCDataText(String s) {
    String cdataText = "";
    try {//from   w w  w .  j  a v  a 2s. c  om
        if (!s.equals("")) {
            Document dom = createDom("java");
            Element root = dom.createElement("root");
            CDATASection cDATASection = dom.createCDATASection(s);
            root.appendChild(cDATASection);
            dom.appendChild(root);

            cdataText = prettyPrintElement(root, true, true);
            cdataText = cdataText.replaceAll("<root>", "");
            cdataText = cdataText.replaceAll("</root>", "");

            String cdataStart = "<![CDATA[";
            if (cdataText.startsWith(cdataStart)) {
                int i = cdataText.substring(cdataStart.length()).indexOf(cdataStart);
                if (i < 0) {
                    cdataText = cdataText.replaceAll("<!\\[CDATA\\[", "");
                    cdataText = cdataText.replaceAll("\\]\\]>", "");
                }
            }
        }
    } catch (ParserConfigurationException e) {
    }
    return cdataText;
}

From source file:com.limegroup.gnutella.archive.ArchiveContribution.java

/**
 * @throws    IllegalStateException/*  www.  ja va2  s .c o  m*/
 *          If java's xml parser configuration is bad
 */
private Document getMetaDocument() {

    /*
     * Sample _meta.xml file:
     * 
     * <metadata>
     *   <collection>opensource_movies</collection>
     *   <mediatype>movies</mediatype>
     *   <title>My Home Movie</title>
     *   <runtime>2:30</runtime>
     *   <director>Joe Producer</director>
     * </metadata>    
     * 
     */

    final String METADATA_ELEMENT = "metadata";
    final String COLLECTION_ELEMENT = "collection";
    final String MEDIATYPE_ELEMENT = "mediatype";
    final String TITLE_ELEMENT = "title";
    final String DESCRIPTION_ELEMENT = "description";
    final String LICENSE_URL_ELEMENT = "licenseurl";
    final String UPLOAD_APPLICATION_ELEMENT = "upload_application";
    final String APPID_ATTR = "appid";
    final String APPID_ATTR_VALUE = "LimeWire";
    final String VERSION_ATTR = "version";
    final String UPLOADER_ELEMENT = "uploader";
    final String IDENTIFIER_ELEMENT = "identifier";
    final String TYPE_ELEMENT = "type";

    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final Document document = db.newDocument();

        final Element metadataElement = document.createElement(METADATA_ELEMENT);
        document.appendChild(metadataElement);

        final Element collectionElement = document.createElement(COLLECTION_ELEMENT);
        metadataElement.appendChild(collectionElement);
        collectionElement.appendChild(document.createTextNode(Archives.getCollectionString(getCollection())));

        final Element mediatypeElement = document.createElement(MEDIATYPE_ELEMENT);
        metadataElement.appendChild(mediatypeElement);
        mediatypeElement.appendChild(document.createTextNode(Archives.getMediaString(getMedia())));

        final Element typeElement = document.createElement(TYPE_ELEMENT);
        metadataElement.appendChild(typeElement);
        typeElement.appendChild(document.createTextNode(Archives.getTypeString(getType())));

        final Element titleElement = document.createElement(TITLE_ELEMENT);
        metadataElement.appendChild(titleElement);
        titleElement.appendChild(document.createTextNode(getTitle()));

        final Element descriptionElement = document.createElement(DESCRIPTION_ELEMENT);
        metadataElement.appendChild(descriptionElement);
        descriptionElement.appendChild(document.createTextNode(getDescription()));

        final Element identifierElement = document.createElement(IDENTIFIER_ELEMENT);
        metadataElement.appendChild(identifierElement);
        identifierElement.appendChild(document.createTextNode(getIdentifier()));

        final Element uploadApplicationElement = document.createElement(UPLOAD_APPLICATION_ELEMENT);
        metadataElement.appendChild(uploadApplicationElement);
        uploadApplicationElement.setAttribute(APPID_ATTR, APPID_ATTR_VALUE);
        uploadApplicationElement.setAttribute(VERSION_ATTR, CommonUtils.getLimeWireVersion());

        final Element uploaderElement = document.createElement(UPLOADER_ELEMENT);
        metadataElement.appendChild(uploaderElement);
        uploaderElement.appendChild(document.createTextNode(getUsername()));

        //take licenseurl from the first File

        final Iterator filesIterator = getFiles().iterator();

        if (filesIterator.hasNext()) {
            final File firstFile = (File) filesIterator.next();
            final String licenseUrl = firstFile.getLicenseUrl();
            if (licenseUrl != null) {
                final Element licenseUrlElement = document.createElement(LICENSE_URL_ELEMENT);
                metadataElement.appendChild(licenseUrlElement);
                licenseUrlElement.appendChild(document.createTextNode(licenseUrl));
            }
        }

        // now build user-defined elements
        final Map userFields = getFields();
        for (final Iterator i = userFields.keySet().iterator(); i.hasNext();) {
            final Object field = i.next();
            final Object value = userFields.get(field);

            if (field instanceof String) {
                final Element e = document.createElement((String) field);
                metadataElement.appendChild(e);

                if (value != null && value instanceof String) {
                    e.appendChild(document.createTextNode((String) value));
                }
            }
        }

        return document;

    } catch (final ParserConfigurationException e) {
        final IllegalStateException ise = new IllegalStateException();
        ise.initCause(e);
        throw ise;
    }
}

From source file:jp.co.opentone.bsol.framework.core.generator.excel.strategy.XmlWorkbookGeneratorStrategy.java

public byte[] generate(WorkbookGeneratorContext context) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("generate start");
    }/*from ww w. j a v a 2  s .co m*/
    checkState(context);

    Document doc;
    try {
        doc = createDocument();
    } catch (ParserConfigurationException e) {
        throw new GeneratorFailedException(e);
    }

    Element book = createWorkbook(context, doc);
    doc.appendChild(book);
    Element sheet = createWorksheet(context, doc);
    book.appendChild(sheet);

    Element table = createTable(context, doc);
    sheet.appendChild(table);

    Element header = createHeader(context, doc);
    if (header != null) {
        table.appendChild(header);
    }

    List<Element> rows = createRows(context, doc);
    for (Element row : rows) {
        table.appendChild(row);
    }
    return toByte(doc);
}

From source file:com.microsoft.windowsazure.management.sql.RecoverDatabaseOperationsImpl.java

/**
* Issues a recovery request for an Azure SQL Database.
*
* @param sourceServerName Required. The name of the Azure SQL Database
* Server on which the database was hosted.
* @param parameters Required. Additional parameters for the Create Recover
* Database Operation request./* w  w w. j  av  a2  s  .com*/
* @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 Contains the response to the Create Recover Database Operation
* request.
*/
@Override
public RecoverDatabaseOperationCreateResponse create(String sourceServerName,
        RecoverDatabaseOperationCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (sourceServerName == null) {
        throw new NullPointerException("sourceServerName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getSourceDatabaseName() == null) {
        throw new NullPointerException("parameters.SourceDatabaseName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(sourceServerName, "UTF-8");
    url = url + "/recoverdatabaseoperations";
    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", "2012-03-01");

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

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

    Element sourceDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "SourceDatabaseName");
    sourceDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getSourceDatabaseName()));
    serviceResourceElement.appendChild(sourceDatabaseNameElement);

    if (parameters.getTargetServerName() != null) {
        Element targetServerNameElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetServerName");
        targetServerNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetServerName()));
        serviceResourceElement.appendChild(targetServerNameElement);
    }

    if (parameters.getTargetDatabaseName() != null) {
        Element targetDatabaseNameElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetDatabaseName");
        targetDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetDatabaseName()));
        serviceResourceElement.appendChild(targetDatabaseNameElement);
    }

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

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

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

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                RecoverDatabaseOperation serviceResourceInstance = new RecoverDatabaseOperation();
                result.setOperation(serviceResourceInstance);

                Element requestIDElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "RequestID");
                if (requestIDElement != null) {
                    String requestIDInstance;
                    requestIDInstance = requestIDElement.getTextContent();
                    serviceResourceInstance.setId(requestIDInstance);
                }

                Element sourceDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName");
                if (sourceDatabaseNameElement2 != null) {
                    String sourceDatabaseNameInstance;
                    sourceDatabaseNameInstance = sourceDatabaseNameElement2.getTextContent();
                    serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance);
                }

                Element targetServerNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "TargetServerName");
                if (targetServerNameElement2 != null) {
                    String targetServerNameInstance;
                    targetServerNameInstance = targetServerNameElement2.getTextContent();
                    serviceResourceInstance.setTargetServerName(targetServerNameInstance);
                }

                Element targetDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "TargetDatabaseName");
                if (targetDatabaseNameElement2 != null) {
                    String targetDatabaseNameInstance;
                    targetDatabaseNameInstance = targetDatabaseNameElement2.getTextContent();
                    serviceResourceInstance.setTargetDatabaseName(targetDatabaseNameInstance);
                }

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

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        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:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java

public Document buildGetIdentityLinkRequest(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname,
        String PEPSDateOfBirth, String signature, String representative, String represented,
        String mandateContent) throws SZRGWClientException {

    String SZRGW_NS = "http://reference.e-government.gv.at/namespace/szrgw/20070807#";
    try {//from  w  w  w. j  a  v a  2s .c  om
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();

        Element getIdentityLink = doc.createElementNS(SZRGW_NS, "szrgw:GetIdentityLinkRequest");
        getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGW_NS);
        doc.appendChild(getIdentityLink);

        if ((PEPSIdentifier != null) || (PEPSFirstname != null) || (PEPSFamilyname != null)
                || (PEPSDateOfBirth != null)) {

            Element pepsDataElem = doc.createElementNS(SZRGW_NS, "szrgw:PEPSData");
            getIdentityLink.appendChild(pepsDataElem);

            if (PEPSIdentifier != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Identifier");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSIdentifier);
                elem.appendChild(text);
            }
            if (PEPSFirstname != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Firstname");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSFirstname);
                elem.appendChild(text);
            }

            if (PEPSFamilyname != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Familyname");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSFamilyname);
                elem.appendChild(text);
            }

            if (PEPSDateOfBirth != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:DateOfBirth");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSDateOfBirth);
                elem.appendChild(text);
            }

            if (representative != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Representative");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(representative);
                elem.appendChild(text);
            }

            if (represented != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Represented");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(represented);
                elem.appendChild(text);
            }

            if (mandateContent != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:MandateContent");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(mandateContent);
                elem.appendChild(text);
            }
        }

        if (signature == null)
            throw new SZRGWClientException("Signature element must not be null!");
        else {
            Element sig = doc.createElementNS(SZRGW_NS, "szrgw:Signature");
            Element base64content = doc.createElementNS(SZRGW_NS, "szrgw:Base64Content");
            sig.appendChild(base64content);
            getIdentityLink.appendChild(sig);
            Text text = doc.createTextNode(signature);
            base64content.appendChild(text);
        }

        if (representative != null && represented != null && mandateContent != null) {
            Element mis = doc.createElementNS(SZRGW_NS, "szrgw:MIS");
            Element filters = doc.createElementNS(SZRGW_NS, "szrgw:Filters");
            mis.appendChild(filters);
            Element target = doc.createElementNS(SZRGW_NS, "szrgw:Target");
            mis.appendChild(target);
            Element friendlyName = doc.createElementNS(SZRGW_NS, "szrgw:OAFriendlyName");
            mis.appendChild(friendlyName);
            getIdentityLink.appendChild(mis);

            //            TODO fetch data from oa params
            //             String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID);
            //             moasessionid = StringEscapeUtils.escapeHtml(moasessionid);
            //              AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moasessionid);
            //             OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix());
            //             if (oaParam == null)
            //                   throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() });
            //              Text text = doc.createTextNode(oaParam.getFriendlyName());
        }

        return doc;
    } catch (ParserConfigurationException e) {
        throw new SZRGWClientException(e);
    } /*catch (CertificateEncodingException e) {
       throw new SZRGWClientException(e);
      }*/

}

From source file:be.fedict.eid.pkira.xkmsws.util.XMLMarshallingUtil.java

public void removeSoapHeaders(Document document) {
    NodeList bodyNodes = document.getElementsByTagNameNS(NAMESPACE_SOAP, "Body");
    if (bodyNodes != null && bodyNodes.getLength() == 1) {
        Element body = (Element) bodyNodes.item(0);

        NodeList children = body.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i) instanceof Element) {
                document.removeChild(document.getDocumentElement());
                document.appendChild(children.item(i));
                break;
            }//from  w w w. j a v  a  2 s .c om
        }
    }
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Generates an XML document from list of elements
 *
 * @param elements/* w  w  w.j av a2  s.  c o m*/
 * @return
 */
public static Document getDocumentFromList(List<Element> elements) throws MetsExportException {
    Document document = null;
    try {
        DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
        builder.setValidating(true);
        builder.setNamespaceAware(true);
        document = builder.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new MetsExportException("Error while getting document from list", false, e1);
    }

    for (Element element : elements) {
        Node newNode = element.cloneNode(true);
        document.adoptNode(newNode);
        document.appendChild(newNode);
    }
    return document;
}

From source file:com.mirth.connect.server.migration.Migrate3_0_0.java

private void migrateAlertTable() {
    Logger logger = Logger.getLogger(getClass());
    PreparedStatement statement = null;
    ResultSet results = null;/*from  w  ww .  j a  v a  2s .com*/

    try {
        Map<String, List<String>> alertEmails = new HashMap<String, List<String>>();
        Map<String, List<String>> alertChannels = new HashMap<String, List<String>>();

        /*
         * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of
         * results. The following error occurs: "ERROR 40XD0: Container has been closed"
         */
        Connection connection = getConnection();
        connection.setAutoCommit(false);

        // Build a list of emails for each alert
        statement = connection.prepareStatement("SELECT ALERT_ID, EMAIL FROM OLD_ALERT_EMAIL");
        results = statement.executeQuery();

        while (results.next()) {
            String alertId = results.getString(1);
            String email = results.getString(2);

            List<String> emailSet = alertEmails.get(alertId);

            if (emailSet == null) {
                emailSet = new ArrayList<String>();
                alertEmails.put(alertId, emailSet);
            }

            emailSet.add(email);
        }

        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(statement);

        // Build a list of applied channels for each alert
        statement = connection.prepareStatement("SELECT CHANNEL_ID, ALERT_ID FROM OLD_CHANNEL_ALERT");
        results = statement.executeQuery();

        while (results.next()) {
            String channelId = results.getString(1);
            String alertId = results.getString(2);

            List<String> channelSet = alertChannels.get(alertId);

            if (channelSet == null) {
                channelSet = new ArrayList<String>();
                alertChannels.put(alertId, channelSet);
            }

            channelSet.add(channelId);
        }

        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(statement);

        statement = connection
                .prepareStatement("SELECT ID, NAME, IS_ENABLED, EXPRESSION, TEMPLATE, SUBJECT FROM OLD_ALERT");
        results = statement.executeQuery();

        while (results.next()) {
            String alertId = "";

            try {
                alertId = results.getString(1);
                String name = results.getString(2);
                boolean enabled = results.getBoolean(3);
                String expression = results.getString(4);
                String template = results.getString(5);
                String subject = results.getString(6);

                /*
                 * Create a new document with alertModel as the root node
                 */
                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element alertNode = document.createElement("alert");
                document.appendChild(alertNode);

                Element node = document.createElement("id");
                node.setTextContent(alertId);
                alertNode.appendChild(node);

                node = document.createElement("name");
                node.setTextContent(name);
                alertNode.appendChild(node);

                node = document.createElement("expression");
                node.setTextContent(expression);
                alertNode.appendChild(node);

                node = document.createElement("template");
                node.setTextContent(template);
                alertNode.appendChild(node);

                node = document.createElement("enabled");
                node.setTextContent(Boolean.toString(enabled));
                alertNode.appendChild(node);

                node = document.createElement("subject");
                node.setTextContent(subject);
                alertNode.appendChild(node);

                // Add each applied channel to the document
                Element channelNode = document.createElement("channels");
                alertNode.appendChild(channelNode);
                List<String> channelList = alertChannels.get(alertId);
                if (channelList != null) {
                    for (String channelId : channelList) {
                        Element stringNode = document.createElement("string");
                        stringNode.setTextContent(channelId);
                        channelNode.appendChild(stringNode);
                    }
                }

                // Add each email address to the document
                Element emailNode = document.createElement("emails");
                alertNode.appendChild(emailNode);
                List<String> emailList = alertEmails.get(alertId);
                if (emailList != null) {
                    for (String email : emailList) {
                        Element stringNode = document.createElement("string");
                        stringNode.setTextContent(email);
                        emailNode.appendChild(stringNode);
                    }
                }

                String alert = new DonkeyElement(alertNode).toXml();

                PreparedStatement updateStatement = null;

                try {
                    updateStatement = connection.prepareStatement("INSERT INTO ALERT VALUES (?, ?, ?)");
                    updateStatement.setString(1, alertId);
                    updateStatement.setString(2, name);
                    updateStatement.setString(3, alert);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                } finally {
                    DbUtils.closeQuietly(updateStatement);
                }
            } catch (Exception e) {
                logger.error("Error migrating alert " + alertId + ".", e);
            }
        }

        connection.commit();
    } catch (SQLException e) {
        logger.error("Error migrating alerts.", e);
    } finally {
        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java

public DOMSource generateDashPlaylist(UUID id, String baseUrl) {
    Job job = jobDao.getJobByID(id);/*from  w  w w.  jav a  2s.com*/

    if (job == null) {
        return null;
    }

    MediaElement mediaElement = mediaDao.getMediaElementByID(job.getMediaElement());

    if (mediaElement == null) {
        return null;
    }

    baseUrl = baseUrl + "/stream/segment/" + id + "/";

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

        // Root elements
        Document playlist = docBuilder.newDocument();
        Element mpd = playlist.createElement("MPD");
        playlist.appendChild(mpd);

        mpd.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        mpd.setAttribute("xmlns", "urn:mpeg:dash:schema:mpd:2011");
        mpd.setAttribute("xsi:schemaLocation", "urn:mpeg:DASH:schema:MPD:2011 DASH-MPD.xsd");
        //mpd.setAttribute("profiles", "urn:mpeg:dash:profile:full:2011");
        mpd.setAttribute("profiles", "urn:mpeg:dash:profile:isoff-live:2011");
        mpd.setAttribute("minBufferTime", "PT" + DASH_SEGMENT_DURATION + "S");
        mpd.setAttribute("type", "static");
        mpd.setAttribute("mediaPresentationDuration", "PT" + mediaElement.getDuration() + "S");

        Element period = playlist.createElement("Period");
        mpd.appendChild(period);

        period.setAttribute("duration", "PT" + mediaElement.getDuration() + "S");

        Element adaptationSet = playlist.createElement("AdaptationSet");
        period.appendChild(adaptationSet);

        adaptationSet.setAttribute("segmentAlignment", "true");
        adaptationSet.setAttribute("contentType", "audio");

        Element representation = playlist.createElement("Representation");
        adaptationSet.appendChild(representation);

        representation.setAttribute("id", "audio");
        representation.setAttribute("mimeType", "audio/mp4");
        representation.setAttribute("codecs", "mp4a.40.2");
        representation.setAttribute("audioSamplingRate", "44100");
        representation.setAttribute("bandwidth", "128000");

        Element audioChannelConfig = playlist.createElement("AudioChannelConfiguration");
        representation.appendChild(audioChannelConfig);

        audioChannelConfig.setAttribute("schemeIdUri",
                "urn:mpeg:dash:23003:3:audio_channel_configuration:2011");
        audioChannelConfig.setAttribute("value", "2");

        Element segmentTemplate = playlist.createElement("SegmentTemplate");
        representation.appendChild(segmentTemplate);

        segmentTemplate.setAttribute("duration", "5000");
        segmentTemplate.setAttribute("initialization", baseUrl + "init-stream0.m4s");
        segmentTemplate.setAttribute("media", baseUrl + "chunk-stream0-$Number%05d$.m4s");
        segmentTemplate.setAttribute("startNumber", "1");

        DOMSource result = new DOMSource(playlist);
        return result;
    } catch (ParserConfigurationException ex) {
        return null;
    }
}

From source file:com.hp.mqm.atrf.App.java

private void convertToXml(List<TestRunResultEntity> runResults, StreamResult result, boolean formatXml) {

    try {//from w w w  . j  ava 2  s . co m
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

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

        Element testRuns = doc.createElement("test_runs");
        rootElement.appendChild(testRuns);

        for (TestRunResultEntity runResult : runResults) {
            Element testRun = doc.createElement("test_run");
            testRuns.appendChild(testRun);

            testRun.setAttribute("module", runResult.getModule());
            testRun.setAttribute("package", runResult.getPackageValue());
            testRun.setAttribute("class", runResult.getClassValue());
            testRun.setAttribute("name", runResult.getTestName());

            testRun.setAttribute("duration", runResult.getDuration());
            testRun.setAttribute("status", runResult.getStatus());
            testRun.setAttribute("started", runResult.getStartedTime());
            testRun.setAttribute("external_report_url", runResult.getExternalReportUrl());
            testRun.setAttribute("run_name", runResult.getRunName());

            Element testFields = doc.createElement("test_fields");
            testRun.appendChild(testFields);

            if (StringUtils.isNotEmpty(runResult.getTestingToolType())) {
                Element testField = doc.createElement("test_field");
                testFields.appendChild(testField);
                testField.setAttribute("type", "Testing_Tool_Type");
                testField.setAttribute("value", runResult.getTestingToolType());
            }

            if (OCTANE_RUN_FAILED_STATUS.equals(runResult.getStatus())) {
                Element error = doc.createElement("error");
                testRun.appendChild(error);

                error.setAttribute("type", "Error");
                error.setAttribute("message",
                        "For more details , goto ALM run : " + runResult.getExternalReportUrl());
            }
        }

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        if (formatXml) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        DOMSource source = new DOMSource(doc);

        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}