Example usage for org.jdom2.output Format getPrettyFormat

List of usage examples for org.jdom2.output Format getPrettyFormat

Introduction

In this page you can find the example usage for org.jdom2.output Format getPrettyFormat.

Prototype

public static Format getPrettyFormat() 

Source Link

Document

Returns a new Format object that performs whitespace beautification with 2-space indents, uses the UTF-8 encoding, doesn't expand empty elements, includes the declaration and encoding, and uses the default entity escape strategy.

Usage

From source file:core.ListComponenXml.java

@Override
public void updateFile() {
    try {//  www.  j ava2  s. co  m
        Element root = new Element("listado");
        Document document = new Document();
        for (Xml xml : this.getXmls()) {
            Element autor = new Element("autor");
            autor.addContent(new Element("nombre").setText(xml.getAutor().getNombre()));
            autor.addContent(new Element("descripcion").setText(xml.getAutor().getDescripcion()));
            autor.addContent(new Element("version").setText(xml.getAutor().getVersion()));
            Element cuerpo = new Element("cuerpo");
            Element tipo = new Element("tipo");
            Element status = new Element("status");
            tipo.setAttribute("columnas", "" + xml.getCuerpo().getColumnas());
            tipo.setAttribute("tipodatocolumna", String.join(",", xml.getCuerpo().getTipo_datos()));
            cuerpo.addContent(tipo);
            tipo.addContent(new Element("claseprincipal").setText(xml.getCuerpo().getMain()));
            status.setAttribute("active", String.valueOf(xml.getStatus().getActive()));
            Element parametro = new Element("parametro");
            for (String dato : xml.getCuerpo().getParametros()) {
                parametro.addContent(new Element(dato));
            }
            cuerpo.addContent(parametro);
            Element pluguin = new Element("pluguin");
            pluguin.addContent(autor);
            pluguin.addContent(cuerpo);
            pluguin.addContent(status);
            root.addContent(pluguin);
        }
        ;
        document.setRootElement(root);
        XMLOutputter outter = new XMLOutputter();
        outter.setFormat(Format.getPrettyFormat());
        String basePath = new File("").getAbsolutePath();
        String ruta = basePath + "/src/configuracion/xml_configuracion.xml";
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            ruta = basePath + "\\src\\configuracion\\xml_configuracion.xml";
        }
        outter.output(document, new FileWriter(new File(ruta)));
    } catch (IOException ex) {
        Logger.getLogger(ListComponenXml.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:core.utileria.java

/**
 * @param args the command line arguments
 *///from w w  w.j ava 2  s  .c o m
public static void main(String[] args) throws IOException {
    // TODO code application logic here
    //        File archivo = new File("/home/dark/Escritorio/aaaaaaaaaaa/a3");
    //        if (!archivo.exists())
    //            archivo.mkdir();
    ListComponenXml l = new ListComponenXml();
    String basePath = new File("").getAbsolutePath();
    System.out.println(basePath);
    System.out.println(System.getProperty("os.name").toLowerCase());
    String ruta = basePath + "/src/configuracion/xml_configuracion.xml";
    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        ruta = basePath + "\\src\\configuracion\\xml_configuracion.xml";
    }
    l.loadingFile(ruta);
    l.readNodeFile();
    //        for(Xml x : l.getXmls()){
    //            System.out.println(x.toString());
    //        }

    Element root = new Element("CONFIGURATION");
    Document doc = new Document();

    Element child1 = new Element("BROWSER");
    child1.addContent("chrome");
    Element child2 = new Element("BASE");
    child1.addContent("http:fut");
    Element child3 = new Element("EMPLOYEE");
    child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));

    root.addContent(child1);
    doc.setRootElement(root);

    XMLOutputter outter = new XMLOutputter();
    outter.setFormat(Format.getPrettyFormat());
    outter.output(doc, new FileWriter(new File(basePath + "\\src\\configuracion\\xml_configuracion2.xml")));
}

From source file:core.WriteComponenXml.java

@Override
public void writeFile(String ruta, Xml xml) {
    FileWriter writer = null;/*ww  w.  j a v a2 s .  co m*/
    try {
        ValidXml vxml = new ValidXml();
        System.out.println(vxml.exisFile(ruta));
        System.out.println(vxml.validExtencion(ruta));
        if (vxml.exisFile(ruta) && vxml.validExtencion(ruta)) {
            loadingFile(ruta);
            try {
                FileInputStream fis = new FileInputStream(this.getFile());
                setDocument(this.getBuilder().build(fis));
                this.setRootNode(getDocument().detachRootElement());
            } catch (FileNotFoundException ex) {
                Logger.getLogger(WriteComponenXml.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JDOMException ex) {
                Logger.getLogger(WriteComponenXml.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(WriteComponenXml.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            String basePath = new File("").getAbsolutePath();
            ruta = basePath + "/src/configuracion/xml_configuracion.xml";
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                ruta = basePath + "\\src\\configuracion\\xml_configuracion.xml";
            }
            Element root = new Element("listado");
            Document doc = new Document();
            doc.setRootElement(root);
            XMLOutputter outter = new XMLOutputter();
            outter.setFormat(Format.getPrettyFormat());
            this.setFile(new File(ruta));
            outter.output(doc, new FileWriter(this.getFile()));
            FileInputStream fis = new FileInputStream(this.getFile());
            setDocument(this.getBuilder().build(this.getFile()));
            this.setRootNode(getDocument().detachRootElement());
            this.setDocument(new Document());
            this.setRootNode(new Element("listado"));
        }
        Element autor = new Element("autor");
        System.out.println("  " + this.getDocument() + "   " + this.getRootNode());
        autor.addContent(new Element("nombre").setText(xml.getAutor().getNombre()));
        autor.addContent(new Element("descripcion").setText(xml.getAutor().getDescripcion()));
        autor.addContent(new Element("version").setText(xml.getAutor().getVersion()));
        Element cuerpo = new Element("cuerpo");
        Element tipo = new Element("tipo");
        Element status = new Element("status");
        tipo.setAttribute("columnas", "" + xml.getCuerpo().getColumnas());
        tipo.setAttribute("tipodatocolumna", String.join(",", xml.getCuerpo().getTipo_datos()));
        cuerpo.addContent(tipo);
        tipo.addContent(new Element("claseprincipal").setText(xml.getCuerpo().getMain()));
        status.setAttribute("active", String.valueOf(xml.getStatus().getActive()));
        Element parametro = new Element("parametro");
        for (String dato : xml.getCuerpo().getParametros()) {
            parametro.addContent(new Element(dato));
        }
        cuerpo.addContent(parametro);
        Element pluguin = new Element("pluguin");
        pluguin.addContent(autor);
        pluguin.addContent(cuerpo);
        pluguin.addContent(status);
        this.getRootNode().addContent(pluguin);
        this.getDocument().setContent(this.getRootNode());
        writer = new FileWriter(ruta);
        XMLOutputter outputter = new XMLOutputter();
        outputter.setFormat(Format.getPrettyFormat());
        outputter.output(this.getDocument(), writer);
        outputter.output(this.getDocument(), System.out);
        writer.close(); // close writer
    } catch (IOException ex) {
        Logger.getLogger(WriteComponenXml.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JDOMException ex) {
        Logger.getLogger(WriteComponenXml.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

    }
}

From source file:cz.cesnet.shongo.connector.device.AdobeConnectConnector.java

@Override
public String exportRoomSettings(String roomId) throws CommandException {
    Element scoInfo = getScoInfo(roomId);
    Document document = scoInfo.getDocument();
    XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
    return xmlOutput.outputString(document);
}

From source file:cz.cesnet.shongo.connector.device.AdobeConnectConnector.java

@Override
public void importRoomSettings(String roomId, String settings) throws CommandException {
    SAXBuilder saxBuilder = new SAXBuilder();
    Document document;//from w w  w  . j  av  a  2 s .  c  o  m
    try {
        document = saxBuilder.build(new StringReader(settings));
    } catch (Exception exception) {
        throw new CommandException(exception.getMessage(), exception);
    }

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    String xmlString = outputter.outputString(document);

    RequestAttributeList attributes = new RequestAttributeList();

    attributes.add("sco-id", roomId);
    //        attributes.add("date-begin", document.getRootElement().getChild("sco").getChild("date-begin").getText());
    //        attributes.add("date-end", document.getRootElement().getChild("sco").getChild("date-end").getText());
    if (document.getRootElement().getChild("sco").getChild("description") != null) {
        attributes.add("description",
                document.getRootElement().getChild("sco").getChild("description").getText());
    }
    attributes.add("url-path", document.getRootElement().getChild("sco").getChild("url-path").getText());
    attributes.add("name", document.getRootElement().getChild("sco").getChild("name").getText());

    execApi("sco-update", attributes);
}

From source file:cz.lbenda.dbapp.rc.SessionConfiguration.java

License:Apache License

public static String storeToString() {
    Document doc = new Document(storeAllToElement());
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    StringWriter sw = new StringWriter();
    try {//w w w. j  av a  2 s. c o  m
        xmlOutput.output(doc, sw);
        return sw.toString();
    } catch (IOException e) {
        LOG.error("There was problem with write XML output to StringWriter", e);
        throw new RuntimeException("There was problem with write XML output to StringWriter", e);
    }
}

From source file:cz.pecina.retro.memory.Snapshot.java

License:Open Source License

/**
 * Writes a hardware shapshot to a file.
 *
 * @param file output file//www.  j av a 2 s. co m
 */
public void write(final File file) {
    log.fine("Writing snapshot to a file, file: " + file.getName());
    final Element snapshot = new Element("snapshot");
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    snapshot.addNamespaceDeclaration(namespace);
    snapshot.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "snapshot-" + SNAPSHOT_XML_FILE_VERSION + ".xsd", namespace);
    snapshot.setAttribute("version", SNAPSHOT_XML_FILE_VERSION);
    hardware.marshal(snapshot);
    final Document doc = new Document(snapshot);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

From source file:cz.pecina.retro.memory.XML.java

License:Open Source License

/**
 * Writes a memory range to a file, with wrap-around.
 *
 * @param file               output file
 * @param startAddress       starting address
 * @param number             number of bytes
 * @param destinationAddress destination address
 *///  w  w  w .  j  a  va 2 s.c  om
public void write(final File file, final int startAddress, final int number, final int destinationAddress) {
    log.fine(
            String.format("Writing XML data to a file, file: %s, start address: %04x," + " number of bytes: %d",
                    file.getName(), startAddress, number));
    final Element tag = new Element("memory");
    Snapshot.buildBlockElement(sourceMemory, tag, startAddress, number);
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    tag.addNamespaceDeclaration(namespace);
    tag.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "memory-" + MEMORY_XML_FILE_VERSION + ".xsd", namespace);
    tag.setAttribute("version", MEMORY_XML_FILE_VERSION);
    tag.setAttribute("start", String.format("%04X", destinationAddress));
    final Document doc = new Document(tag);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

From source file:cz.pecina.retro.trec.XML.java

License:Open Source License

/**
 * Writes the tape to an XML file.//w w  w  . j  ava2s  . co m
 *
 * @param file output file
 */
public void write(final File file) {
    log.fine("Writing tape data to an XML file, file: " + file);
    final Element tag = new Element("tape");
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    tag.addNamespaceDeclaration(namespace);
    tag.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "tape-" + TAPE_XML_FILE_VERSION + ".xsd", namespace);
    tag.setAttribute("version", TAPE_XML_FILE_VERSION);
    tag.setAttribute("rate", String.valueOf(tapeRecorderInterface.tapeSampleRate));
    tag.setAttribute("unit", "per sec");
    try {
        long currPos = -1;
        for (long start : tape.navigableKeySet()) {
            final long duration = tape.get(start);
            log.finest(String.format("Fetched: (%d, %d)", start, duration));
            if ((start > currPos) && (duration > 0)) {
                final Element pulse = new Element("pulse");
                pulse.setAttribute("start", String.valueOf(start));
                pulse.setAttribute("duration", String.valueOf(duration));
                tag.addContent(pulse);
                log.finest(String.format("Write: (%d, %d)", start, duration));
                currPos = start + duration;
            }
        }
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    final Document doc = new Document(tag);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

From source file:de.danielluedecke.zettelkasten.tasks.export.ExportToXmlTask.java

License:Open Source License

@Override
protected Object doInBackground() {
    // Your Task's code here.  This method runs
    // on a background thread, so don't reference
    // the Swing GUI from here.
    // prevent task from processing when the file path is incorrect

    // if no file exists, exit task
    if (null == filepath) {
        showOkMessage = false;//from   w  w  w .j  a v a  2  s.  c  o  m
        return null;
    }
    // check whether file already exists
    if (filepath.exists()) {
        // file exists, ask user to overwrite it...
        int optionDocExists = JOptionPane.showConfirmDialog(null,
                resourceMap.getString("askForOverwriteFileMsg", "", filepath.getName()),
                resourceMap.getString("askForOverwriteFileTitle"), JOptionPane.YES_NO_OPTION,
                JOptionPane.PLAIN_MESSAGE);
        // if the user does *not* choose to overwrite, quit...
        if (optionDocExists != JOptionPane.YES_OPTION) {
            // don't show "export was OK" message in main frame
            showOkMessage = false;
            return null;
        }
    }
    int contentsize;
    int counter;
    // first of all, create a new, empty xml-document
    Document exportDoc = new Document(new Element("zettelkasten"));
    // yet everything is ok...
    exportOk = true;
    // create a list of all elements from the main xml file
    try {
        // get the size of the export data, used for progressbar
        contentsize = exportentries.size();
        // go through all elements of the data file
        for (counter = 0; counter < exportentries.size(); counter++) {
            // add the headline to our final export document
            exportDoc.getRootElement().addContent(exportEntries(counter));
            // update progress bar
            setProgress(counter, 0, contentsize);
        }
    } catch (IllegalStateException e) {
        // log error-message
        Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
        // show warning message box
        JOptionPane.showMessageDialog(null, resourceMap.getString("errorExportMsg"),
                resourceMap.getString("errorExportTitle"), JOptionPane.PLAIN_MESSAGE);
        // and change indicator
        exportOk = false;
    }
    //
    // now that we've created our xml-document, we can
    // export it to a file
    //
    try {
        // show status text
        msgLabel.setText(resourceMap.getString("msg2"));
        // open the outputstream
        FileOutputStream fos = new FileOutputStream(filepath);
        // create a new XML-outputter with the pretty output format,
        // so the xml-file looks nicer
        XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
        try {
            // save the main-export-file
            out.output(exportDoc, fos);
            // close the output stream
            fos.close();
        } catch (IOException e) {
            // log error-message
            Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
            // and change indicator
            exportOk = false;
        }
        // if the user chose to export the keywords and authors as separate
        // file, do so
        if (!allinone) {
            //
            // first we export the keyword file
            //
            // prepare the filepath
            StringBuilder fp = new StringBuilder(filepath.toString());
            // get position of file extension
            int ext = fp.lastIndexOf(".");
            // insert an appendix befor the file extenstion
            fp.insert(ext, "_keywords");
            // create a new file
            File file_keywords = new File(fp.toString());
            // open the outputstream
            fos = new FileOutputStream(file_keywords);
            // create a new XML-outputter with the pretty output format,
            // so the xml-file looks nicer
            out = new XMLOutputter(Format.getPrettyFormat());
            try {
                // save the main-export-file
                out.output(dataObj.getKeywordData(), fos);
                // close the output stream
                fos.close();
            } catch (IOException e) {
                // log error-message
                Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
                // and change indicator
                exportOk = false;
            }
            //
            // now we export the author file
            //
            // prepare the filepath
            fp = new StringBuilder(filepath.toString());
            // get position of file extension
            ext = fp.lastIndexOf(".");
            // insert an appendix befor the file extenstion
            fp.insert(ext, "_authors");
            // create a new file
            File file_authors = new File(fp.toString());
            // open the outputstream
            fos = new FileOutputStream(file_authors);
            // create a new XML-outputter with the pretty output format,
            // so the xml-file looks nicer
            out = new XMLOutputter(Format.getPrettyFormat());
            try {
                // save the main-export-file
                out.output(dataObj.getAuthorData(), fos);
                // close the output stream
                fos.close();
            } catch (IOException e) {
                // log error-message
                Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
                // and change indicator
                exportOk = false;
            }
        }
    } catch (FileNotFoundException e) {
        // log error-message
        Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
        // show warning message
        JOptionPane.showMessageDialog(null, resourceMap.getString("errorExportMsg"),
                resourceMap.getString("errorExportTitle"), JOptionPane.PLAIN_MESSAGE);
        // and change indicator
        exportOk = false;
    } catch (SecurityException e) {
        // log error-message
        Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
        // show warning message
        JOptionPane.showMessageDialog(null, resourceMap.getString("errorNoAccessMsg"),
                resourceMap.getString("errorNoAccessTitle"), JOptionPane.PLAIN_MESSAGE);
        // and change indicator
        exportOk = false;
    }
    // if the user requested a bibtex-export, do this now
    if (exportbibtex) {
        // show status text
        msgLabel.setText(resourceMap.getString("msgBibtextExport"));
        // write bibtex file
        ExportTools.writeBibTexFile(dataObj, bibtexObj, exportentries, filepath, resourceMap);
    }
    return null; // return your result
}