Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

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

Prototype

public Document(List<? extends Content> content) 

Source Link

Document

This will create a new Document, with the supplied list of content, and a DocType declaration only if the content contains a DocType instance.

Usage

From source file:org.blip.workflowengine.configuration.XmlConfigWrite.java

License:Apache License

default void write(final Microservice microservice, final File file) throws IOException {
    Objects.requireNonNull(microservice, "microservice argument is null");
    Objects.requireNonNull(file, "file argument is null");

    if (!file.isFile()) {
        throw new IllegalArgumentException("Not a file");
    } else if (!file.canWrite()) {
        throw new IllegalArgumentException("Can't write to file");
    }/*from   w  ww.  j a v  a 2s .  c  om*/

    final XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    final Document document = new Document(microserviceToXml().apply(microservice));
    out.output(document, new FileOutputStream(file));
}

From source file:org.crazyt.xgogdownloader.Util.java

License:Open Source License

public final int createXML(String filepath, int chunk_size, String xml_dir) {
    int res = 0;//from  ww  w  .jav  a 2s. c om
    File infile;
    int filesize;
    int size;
    int chunks;
    int i;
    if (xml_dir == "") {
        xml_dir = ".cache/xgogdownloader/xml";
    } // end of if
    File path = Factory.newFile(xml_dir);
    if (!path.exists()) {
        if (!path.mkdirs()) {
            System.out.println("Failed to create directory: " + path);
        }
    }

    infile = Factory.newFile(filepath);
    // RandomAccessFile file = new RandomAccessFile("file.txt", "rw");?
    // fseek/seek ftell/getFilePointer rewind/seek(0)
    if (infile.exists()) {
        filesize = (int) infile.length();
    } else {
        System.out.println(filepath + " doesn't exist");
        return res;
    } // end of if-else

    // Get filename
    String filename = FilenameUtils.removeExtension(infile.getName());
    String filenameXML = xml_dir + "/" + filename + ".xml";

    System.out.println(filename);
    // Determine number of chunks
    int remaining = filesize % chunk_size;
    chunks = (remaining == 0) ? filesize / chunk_size : (filesize / chunk_size) + 1;
    System.out.println("Filesize: " + filesize + " bytes");
    System.out.println("Chunks: " + chunks);
    System.out.println("Chunk size: " + (chunk_size / Math.pow(2.0, 20.0)) + " MB");
    Util util_md5 = new Util();
    String file_md5 = util_md5.getFileHash(filepath);
    System.out.println("MD5: " + file_md5);

    Element fileElem = new Element("file");
    fileElem.setAttribute(new Attribute("name", filename));
    fileElem.setAttribute(new Attribute("md5", file_md5));
    fileElem.setAttribute(new Attribute("chunks", String.valueOf(chunks)));
    fileElem.setAttribute(new Attribute("total_size", String.valueOf(filesize)));

    System.out.println("Getting MD5 for chunks");
    for (i = 0; i < chunks; i++) {
        int range_begin = i * chunk_size;
        // fseek(infile, range_begin, SEEK_SET);
        if ((i == chunks - 1) && (remaining != 0)) {
            chunk_size = remaining;
        }
        int range_end = range_begin + chunk_size - 1;
        String chunk = String.valueOf(chunk_size * 4);

        String hash = util_md5.getChunkHash(chunk); // calculates hash of
        // chunk string?
        Element chunkElem = new Element("chunk");
        chunkElem.setAttribute(new Attribute("id", String.valueOf(i)));
        chunkElem.setAttribute(new Attribute("from", String.valueOf(range_begin)));
        chunkElem.setAttribute(new Attribute("to", String.valueOf(range_begin)));
        chunkElem.setAttribute(new Attribute("method", "md5"));
        chunkElem.addContent(new Text(hash));
        fileElem.addContent(chunkElem);

        System.out.println("Chunks hashed " + (i + 1) + " / " + chunks + "\r");
    }
    Document doc = new Document(fileElem);

    System.out.println("Writing XML: " + filenameXML);
    try {
        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, Factory.newFileWriter(filenameXML));
        res = 1;
    } catch (IOException e) {
        System.out.println("Can't create " + filenameXML);
        return res;
    }
    return res;
}

From source file:org.culturegraph.mf.jdom.StreamToJDomDocument.java

License:Apache License

@Override
public void startRecord(final String identifier) {
    assert !isClosed();
    currentElement = createElement(rootTagName);
    for (Namespace namespace : namespaces.values()) {
        currentElement.addNamespaceDeclaration(namespace);
    }//from   w w w  .  j  av  a  2 s . c  om
    document = new Document(currentElement);
}

From source file:org.esa.nest.dat.toolviews.Projects.ProductSet.java

License:Open Source License

public void Save() {

    final Element root = new Element("ProjectSet");
    final Document doc = new Document(root);

    for (File file : fileList) {
        final Element fileElem = new Element("product");
        fileElem.setAttribute("path", file.getAbsolutePath());
        root.addContent(fileElem);/*from w w  w. j  av  a 2s.  c  o m*/
    }

    XMLSupport.SaveXML(doc, productSetFile.getAbsolutePath());
}

From source file:org.esa.nest.dat.toolviews.Projects.Project.java

License:Open Source License

public void SaveProject() {
    if (projectSubFolders == null)
        return;/*from   www  .  j  a v a  2 s  .c  om*/

    final Element root = new Element("Project");
    root.setAttribute("name", getProjectName());
    final Document doc = new Document(root);

    final Vector subFolders = projectSubFolders.getSubFolders();
    for (Enumeration e = subFolders.elements(); e.hasMoreElements();) {
        final ProjectSubFolder folder = (ProjectSubFolder) e.nextElement();
        final Element elem = folder.toXML();
        root.addContent(elem);
    }

    XMLSupport.SaveXML(doc, projectFile.getAbsolutePath());
}

From source file:org.esa.nest.gpf.oceantools.ObjectDiscriminationOp.java

License:Open Source License

/**
 * Output cluster information to file.//from   ww  w  .j ava  2 s  . c  om
 *
 * @throws OperatorException when can't save metadata
 */
private void writeBandClusterListsToFile() throws OperatorException {

    final Element root = new Element("Detection");
    final Document doc = new Document(root);

    for (String bandName : bandClusterLists.keySet()) {
        final Element elem = new Element("targetsDetected");
        elem.setAttribute("bandName", bandName);
        final List<ShipRecord> clusterList = bandClusterLists.get(bandName);
        for (ShipRecord rec : clusterList) {
            final Element subElem = new Element("target");
            subElem.setAttribute("lat", String.valueOf(rec.lat));
            subElem.setAttribute("lon", String.valueOf(rec.lon));
            subElem.setAttribute("width", String.valueOf(rec.width));
            subElem.setAttribute("length", String.valueOf(rec.length));
            subElem.setAttribute("intensity", String.valueOf(rec.intensity));
            elem.addContent(subElem);
        }
        root.addContent(elem);
    }
    XMLSupport.SaveXML(doc, targetReportFile.getAbsolutePath());
}

From source file:org.esa.nest.gpf.oceantools.WindFieldEstimationOp.java

License:Open Source License

/**
 * Output wind fielld information to file.
 *
 * @throws OperatorException when can't save metadata
 *//*from   www. j av a2s.com*/
private void outputWindFieldInfoToFile() throws OperatorException {
    /*
    double dxMean = 0.0;
    double dyMean = 0.0;
    int counter = 0;
    for (String bandName : bandWindFieldRecord.keySet())  {
    final java.util.List<WindFieldRecord> recordList = bandWindFieldRecord.get(bandName);
    for (WindFieldRecord rec : recordList) {
        dxMean += rec.dx;
        dyMean += rec.dy;
        counter++;
    }
    }
    dxMean /= counter;
    dyMean /= counter;
    */
    final Element root = new Element("Detection");
    final Document doc = new Document(root);

    for (String bandName : bandWindFieldRecord.keySet()) {
        final Element elem = new Element("windFieldEstimated");
        elem.setAttribute("bandName", bandName);
        final java.util.List<WindFieldRecord> recordList = bandWindFieldRecord.get(bandName);
        for (WindFieldRecord rec : recordList) {
            /*
            if (rec.dx*dxMean + rec.dy*dyMean <= 0.707) {
            continue;
            }
            */
            final Element subElem = new Element("windFieldInfo");
            subElem.setAttribute("lat", String.valueOf(rec.lat));
            subElem.setAttribute("lon", String.valueOf(rec.lon));
            subElem.setAttribute("speed", String.valueOf(rec.speed));
            subElem.setAttribute("dx", String.valueOf(rec.dx));
            subElem.setAttribute("dy", String.valueOf(rec.dy));
            subElem.setAttribute("ratio", String.valueOf(rec.ratio));
            elem.addContent(subElem);
        }
        root.addContent(elem);
    }
    XMLSupport.SaveXML(doc, windFieldReportFile.getAbsolutePath());
}

From source file:org.esa.s2tbx.dataio.s2.gml.GmlFilter.java

License:Open Source License

public Pair<String, List<EopPolygon>> parse(InputStream stream) {
    SAXBuilder builder = new SAXBuilder();
    Document jdomDoc = null;// w  w  w.j a va 2 s.  c o m

    try {
        jdomDoc = builder.build(stream);

        //get the root element
        Element web_app = jdomDoc.getRootElement();
        String maskEpsg = "";

        Namespace gml = Namespace.getNamespace("http://www.opengis.net/gml/3.2");
        Namespace eop = Namespace.getNamespace("http://www.opengis.net/eop/2.0");

        List<Element> targeted = web_app.getChildren("boundedBy", gml);
        if (!targeted.isEmpty()) {
            Element aEnvelope = targeted.get(0).getChild("Envelope", gml);
            if (aEnvelope != null) {
                maskEpsg = aEnvelope.getAttribute("srsName").getValue();
            }
        }

        List<EopPolygon> recoveredGeometries = new ArrayList<>();

        IteratorIterable<Content> contents = web_app.getDescendants();
        while (contents.hasNext()) {
            Content web_app_content = contents.next();
            if (!web_app_content.getCType().equals(CType.Text)
                    && !web_app_content.getCType().equals(CType.Comment)) {
                boolean withGml = (web_app_content.getNamespacesInScope().get(0).getPrefix().contains("gml"));
                if (withGml) {
                    boolean parentNotGml = !(web_app_content.getParentElement().getNamespace().getPrefix()
                            .contains("gml"));
                    if (parentNotGml) {
                        Element capturedElement = (Element) web_app_content;
                        Attribute attr = null;
                        String polygonId = "";
                        String typeId = "";
                        if (capturedElement.getName().contains("Polygon")) {
                            attr = capturedElement.getAttribute("id", gml);
                            if (attr != null) {
                                polygonId = attr.getValue();
                                if (polygonId.indexOf('.') != -1) {
                                    typeId = polygonId.substring(0, polygonId.indexOf('.'));
                                }
                            }
                        }

                        Document newDoc = new Document(capturedElement.clone().detach());

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        xmlOutput.output(newDoc, baos);
                        String replacedContent = baos.toString().replace("/www.opengis.net/gml/3.2",
                                "/www.opengis.net/gml");

                        InputStream ois = new ByteArrayInputStream(replacedContent.getBytes());

                        List<Polygon> pols = streamParseGML3(ois);
                        for (Polygon pol : pols) {
                            recoveredGeometries.add(new EopPolygon(polygonId, typeId, pol));
                        }
                    }
                }

            }
        }

        return new Pair<String, List<EopPolygon>>(maskEpsg, recoveredGeometries);
    } catch (JDOMException e) {
        // {@report "parse xml problem !"}
    } catch (IOException e) {
        // {@report "IO problem !"}
    }

    return new Pair<String, List<EopPolygon>>("", new ArrayList<>());
}

From source file:org.esa.snap.core.dataop.downloadable.FtpDownloader.java

License:Open Source License

private static void writeRemoteFileList(final FTPFile[] remoteFileList, final String server,
        final String remotePath, final File file) {

    final Element root = new Element("remoteFileListing");
    root.setAttribute("server", server);

    final Document doc = new Document(root);
    final Element remotePathElem = new Element("remotePath");
    remotePathElem.setAttribute("path", remotePath);
    root.addContent(remotePathElem);//w ww  .  jav  a2s. c  o m

    for (FTPFile ftpFile : remoteFileList) {
        // add prefix just in case file name starts with a digit
        final Element fileElem = new Element(elemPrefix + ftpFile.getName());
        fileElem.setAttribute("size", String.valueOf(ftpFile.getSize()));
        remotePathElem.addContent(fileElem);
    }
    try {
        XMLSupport.SaveXML(doc, file.getAbsolutePath());
    } catch (IOException e) {
        SystemUtils.LOG.warning("Unable to save " + file.getAbsolutePath());
    }
}

From source file:org.esa.snap.datamodel.metadata.AbstractMetadataIO.java

License:Open Source License

public static void Save(final Product product, final MetadataElement metadataElem, final File metadataFile) {

    final Element root = new Element("Metadata");
    final Document doc = new Document(root);

    if (metadataElem != null) {
        final Element AbstractedMetadataElem = new Element(AbstractMetadata.ABSTRACT_METADATA_ROOT);
        root.addContent(AbstractedMetadataElem);
        XMLSupport.metadataElementToDOMElement(metadataElem, AbstractedMetadataElem);
    }//from w w  w  .  ja v  a2 s  .com
    if (product.getTiePointGrids().length > 0) {
        final Element tiePointGridsElem = new Element(TPG);
        root.addContent(tiePointGridsElem);
        writeTiePointGrids(product, tiePointGridsElem);
    }

    XMLSupport.SaveXML(doc, metadataFile.getAbsoluteFile().toString());
}