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.enonic.vertical.engine.handlers.ContentObjectHandler.java

public void updateContentObject(Document doc) throws VerticalUpdateException {
    Element docElem = doc.getDocumentElement();
    Element[] contentobjectElems;
    if ("contentobject".equals(docElem.getTagName())) {
        contentobjectElems = new Element[] { docElem };
    } else {//from   w ww . ja  v  a2  s.  c  om
        contentobjectElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    int pos = 0;
    String tmpStr = null;

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(COB_UPDATE);

        for (Element root : contentobjectElems) {
            Map subelems = XMLTool.filterElements(root.getChildNodes());

            int key = -1, menuKey = -1;
            ResourceKey styleSheetKey = null, borderStyleSheetKey = null;

            pos = 0;
            tmpStr = root.getAttribute("key");
            if (tmpStr != null && tmpStr.length() > 0) {
                key = Integer.parseInt(tmpStr);
            } else {
                String message = "No content object key specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            // was sitekey

            pos++;
            tmpStr = root.getAttribute("menukey");
            if (tmpStr != null && tmpStr.length() > 0) {
                menuKey = Integer.parseInt(tmpStr);
            } else {
                String message = "No menu key specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            Element subelem = (Element) subelems.get("objectstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    styleSheetKey = new ResourceKey(tmpStr);
                } else {
                    String message = "No object stylesheet key specified.";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No object stylesheet specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            subelem = (Element) subelems.get("borderstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    borderStyleSheetKey = new ResourceKey(tmpStr);
                }
            }

            // element: name
            String name = null;
            subelem = (Element) subelems.get("name");
            if (subelem != null) {
                name = XMLTool.getElementText(subelem);
                if (name == null || name.length() == 0) {
                    String message = "Empty stylesheet name.";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No stylesheet name specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            // element: contentobjectdata (optional)
            byte[] contentobjectdata;
            subelem = (Element) subelems.get("contentobjectdata");
            if (subelem != null) {
                Document codDoc = XMLTool.createDocument();
                codDoc.appendChild(codDoc.importNode(subelem, true));
                contentobjectdata = XMLTool.documentToBytes(codDoc, "UTF-8");
            } else {
                contentobjectdata = null;
            }

            preparedStmt.setInt(7, key);
            preparedStmt.setInt(1, menuKey);
            if (styleSheetKey != null) {
                preparedStmt.setString(2, styleSheetKey.toString());
            } else {
                preparedStmt.setNull(2, Types.VARCHAR);
            }
            if (borderStyleSheetKey != null) {
                preparedStmt.setString(3, borderStyleSheetKey.toString());
            } else {
                preparedStmt.setNull(3, Types.VARCHAR);
            }
            preparedStmt.setCharacterStream(4, new StringReader(name), name.length());
            if (contentobjectdata != null) {
                preparedStmt.setBinaryStream(5, new ByteArrayInputStream(contentobjectdata),
                        contentobjectdata.length);
            } else {
                preparedStmt.setNull(5, Types.VARCHAR);
            }

            RunAsType runAs = RunAsType.INHERIT;
            String runAsStr = root.getAttribute("runAs");
            if (StringUtils.isNotEmpty(runAsStr)) {
                runAs = RunAsType.valueOf(runAsStr);
            }
            preparedStmt.setInt(6, runAs.getKey());

            // update content object
            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to update content object, no content object updated.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }
        }

        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "Failed to update content object(s): %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse %0: %1";
        Object[] msgData;
        switch (pos) {
        case 1:
            msgData = new Object[] { "site key", tmpStr };
            break;
        case 2:
            msgData = new Object[] { "menu key", tmpStr };
            break;
        case 3:
            msgData = new Object[] { "object stylesheet key", tmpStr };
            break;
        case 4:
            msgData = new Object[] { "border stylesheet key", tmpStr };
            break;
        default:
            msgData = new Object[] { "content object key", tmpStr };
        }
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, msgData, nfe);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

From source file:org.hammurapi.inspectors.history.HistoryInspector.java

public void leave(Repository repository) {
    getContext().annotate(new LinkedAnnotation() {
        NamedResults summary = ResultsFactory.getThreadResults();
        FileEntry rootFile;/*from  w  ww  . ja va 2s .c  o  m*/

        public String getName() {
            return "History";
        }

        public void render(AnnotationContext context) throws HammurapiException {
            if (ResultsFactory.getInstance() instanceof org.hammurapi.results.persistent.jdbc.ResultsFactory) {
                try {
                    SQLProcessor processor = getContext().getSession().getProcessor();
                    HistoryEngine historyEngine = new HistoryEngine(processor);
                    ResultsEngine resultsEngine = new ResultsEngine(processor);
                    Iterator it = historyEngine.getReportWithoutHistory(summary.getName(),
                            ((org.hammurapi.results.persistent.jdbc.ResultsFactory) ResultsFactory
                                    .getInstance()).getReportId())
                            .iterator();
                    while (it.hasNext()) {
                        Report report = (Report) it.next();
                        BasicResultTotal result = resultsEngine
                                .getBasicResultTotal(report.getResultId().intValue());
                        AggregatedResultsMetricData cr = resultsEngine.getAggregatedResultsMetricData(
                                report.getResultId().intValue(), "Change ratio");

                        historyEngine.insertHistory(report.getId(), result.getCodebase(),
                                (Integer) CompositeConverter.getDefaultConverter()
                                        .convert(result.getMaxSeverity(), Integer.class, false),
                                result.getReviews(), result.getViolationLevel(), result.getViolations(),
                                result.getWaivedViolations(), (int) result.getHasWarnings(),
                                cr == null ? -1 : cr.getTotalValue() / cr.getMeasurements(),
                                result.getCompilationUnits(), result.getResultDate(), report.getName(),
                                report.getDescription(), new Long(report.getExecutionTime() == null ? 0
                                        : report.getExecutionTime().longValue()));
                    }

                    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                    Element root = doc.createElement("history");
                    root.setAttribute("title", summary.getName());
                    doc.appendChild(root);
                    Collection series = new ArrayList();
                    DOMUtils.toDom(historyEngine.getJoinedHistory(summary.getName(), series,
                            JoinedHistoryImplEx.class), root);

                    // Generate charts here
                    if (series.size() > 1) {
                        generateNodesChart(context, root, series);
                        generateFilesChart(context, root, series);
                        generateActivityChart(context, root, series);
                        generateSigmaChart(context, root, series);
                        generateDpmoChart(context, root, series);
                        generateMaxSeverityChart(context, root, series);
                        generateViolationsChart(context, root, series);
                        generateReviewsChart(context, root, series);
                        //generatePerformanceChart(context, root, series);
                    }

                    rootFile = context.getNextFile(context.getExtension());

                    if (context.getExtension().equalsIgnoreCase(".html")) {
                        TransformerFactory tFactory = TransformerFactory.newInstance();
                        InputStream styleStream = styleConfig.getStream();
                        if (styleStream == null) {
                            throw new HammurapiException("Stylesheet cannot be loaded");
                        }

                        Transformer transformer = tFactory.newTransformer(new StreamSource(styleStream));

                        DOMSource domSource = new DOMSource(doc);
                        transformer.transform(domSource, new StreamResult(rootFile.getFile()));
                    } else {
                        DOMUtils.serialize(doc, rootFile.getFile());
                    }
                } catch (ConfigurationException e) {
                    throw new HammurapiException("Cannot render history annotation, " + e.getMessage(), e);
                } catch (IOException e) {
                    throw new HammurapiException("Cannot render history annotation, " + e.getMessage(), e);
                } catch (SQLException e) {
                    throw new HammurapiException("Cannot process history annotation, " + e.getMessage(), e);
                } catch (ParserConfigurationException e) {
                    throw new HammurapiException("Cannot process history annotation, " + e.getMessage(), e);
                } catch (FactoryConfigurationError e) {
                    throw new HammurapiException("Cannot process history annotation, " + e.getMessage(), e);
                } catch (TransformerConfigurationException e) {
                    throw new HammurapiException("Cannot process history annotation, " + e.getMessage(), e);
                } catch (TransformerException e) {
                    throw new HammurapiException("Cannot process history annotation, " + e.getMessage(), e);
                }
            }
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateNodesChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator codeBaseChartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    return new Long(jhie.getCodebase());
                }
            };

            FileEntry codeBaseNodesChart = context.getNextFile(".png");
            TimeSeries cbtn = codeBaseChartGenerator.createTimeSeries(series, "Nodes");
            codeBaseChartGenerator.createPngChart("Codebase history (nodes)", cbtn,
                    codeBaseNodesChart.getFile());
            root.setAttribute("nodes-chart", codeBaseNodesChart.getPath());
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateFilesChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator codeBaseChartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    return new Long(jhie.getCompilationUnits());
                }
            };

            FileEntry codeBaseChart = context.getNextFile(".png");
            TimeSeries cbtn = codeBaseChartGenerator.createTimeSeries(series, "Files");
            codeBaseChartGenerator.createPngChart("Codebase history (files)", cbtn, codeBaseChart.getFile());
            root.setAttribute("files-chart", codeBaseChart.getPath());
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateActivityChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator chartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    return new Integer((int) (jhie.getChangeRatio() * 100));
                }
            };

            FileEntry fileEntry = context.getNextFile(".png");
            TimeSeries cbtn = chartGenerator.createTimeSeries(series, "Activity (%)");
            chartGenerator.createPngBarChart("Activity history", cbtn, fileEntry.getFile());
            root.setAttribute("activity-chart", fileEntry.getPath());
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateSigmaChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator chartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    String sigma = jhie.getSigma();
                    int idx = sigma.indexOf(' ');
                    try {
                        return new Double(idx == -1 ? sigma : sigma.substring(0, idx));
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
            };

            FileEntry fileEntry = context.getNextFile(".png");
            TimeSeries cbtn = chartGenerator.createTimeSeries(series, "Sigma");
            chartGenerator.createPngChart("Sigma history", cbtn, fileEntry.getFile());
            root.setAttribute("sigma-chart", fileEntry.getPath());
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateDpmoChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator chartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    String dpmo = jhie.getDPMO();
                    int idx = dpmo.indexOf(' ');
                    try {
                        return new Long(idx == -1 ? dpmo : dpmo.substring(0, idx));
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
            };

            FileEntry fileEntry = context.getNextFile(".png");
            TimeSeries cbtn = chartGenerator.createTimeSeries(series, "DPMO");
            chartGenerator.createPngChart("DPMO history", cbtn, fileEntry.getFile());
            root.setAttribute("dpmo-chart", fileEntry.getPath());
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateViolationsChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator chartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    return new Long(jhie.getViolations());
                }
            };

            FileEntry fileEntry = context.getNextFile(".png");
            TimeSeries cbtn = chartGenerator.createTimeSeries(series, "Violations");
            chartGenerator.createPngChart("Violations history", cbtn, fileEntry.getFile());
            root.setAttribute("violations-chart", fileEntry.getPath());
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateMaxSeverityChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator chartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    return new Integer(jhie.getMaxSeverity());
                }
            };

            FileEntry fileEntry = context.getNextFile(".png");
            TimeSeries cbtn = chartGenerator.createTimeSeries(series, "Max severity");
            chartGenerator.createPngChart("Max severity history", cbtn, fileEntry.getFile());
            root.setAttribute("max-severity-chart", fileEntry.getPath());
        }

        /**
         * @param context
         * @param root
         * @param series
         * @throws HammurapiException
         * @throws IOException
         */
        private void generateReviewsChart(AnnotationContext context, Element root, Collection series)
                throws HammurapiException, IOException {
            TimeChartGenerator chartGenerator = new TimeChartGenerator() {
                Number getValue(JoinedHistoryImplEx jhie) {
                    return new Long(jhie.getReviews());
                }
            };

            FileEntry fileEntry = context.getNextFile(".png");
            TimeSeries cbtn = chartGenerator.createTimeSeries(series, "Reviews");
            chartGenerator.createPngChart("Reviews history", cbtn, fileEntry.getFile());
            root.setAttribute("reviews-chart", fileEntry.getPath());
        }

        public Properties getProperties() {
            return null;
        }

        public String getPath() {
            return rootFile.getPath();
        }

    });
}

From source file:fi.helsinki.lib.simplerest.ItemsResource.java

@Get("html|xhtml|xml")
public Representation toXml() {
    Collection collection = null;
    DomRepresentation representation = null;
    Document d = null;
    try {//w ww  .  j a va 2s .c  om
        collection = Collection.find(context, this.collectionId);
        if (collection == null) {
            return errorNotFound(context, "Could not find the collection.");
        }

        representation = new DomRepresentation(MediaType.TEXT_HTML);
        d = representation.getDocument();
    } catch (SQLException e) {
        return errorInternal(context, e.toString());
    } catch (IOException e) {
        return errorInternal(context, e.toString());
    }

    Element html = d.createElement("html");
    d.appendChild(html);

    Element head = d.createElement("head");
    html.appendChild(head);

    Element title = d.createElement("title");
    head.appendChild(title);
    title.appendChild(d.createTextNode("Items for collection " + collection.getName()));

    Element body = d.createElement("body");
    html.appendChild(body);

    Element ulItems = d.createElement("ul");
    setId(ulItems, "items");
    body.appendChild(ulItems);

    String base = baseUrl();
    try {
        ItemIterator ii = collection.getItems();
        while (ii.hasNext()) {
            Item item = ii.next();
            Element li = d.createElement("li");
            Element a = d.createElement("a");
            String name = item.getName();
            if (name == null) {
                // FIXME: Should we really give names for items with no
                // FIXME: name? (And if so does "Untitled" make sense?)
                // FIXME: Anyway, this would break with null values.
                name = "Untitled";
            }
            a.appendChild(d.createTextNode(name));
            String href = base + ItemResource.relativeUrl(item.getID());
            setAttribute(a, "href", href);
            li.appendChild(a);
            ulItems.appendChild(li);
        }
    } catch (SQLException e) {
        String errMsg = "SQLException while trying to items of the collection. " + e.getMessage();
        return errorInternal(context, errMsg);
    }

    Element form = d.createElement("form");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("method", "post");
    makeInputRow(d, form, "title", "Title");
    makeInputRow(d, form, "lang", "Language");

    Element submitButton = d.createElement("input");
    submitButton.setAttribute("type", "submit");
    submitButton.setAttribute("value", "Create a new item");
    form.appendChild(submitButton);

    body.appendChild(form);

    try {
        if (context != null) {
            context.complete();
        }
    } catch (SQLException e) {
        log.log(Priority.INFO, e);
    }

    return representation;
}

From source file:com.enonic.vertical.engine.handlers.ContentObjectHandler.java

public int[] createContentObject(CopyContext copyContext, Document doc, boolean useOldKey)
        throws VerticalCreateException {

    Element docElem = doc.getDocumentElement();
    Element[] contentobjectElems;
    if ("contentobject".equals(docElem.getTagName())) {
        contentobjectElems = new Element[] { docElem };
    } else {//from  w ww. j a  va 2 s. co m
        contentobjectElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    int pos = 0;
    String tmpStr = null;
    TIntArrayList newKeys = new TIntArrayList();

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(COB_CREATE);

        for (Element root : contentobjectElems) {
            Map subelems = XMLTool.filterElements(root.getChildNodes());

            int key, menuKey = -1;
            String styleSheetKey = "", borderStyleSheetKey = "";

            pos = 0;
            String keyStr = root.getAttribute("key");
            if (!useOldKey || tmpStr == null || tmpStr.length() == 0) {
                key = getNextKey(COB_TABLE);
            } else {
                key = Integer.parseInt(tmpStr);
            }
            if (copyContext != null) {
                copyContext.putContentObjectKey(Integer.parseInt(keyStr), key);
            }
            newKeys.add(key);

            pos++;
            // was sitekey

            pos++;
            tmpStr = root.getAttribute("menukey");
            if (tmpStr != null && tmpStr.length() > 0) {
                menuKey = Integer.parseInt(tmpStr);
            } else {
                String message = "No menu key specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            pos++;
            Element subelem = (Element) subelems.get("objectstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    styleSheetKey = tmpStr;
                } else {
                    String message = "No object stylesheet key specified.";
                    VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No object stylesheet specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            pos++;
            subelem = (Element) subelems.get("borderstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    borderStyleSheetKey = tmpStr;
                }
            }

            String name = null;
            byte[] contentobjectdata;

            // element: name
            subelem = (Element) subelems.get("name");
            if (subelem != null) {
                name = XMLTool.getElementText(subelem);
                if (name == null || name.length() == 0) {
                    String message = "Empty stylesheet name.";
                    VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No stylesheet name specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            // element: contentobjectdata (optional)
            subelem = (Element) subelems.get("contentobjectdata");
            if (subelem != null) {
                Document codDoc = XMLTool.createDocument();
                codDoc.appendChild(codDoc.importNode(subelem, true));
                contentobjectdata = XMLTool.documentToBytes(codDoc, "UTF-8");
            } else {
                contentobjectdata = null;
            }

            preparedStmt.setInt(1, key);
            preparedStmt.setInt(2, menuKey);
            preparedStmt.setString(3, styleSheetKey);
            if (borderStyleSheetKey.length() > 0) {
                preparedStmt.setString(4, borderStyleSheetKey);
            } else {
                preparedStmt.setNull(4, Types.VARCHAR);
            }
            preparedStmt.setString(5, name);
            if (contentobjectdata != null) {
                preparedStmt.setBinaryStream(6, new ByteArrayInputStream(contentobjectdata),
                        contentobjectdata.length);
            } else {
                preparedStmt.setNull(6, Types.VARBINARY);
            }

            RunAsType runAs = RunAsType.INHERIT;
            String runAsStr = root.getAttribute("runAs");
            if (StringUtils.isNotEmpty(runAsStr)) {
                runAs = RunAsType.valueOf(runAsStr);
            }
            preparedStmt.setInt(7, runAs.getKey());

            // create content object
            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to create content object, no content object created.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }
        }

        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "Failed to create content object(s): %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse %0: %1";
        Object[] msgData;
        switch (pos) {
        case 1:
            msgData = new Object[] { "site key", tmpStr };
            break;
        case 2:
            msgData = new Object[] { "menu key", tmpStr };
            break;
        case 3:
            msgData = new Object[] { "object stylesheet key", tmpStr };
            break;
        case 4:
            msgData = new Object[] { "border stylesheet key", tmpStr };
            break;
        default:
            msgData = new Object[] { "content object key", tmpStr };
        }
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, msgData, nfe);
    } catch (VerticalKeyException gke) {
        String message = "Failed to generate content object key";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, gke);
    } finally {
        close(preparedStmt);
        close(con);
    }

    return newKeys.toArray();
}

From source file:net.sf.jabref.logic.msbib.MSBibDatabase.java

public Document getDOM() {
    Document document = null;
    try {//  w  w w .jav  a 2  s.c o  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        document = documentBuilder.newDocument();

        Element rootNode = document.createElementNS(NAMESPACE, PREFIX + "Sources");
        rootNode.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", NAMESPACE);
        rootNode.setAttributeNS("http://www.w3.org/2000/xmlns/",
                "xmlns:" + PREFIX.substring(0, PREFIX.length() - 1), NAMESPACE);
        rootNode.setAttribute("SelectedStyle", "");

        for (MSBibEntry entry : entries) {
            Node node = entry.getDOM(document);
            rootNode.appendChild(node);
        }

        document.appendChild(rootNode);
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Could not build XML document", e);
    }

    return document;
}

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

public Document generateDASHPlaylist(long id, String baseUrl) {

    Job job = jobDao.getJobByID(id);//from   ww  w  . j  a  v a  2s.  c  om

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

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

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

    AdaptiveStreamingProfile profile = getProfileByID(id);

    if (profile == null) {
        LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME,
                "Unable to get transcode profile to generate manifest for job " + id, null);
        return null;
    }

    // Transcode Parameters
    Dimension resolution = transcodeService.getVideoResolution(profile.getVideoQuality(), mediaElement);
    String codec;
    String mimeType;

    switch (profile.getType()) {
    case StreamType.DASH:
        codec = "avc1";
        mimeType = "video/MP2T";
        break;

    case StreamType.DASH_MP4:
        codec = "avc1";
        mimeType = "video/mp4";
        break;

    case StreamType.DASH_WEBM:
        codec = "vp8";
        mimeType = "video/webm";
        break;

    default:
        return null;
    }

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

        // Root MPD Element
        Document mpd = docBuilder.newDocument();
        Element root = mpd.createElement("MPD");
        root.setAttribute("xmnls", "urn:mpeg:dash:schema:mpd:2011");
        root.setAttribute("profiles", "urn:mpeg:dash:profile:isoff-on-demand:2011");
        root.setAttribute("type", "static");
        root.setAttribute("mediaPresentationDuration", "PT" + mediaElement.getDuration() + "S");
        root.setAttribute("minBufferTime", "PT2.0S");
        mpd.appendChild(root);

        // Program Information
        Element programInformation = mpd.createElement("ProgramInformation");
        root.appendChild(programInformation);

        // Title
        Element title = mpd.createElement("Title");
        title.appendChild(mpd.createTextNode(mediaElement.getTitle()));
        programInformation.appendChild(title);

        // Period
        Element period = mpd.createElement("Period");
        period.setAttribute("duration", "PT" + mediaElement.getDuration() + "S");
        period.setAttribute("start", "PT0S");
        root.appendChild(period);

        // Adaptation Set
        Element adaptationSet = mpd.createElement("AdaptationSet");
        adaptationSet.setAttribute("bitstreamSwitching", "false");
        period.appendChild(adaptationSet);

        // Representation
        Element representation = mpd.createElement("Representation");
        representation.setAttribute("id", "1");
        representation.setAttribute("codecs", codec);
        representation.setAttribute("mimeType", mimeType);
        representation.setAttribute("width", String.valueOf(resolution.width));
        representation.setAttribute("height", String.valueOf(resolution.height));
        adaptationSet.appendChild(representation);

        // Segment List
        Element segmentList = mpd.createElement("SegmentList");
        segmentList.setAttribute("timescale", "1000");
        segmentList.setAttribute("duration", Integer.toString(DASHTranscode.DEFAULT_SEGMENT_DURATION * 1000));
        representation.appendChild(segmentList);

        // Initialisation
        Element initialisation = mpd.createElement("Initialization");
        initialisation.setAttribute("sourceURL", createDASHSegmentUrl(baseUrl, job.getID(), 0));
        segmentList.appendChild(initialisation);

        // Segment URLs
        for (int i = 1; i < (mediaElement.getDuration() / DASHTranscode.DEFAULT_SEGMENT_DURATION); i++) {
            Element segmentUrl = mpd.createElement("SegmentURL");
            segmentUrl.setAttribute("media", createDASHSegmentUrl(baseUrl, job.getID(), i));
            segmentList.appendChild(segmentUrl);
        }

        // Determine the duration of the final segment.
        Integer remainder = mediaElement.getDuration() % DASHTranscode.DEFAULT_SEGMENT_DURATION;
        if (remainder > 0) {
            Element segmentUrl = mpd.createElement("SegmentURL");
            segmentUrl.setAttribute("media", createDASHSegmentUrl(baseUrl, job.getID(),
                    mediaElement.getDuration() / HLSTranscode.DEFAULT_SEGMENT_DURATION));
            segmentList.appendChild(segmentUrl);
        }

        mpd.normalizeDocument();

        return mpd;
    } catch (ParserConfigurationException ex) {
    }

    return null;
}

From source file:marytts.tools.install.ComponentDescription.java

public Document createComponentXML() throws ParserConfigurationException {
    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    fact.setNamespaceAware(true);//from  w w  w. j a  v  a  2  s.  co m
    Document doc = fact.newDocumentBuilder().newDocument();
    Element root = (Element) doc.appendChild(doc.createElementNS(installerNamespaceURI, "marytts-install"));
    Element desc = (Element) root
            .appendChild(doc.createElementNS(installerNamespaceURI, getComponentTypeString()));
    desc.setAttribute("locale", MaryUtils.locale2xmllang(locale));
    desc.setAttribute("name", name);
    desc.setAttribute("version", version);
    Element descriptionElt = (Element) desc
            .appendChild(doc.createElementNS(installerNamespaceURI, "description"));
    descriptionElt.setTextContent(description);
    Element licenseElt = (Element) desc.appendChild(doc.createElementNS(installerNamespaceURI, "license"));
    if (license != null) {
        licenseElt.setAttribute("href", license.toString());
    }
    Element packageElt = (Element) desc.appendChild(doc.createElementNS(installerNamespaceURI, "package"));
    packageElt.setAttribute("size", Integer.toString(packageSize));
    packageElt.setAttribute("md5sum", packageMD5);
    packageElt.setAttribute("filename", packageFilename);
    for (URL l : locations) {
        // Serialize the location without the filename:
        String urlString = l.toString();
        boolean isFolder = false;
        if (urlString.endsWith(packageFilename)) {
            urlString = urlString.substring(0, urlString.length() - packageFilename.length());
            isFolder = true;
        }
        Element lElt = (Element) packageElt.appendChild(doc.createElementNS(installerNamespaceURI, "location"));
        lElt.setAttribute("href", urlString);
        lElt.setAttribute("folder", String.valueOf(isFolder));
    }
    if (installedFilesNames != null) {
        Element filesElement = (Element) desc.appendChild(doc.createElementNS(installerNamespaceURI, "files"));
        filesElement.setTextContent(installedFilesNames);
    }
    return doc;
}

From source file:it.pronetics.madstore.crawler.publisher.impl.AtomPublisherImpl.java

private Element createCollectionElement(String key, String href, String title) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from www.j a v a 2s . com
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document collectionDocument = builder.newDocument();
    Element collectionelElement = collectionDocument.createElementNS(AtomConstants.APP_NS,
            AtomConstants.ATOM_COLLECTION);
    collectionelElement.setAttribute(AtomConstants.ATOM_KEY, key);
    collectionelElement.setAttribute(AtomConstants.ATOM_COLLECTION_HREF, href);
    Element acceptElement = collectionDocument.createElementNS(AtomConstants.APP_NS,
            AtomConstants.ATOM_COLLECTION_ACCEPT);
    Element titleElement = collectionDocument.createElementNS(AtomConstants.ATOM_NS,
            AtomConstants.ATOM_COLLECTION_TITLE);
    titleElement.setTextContent(title);
    collectionelElement.appendChild(acceptElement);
    collectionelElement.appendChild(titleElement);
    collectionDocument.appendChild(collectionelElement);
    return collectionelElement;
}

From source file:de.codesourcery.jasm16.ide.ProjectConfiguration.java

/**
 * Stores this project's configuration as an XML file.
 * /*from w ww  . j a  va2s  .c  o  m*/
 * @throws IOException
 */
public void save() throws IOException {

    if (!baseDir.exists()) {
        LOG.error("save(): Project base directory " + baseDir.getAbsolutePath() + " does not exist ?");
        throw new IOException("Project base directory " + baseDir.getAbsolutePath() + " does not exist ?");
    }
    Document document;
    try {
        document = createDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        LOG.error("Failed to save project configuration", e);
        throw new IOException("Failed to save project configuration", e);
    }

    final Element root = document.createElement("project");
    document.appendChild(root);

    root.appendChild(createElement("name", projectName, document));
    root.appendChild(createElement("outputFolder", outputFolder, document));
    root.appendChild(createElement("executableName", executableName, document));

    // compilation root
    if (compilationRoot != null) {
        root.appendChild(createElement("compilationRoot", compilationRoot, document));
    }

    // source filename patterns
    final Element srcFilePatterns = createElement("sourceFilenamePatterns", document);
    root.appendChild(srcFilePatterns);

    for (String pat : sourceFilenamePatterns) {
        srcFilePatterns.appendChild(createElement("sourceFilenamePattern", pat, document));
    }

    // build options
    final Element buildOptions = document.createElement("buildOptions");
    root.appendChild(buildOptions);

    this.buildOptions.saveBuildOptions(buildOptions, document);

    // debugger options
    final Element debugOptions = document.createElement("debuggerOptions");
    root.appendChild(debugOptions);

    this.debuggerOptions.saveDebuggerOptions(debugOptions, document);

    // emulation options
    final Element options = document.createElement("emulationOptions");
    this.emulationOptions.saveEmulationOptions(options, document);
    root.appendChild(options);

    final Element srcFolderNode = createElement("sourceFolders", document);
    root.appendChild(srcFolderNode);

    for (String folder : sourceFolders) {
        srcFolderNode.appendChild(createElement("sourceFolder", folder, document));
    }

    try {
        writeXML(document, resolveRelativePath(PROJECT_CONFIG_FILE));
    } catch (Exception e) {
        LOG.error("Failed to save project configuration", e);
        throw new IOException("Failed to save project configuration", e);
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

public static Element createRootElement(Document doc, String name) {

    if (name == null) {
        throw new XMLToolException("Root element name cannot be null!");
    } else if (name.trim().length() == 0) {
        throw new XMLToolException("Root element name has to contain at least one character!");
    }/*from w  w  w. ja va2  s  . com*/

    // remove old root
    NodeList nodes = doc.getChildNodes();
    Node[] element = filterNodes(nodes, Node.ELEMENT_NODE);
    for (int i = 0; i < element.length; i++) {
        doc.removeChild(element[i]);
    }

    // create and append the new root
    Element root = doc.createElement(name);
    doc.appendChild(root);

    return root;
}