Example usage for org.jdom2 Document setRootElement

List of usage examples for org.jdom2 Document setRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document setRootElement.

Prototype

public Document setRootElement(Element rootElement) 

Source Link

Document

This sets the root Element for the Document.

Usage

From source file:org.polago.deployconf.DeploymentWriter.java

License:Open Source License

/**
 * Write the given DeploymentConfig to persistent storage.
 *
 * @param deploymentConfig the DeploymentConfig to persist
 * @throws IOException indicating IO problems
 *//*from   w ww. j  a v  a2s  .c  o m*/
public void persist(DeploymentConfig deploymentConfig) throws IOException {
    Format format = Format.getPrettyFormat();
    format.setLineSeparator(LineSeparator.UNIX);
    format.setExpandEmptyElements(true);
    XMLOutputter outputter = new XMLOutputter(format);

    Element root = new Element(DOM_ROOT);
    String name = deploymentConfig.getName();
    if (name != null) {
        root.setAttribute(ATTR_NAME, name);
    }
    Document document = new Document();
    document.setRootElement(root);

    for (Task task : deploymentConfig.getTasks()) {
        Element node = new Element(task.getSerializedName());
        root.addContent(node);
        task.serialize(node, groupManager);
    }

    outputter.output(document, outputStream);
}

From source file:org.roda.core.plugins.plugins.characterization.TikaFullTextPluginUtils.java

private static String generateMetadataFile(Metadata metadata) throws IOException {
    try {/*from www.  ja v  a  2 s  .  c om*/
        String[] names = metadata.names();
        Element root = new Element("metadata");
        org.jdom2.Document doc = new org.jdom2.Document();

        for (String name : names) {
            String[] values = metadata.getValues(name);
            if (values != null && values.length > 0) {
                for (String value : values) {
                    Element child = new Element("field");
                    child.setAttribute("name", MetadataFileUtils.escapeAttribute(name));
                    child.addContent(MetadataFileUtils.escapeContent(value));
                    root.addContent(child);
                }

            }
        }
        doc.setRootElement(root);
        XMLOutputter outter = new XMLOutputter();
        outter.setFormat(Format.getPrettyFormat());
        outter.outputString(doc);
        return outter.outputString(doc);
    } catch (IllegalDataException e) {
        LOGGER.debug("Error generating Tika metadata file {}", e.getMessage());
        return "";
    }
}

From source file:org.roda_project.commons_ip.model.impl.bagit.BagitUtils.java

public static String generateMetadataFile(Path metadataPath) throws IllegalDataException {
    Map<String, String> bagInfo = getBagitInfo(metadataPath);
    Element root = new Element(IPConstants.BAGIT_METADATA);
    org.jdom2.Document doc = new org.jdom2.Document();

    for (Map.Entry<String, String> entry : bagInfo.entrySet()) {
        if (!IPConstants.BAGIT_PARENT.equalsIgnoreCase(entry.getKey())) {
            Element child = new Element(IPConstants.BAGIT_FIELD);
            child.setAttribute(IPConstants.BAGIT_NAME,
                    XmlEscapers.xmlAttributeEscaper().escape(entry.getKey()));
            child.addContent(entry.getValue());
            root.addContent(child);/* ww  w .j  ava 2 s .  c  o  m*/
        }
    }

    doc.setRootElement(root);
    XMLOutputter outter = new XMLOutputter();
    outter.setFormat(Format.getPrettyFormat());
    return outter.outputString(doc);
}

From source file:org.xflatdb.xflat.convert.converters.JavaBeansPojoConverter.java

License:Apache License

private static <U> Converter<Element, U> getDecoder(Class<U> clazz) {
    return new Converter<Element, U>() {

        final String version = System.getProperty("java.version");

        @Override/* w  w  w . j ava 2 s.  co  m*/
        public U convert(Element source) throws ConversionException {
            byte[] bytes;
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

                Document doc = new Document();
                doc.setRootElement(new Element("java").setAttribute("version", version).setAttribute("class",
                        "java.beans.XMLDecoder"));

                doc.getRootElement().addContent(source.detach());

                XMLOutputter outputter = new XMLOutputter();
                outputter.output(doc, os);

                bytes = os.toByteArray();
            } catch (IOException ex) {
                throw new ConversionException("Error reading object of class " + source.getClass(), ex);
            }

            try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {

                try (XMLDecoder decoder = new XMLDecoder(is)) {
                    return (U) decoder.readObject();
                }
            } catch (IOException ex) {
                throw new ConversionException("Error reading object of class " + source.getClass(), ex);
            }
        }
    };
}

From source file:org.xflatdb.xflat.db.TableMetadataFactory.java

License:Apache License

/**
 * Saves the given metadata to disk.//from  w w  w . j  a  v a 2 s  .  c o m
 * @param metadata The metadata to save.
 * @throws IOException 
 */
public void saveTableMetadata(TableMetadata metadata) throws IOException {
    Document doc = new Document();
    doc.setRootElement(new Element("metadata", XFlatConstants.xFlatNs));

    //save config
    if (metadata.config != null) {
        Element cfg;
        try {
            cfg = TableConfig.ToElementConverter.convert(metadata.config);
        } catch (ConversionException ex) {
            throw new XFlatException("Cannot serialize table metadata", ex);
        }
        doc.getRootElement().addContent(cfg);
    }

    //save generator
    if (metadata.idGenerator != null) {
        Element g = new Element("generator", XFlatConstants.xFlatNs);
        g.setAttribute("class", metadata.idGenerator.getClass().getName(), XFlatConstants.xFlatNs);
        metadata.idGenerator.saveState(g);

        doc.getRootElement().addContent(g);
    }

    //save engine
    Element e = metadata.engineMetadata.clone();

    doc.getRootElement().addContent(e);

    this.wrapper.writeFile(metadata.name + ".config.xml", doc);
}

From source file:org.xflatdb.xflat.engine.CachedDocumentEngine.java

License:Apache License

/**
 * Dumps the cache immediately, on this thread.
 * @param required true if a dump is absolutely required, false to allow this
 * method to choose not to dump if it feels that a dump is unnecessary.
 *///from   w  ww .j  a  v a 2s.  c  om
private void dumpCacheNow(boolean required) {
    synchronized (dumpSyncRoot) {
        if (!required && lastModified.get() < lastDump.get()) {
            //no need to dump
            return;
        }

        long lastDump = System.currentTimeMillis();

        Document doc = new Document();
        Element root = new Element("table", XFlatConstants.xFlatNs).setAttribute("name", this.getTableName(),
                XFlatConstants.xFlatNs);
        doc.setRootElement(root);

        for (Row row : this.cache.values()) {
            synchronized (row) {
                Element rowEl = null;

                int nonDeleteData = 0;

                //put ALL committed data to disk, even some that might otherwise
                //be cleaned up, because we may be in the process of committing
                //one of N engines and will need all previous values if we revert.
                for (RowData rData : row.rowData.values()) {
                    if (rData == null)
                        continue;

                    if (rData.commitId == -1)
                        //uncommitted data is not put to disk
                        continue;

                    if (rowEl == null) {
                        rowEl = new Element("row", XFlatConstants.xFlatNs);
                        setId(rowEl, row.rowId);
                    }

                    Element dataEl;
                    if (rData.data == null) {
                        //the data was deleted - make sure we mark that on the row
                        dataEl = new Element("delete", XFlatConstants.xFlatNs);
                    } else {
                        dataEl = rData.data.clone();
                        nonDeleteData++;
                    }

                    dataEl.setAttribute("tx", Long.toString(rData.transactionId, TRANSACTION_ID_RADIX),
                            XFlatConstants.xFlatNs);
                    dataEl.setAttribute("commit", Long.toString(rData.commitId, TRANSACTION_ID_RADIX),
                            XFlatConstants.xFlatNs);

                    rowEl.addContent(dataEl);
                }

                //doublecheck - only write out an element if there's actually
                //any data to write.  Delete marker elements don't count.
                if (rowEl != null && nonDeleteData > 0) {
                    root.addContent(rowEl);
                }
            }
        }

        try {
            this.file.writeFile(doc);
        } catch (FileNotFoundException ex) {
            //this is a transient issue that may be caused by another process opening the file quickly,
            //the message is generally "The requested operation cannot be performed on a file with a user-mapped section open"
            int failures = dumpFailures.incrementAndGet();
            if (failures > 3)
                throw new XFlatException("Unable to dump cache to file", ex);

            try {
                Thread.sleep(50);
            } catch (InterruptedException interruptedEx) {
            }

            //try again
            dumpCacheNow(required);
            return;
        } catch (Exception ex) {
            dumpFailures.incrementAndGet();
            throw new XFlatException("Unable to dump cache to file", ex);
        } finally {
            scheduledDump.set(null);
            this.lastDump.set(lastDump);
        }

        //success!
        dumpFailures.set(0);
    }
}

From source file:org.yawlfoundation.yawl.elements.YDecomposition.java

License:Open Source License

/**
 * This method returns the list of data from a decomposition. According to
 * its declared output parameters.  Only useful for Beta 4 and above.
 * The data inside this decomposition is groomed so to speak so that the
 * output data is returned in sequence.  Furthermore no internal variables, \
 * or input only parameters are returned.
 * @return a JDom Document of the output data.
 *//*from w  w w.  j  a  va 2 s . co m*/
public Document getOutputData() {

    //create a new output document to return
    Document outputDoc = new Document();
    Element root = _data.getRootElement();
    outputDoc.setRootElement(new Element(root.getName()));

    //now prepare a list of output params to iterate over.
    List<YParameter> outputParamsList = new ArrayList<YParameter>(getOutputParameters().values());
    Collections.sort(outputParamsList);

    for (YParameter parameter : outputParamsList) {
        Element child = root.getChild(parameter.getPreferredName());
        outputDoc.getRootElement().addContent(child.clone());
    }
    return outputDoc;
}

From source file:org.yawlfoundation.yawl.scheduling.SchedulingService.java

License:Open Source License

/**
 * adds new activities from YAWL model specification to document in right
 * order, e.g. if another worklet with new activities was started update
 * times of all activities beginning at last activity which has a time
 * TODO@tbe: returns false also, if order of activities was changed
 *
 * @param doc//from  w w  w  . jav a2s  .  c  om
 * @return true, if new activity was added
 */
public void extendRUPFromYAWLModel(Document doc, Set<String> addedActivityNames) throws Exception {
    String caseId = XMLUtils.getCaseId(doc);

    Element rupElement = new Element(XML_RUP);
    rupElement.addContent(_pgc.getActivityElements(caseId));

    boolean changed = XMLUtils.mergeElements(rupElement, doc.getRootElement());
    addedActivityNames.addAll(getDiffActivityNames(doc.getRootElement(), rupElement));
    doc.setRootElement(rupElement);

    if (changed) {
        _log.info("Extract RUP of case Id " + caseId + " from YAWL specification: "
                + Utils.document2String(doc, false));
    }
}

From source file:parcelhub.utilities.ParcelXMLFileWriter.java

License:Open Source License

/**
 * Creates the XML file which stores our parcel information.
 */// w w  w .j  av a  2 s. c  om
public void createXMLFile() {
    Element root = new Element("Parcels");
    Document xmlDatabase = new Document();

    for (int i = 0; i < parcels.size(); i++) {
        Parcel parcelObj = parcels.get(i);
        Element parcelXML = new Element("Parcel");
        parcelXML.addContent(new Element("parcelID").addContent(parcelObj.getParcelID()));
        parcelXML.addContent(new Element("name").addContent(parcelObj.getNameReciever()));
        parcelXML.addContent(new Element("address").addContent(parcelObj.getAddress()));
        parcelXML.addContent(new Element("date").addContent(parcelObj.getDate()));
        parcelXML.addContent(new Element("city").addContent(parcelObj.getCity()));
        parcelXML.addContent(new Element("state").addContent(parcelObj.getState()));
        parcelXML.addContent(new Element("zip").addContent(parcelObj.getZip()));
        root.addContent(parcelXML);
    }

    xmlDatabase.setRootElement(root);
    XMLOutputter outter = new XMLOutputter();
    outter.setFormat(Format.getPrettyFormat());
    try {
        outter.output(xmlDatabase, new FileWriter(new File(fileName)));
    } catch (IOException ex) {
        Logger.getLogger(ParcelXMLFileWriter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:princetonPlainsboro.EcritureXML.java

private Document createJDOM(DossierMedical dossier) {
    Document jdomDoc = new Document();

    // racine/*  www .  j  av  a 2 s. c  o  m*/
    Element rootElement = new Element("dossiers");
    jdomDoc.setRootElement(rootElement);

    //ajoute les fiches de soin
    for (FicheDeSoins fiche : dossier.getFiches()) {

        Element DOMfiche = new Element("ficheDeSoins");

        //Date:
        DOMfiche.addContent(convertDate(fiche.getDate()));

        //Medecin
        DOMfiche.addContent(convertMedecin(fiche.getMedecin()));

        //Patient
        DOMfiche.addContent(convertPatient(fiche.getPatient()));

        //Actes
        for (Acte acte : fiche.getActes()) {
            DOMfiche.addContent(convertActe(acte));
        }

        // ajoute la nouvelle fiche de soin au document
        rootElement.addContent(DOMfiche);

    }

    return jdomDoc;
}