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:Domain.DataAccess.DatabaseHandler.java

public boolean insertBookLoan(String pBookId, String pStudentId) {

    boolean result = false;

    try {/*  w ww .j  a va 2 s.c  o m*/

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.parse("./src/Loans.xml");
        Element root = document.getDocumentElement();

        Element newServer = document.createElement("loan");
        root.appendChild(newServer);

        Element name = document.createElement("studentId");
        name.appendChild(document.createTextNode(pStudentId));
        newServer.appendChild(name);

        Element port = document.createElement("bookId");
        port.appendChild(document.createTextNode(pBookId));
        newServer.appendChild(port);

        root.appendChild(newServer);

        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        StreamResult res = new StreamResult("./src/Loans.xml");
        transformer.transform(source, res);

        SAXBuilder builder = new SAXBuilder();
        org.jdom2.Document readDoc = null;
        readDoc = builder.build(new File("./src/Loans.xml"));

        XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());

        xmlOutput.output(readDoc, new FileOutputStream(new File("./src/Loans.xml")));

        disableBook(pBookId);

        result = true;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:Domain.DataAccess.DatabaseHandler.java

public boolean removeBookLoan(String pBookId) {

    boolean result = false;

    org.jdom2.Element loan;/*from  w  w w . j  ava  2s .c  o m*/

    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document readDoc = null;
    try {
        readDoc = builder.build(new File("./src/Loans.xml"));
        org.jdom2.Element root = readDoc.getRootElement();
        List children = root.getChildren();

        for (int i = 0; i < children.size(); i++) {
            loan = (org.jdom2.Element) children.get(i);

            if (loan.getChildText("bookId").equals(pBookId)) {

                System.out.println("bookId: " + loan.getChildText("bookId") + "--- param: " + pBookId);
                children.remove(i);
                break;
            }
        }

        XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
        xmlOutput.output(readDoc, new FileOutputStream(new File("./src/Loans.xml")));

        enableBook(pBookId);

        result = true;

    } catch (JDOMException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return result;
}

From source file:edu.kit.trufflehog.model.configdata.SettingsDataModel.java

License:Open Source License

/**
 * <p>/*w  w  w. j ava  2  s  .c  om*/
 *     Actually make the change to the XML and save it to the hard drive.
 * </p>
 *
 * @param typeClass The type of the value (i.e. String, Integer or Boolean are examples)
 * @param key The key mapped to the value, classic key value mapping.
 * @param oldValue The old value that should be updated.
 * @param newValue The new value, that should overwrite the old value.
 * @param document The document object that represent the parsed XML.
 * @param entry The entry that should be updated in the XML file.
 * @throws IOException Thrown if something goes wrong during the write operation.
 */
private void saveNewValue(final Class typeClass, final String key, final String oldValue, final String newValue,
        final Document document, final Element entry) throws IOException {
    // Get the only one we found
    entry.getChild("value").setText(newValue);

    // Save the new XML to the file
    XMLOutputter xmlOutput = new XMLOutputter();
    PrintWriter writer = new PrintWriter(settingsFile, "UTF-8");
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(document, writer);
    writer.close();

    logger.debug("Changed key: " + key + " of type: " + typeClass.getName() + " from old value: " + oldValue
            + " to new value: " + newValue);
}

From source file:edu.unc.lib.deposit.normalize.Proquest2N3BagJob.java

License:Apache License

/**
 * Transform the given root element from the data document into MODS and stores it as the metadata for the object
 * being ingested// w ww.  ja v a 2 s .c  om
 *
 * @param primaryPID
 * @param dataRoot
 * @param modified
 * @throws TransformerException
 * @throws FileNotFoundException
 * @throws IOException
 */
private Document extractMods(PID primaryPID, Element dataRoot, DateTime modified)
        throws TransformerException, FileNotFoundException, IOException {

    int month = modified.getMonthOfYear();
    String gradSemester;

    if (month >= 2 && month <= 6) {
        gradSemester = "Spring";
    } else if (month >= 7 && month <= 9) {
        gradSemester = "Summer";
    } else {
        gradSemester = "Winter";
    }

    JDOMResult mods = new JDOMResult();
    // Transform the metadata into MODS
    synchronized (proquest2ModsTransformer) {
        proquest2ModsTransformer.setParameter("graduationSemester", gradSemester + " " + modified.getYear());
        proquest2ModsTransformer.transform(new JDOMSource(dataRoot), mods);
    }

    // Create the description folder and write the MODS out to it
    final File modsFolder = getDescriptionDir();
    modsFolder.mkdir();

    File modsFile = new File(modsFolder, primaryPID.getUUID() + ".xml");

    try (FileOutputStream fos = new FileOutputStream(modsFile)) {
        new XMLOutputter(Format.getPrettyFormat()).output(mods.getDocument(), fos);
    }

    return mods.getDocument();
}

From source file:edu.unc.lib.deposit.normalize.VocabularyEnforcementJob.java

License:Apache License

@Override
public void runJob() {
    Model model = getWritableModel();//  w ww . j a  v a  2s.  com

    // Get the list of all objects being ingested in this job
    List<String> resourcePIDs = new ArrayList<>();
    Bag deposit = model.getBag(getDepositPID().getURI());
    walkChildrenDepthFirst(deposit, resourcePIDs, true);

    SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false));

    // Vocabulary mappings need to be resolved against the destination since they are not in the hierarchy yet
    PID destinationPID = new PID(getDepositStatus().get(DepositField.containerId.name()));

    for (String resourcePID : resourcePIDs) {
        PID pid = new PID(resourcePID);
        File modsFile = new File(getDescriptionDir(), pid.getUUID() + ".xml");

        // Check if the resource has a description
        if (modsFile.exists()) {
            try {
                Document modsDoc = sb.build(modsFile);

                // Update the MODS document to use approved terms when possible if the vocabularies support remapping
                log.debug("Updating document terms for {} within destination {}", pid, destinationPID);
                boolean modified = updateDocumentTerms(destinationPID, modsDoc.getRootElement());

                // Update the mods document if it was changed
                if (modified) {
                    try (FileOutputStream fos = new FileOutputStream(modsFile)) {
                        new XMLOutputter(Format.getPrettyFormat()).output(modsDoc.getDocument(), fos);
                    }
                }

                // Capture any invalid affiliations as relations
                log.debug("Adding invalid terms for {} within destination {}", pid, destinationPID);
                addInvalidTerms(pid, destinationPID, modsDoc.getRootElement(), model);

            } catch (JDOMException | IOException e) {
                log.error("Failed to parse description file {}", modsFile.getAbsolutePath(), e);
            }
        }
    }
}

From source file:edu.utep.cs.jasg.apiGenerator.APIGenerator.java

License:Open Source License

/** Creates a XML file with an XSL reference using JDom */
private void createXMLFileWithXSLLink() {
    try (FileWriter fileWriter = new FileWriter(outputPath + File.separator + fileName + ".xml");) {

        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());

        HashMap<String, String> piMap = new HashMap<String, String>();
        piMap.put("type", "text/xsl");
        piMap.put("href", "stylesheet.xsl");
        ProcessingInstruction pi = new ProcessingInstruction("xml-stylesheet", piMap);

        doc.getContent().add(0, pi);/*from  w w  w  .  j  ava  2 s.c  o m*/

        xmlOutput.output(doc, fileWriter);

        System.out.println("File \"" + outputPath + File.separator + fileName + ".xml" + "\" created");

    } catch (IOException io) {
        System.err.println("IOException in APIGenerator: " + io.getMessage());
    }
}

From source file:Ejercicios.punto5d.CreatorEntity.java

/**
 *
 * @return documento jdom xml con el contenido de la entidad
 * @throws IOException si hay un error al guardar el archivo en disco
 *///from  www  .  j a va2 s .c om
public Document crearXML() throws IOException {
    if ("".equals(nombre) || "".equals(raiz) || 0 == atributos.size()) {
        return null;
    }
    root = new Element(raiz);
    doc = new Document(root);
    for (String s : atributos.keySet()) {
        Element e = new Element(s).addContent(atributos.get(s));
        getDoc().getRootElement().addContent(e);
    }
    try {
        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(getDoc(), new FileWriter(nombre + ".xml"));

        System.out.println("Archivo Guardado!");
        return doc;

    } catch (IOException e) {
        System.out.println(e.getMessage());
        return null;
    }

}

From source file:es.ucm.fdi.ac.Analysis.java

License:Open Source License

/**
 * Saves this analysis to a file//  ww  w .j ava 2  s.com
 *
 * @param f the file to write to 
 * @throws java.io.IOException
 */
public void saveToFile(File f) throws IOException {
    FileOutputStream fos = null;
    try {
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        fos = new FileOutputStream(f);
        outputter.output(new Document(saveToXML()), fos);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

From source file:es.ucm.fdi.ac.gui.MainGui.java

License:Open Source License

/** 
 * Load a test help file, adhering to the following structure:
 * <helppairs>/*from ww w  .  j  ava  2s .com*/
 *  <testhelp>
 *   <testname>...</testname>
 *   <helpcontent>...</helpcontent>
 *  </testhelp>
 *  ...
 * </helppairs>
 * Notice that 'helpcontent' should be XHTML: old-fashioned HTML may fail to
 * validate.
 */
public HashMap<String, String> loadTestHelpFile(String fileName) throws IOException {
    HashMap<String, String> m = new HashMap<String, String>();
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    URL url = getClass().getClassLoader().getResource(fileName);
    try {
        Document doc = (new SAXBuilder()).build(url);
        for (Element th : doc.getRootElement().getChildren()) {
            m.put(th.getChildTextTrim("testname"), outputter.outputString(th.getChild("helpcontent")));
        }
    } catch (JDOMException | NullPointerException e) {
        throw new IOException("Impossible to read XML file for " + url, e);
    }
    return m;
}

From source file:es.ucm.fdi.clover.gui.CloverSave.java

License:Open Source License

/**
 * Saves the CloverSave to an XML file/* w w  w  .  ja v a 2 s .  c o m*/
 */
public static void save(Collection<ClusterView> views, File f) throws IOException {
    Element root = new Element("clover");
    root.setAttribute("version", saveVersion);
    root.setAttribute("requiresVersion", compatibleWith);
    root.setAttribute("date", new Date().toString());

    Element shared = new Element("shared");
    root.addContent(shared);

    HashMap<Filter, String> filterToId = new HashMap<Filter, String>();
    HashMap<ClusteringEngine, String> engineToId = new HashMap<ClusteringEngine, String>();
    HashMap<ClusterHierarchy, String> hierarchyToId = new HashMap<ClusterHierarchy, String>();

    for (ClusterView v : views) {
        Element view = new Element("view");
        v.save(view);

        Element layoutCache = new Element("layoutCache");
        v.getAnimator().getLayoutCache().save(layoutCache, v.getBase());
        view.addContent(layoutCache);

        Element animatorProps = new Element("animatorProps");
        v.getAnimator().save(animatorProps);
        view.addContent(animatorProps);

        ClusteredGraph cg = (ClusteredGraph) v.getBase();
        ClusterHierarchy h = cg.getHierarchy();
        BaseGraph bg = cg.getBase();

        // create the hierarchy element (if necessary)
        if (!hierarchyToId.containsKey(h)) {
            String hierarchyId = "" + generateId();
            hierarchyToId.put(h, hierarchyId);
            Element hierarchy = new Element("hierarchy");
            hierarchy.setAttribute("id", hierarchyId);
            h.save(hierarchy);

            // save the filtering used in the hierarchy (if necessary)
            if (bg instanceof FilteredGraph) {
                Filter filter = ((FilteredGraph) bg).getFilter();
                if (!filterToId.containsKey(filter)) {
                    String filterId = "" + generateId();
                    filterToId.put(filter, filterId);
                    Element fe = new Element("filter");
                    fe.setAttribute("id", filterId);
                    filter.save(fe);
                    shared.addContent(fe);
                }

                hierarchy.setAttribute("filterId", filterToId.get(filter));
            }

            // save the hierarchy itself: clustering and update-engine
            ClusteringEngine e = h.getEngine();
            Element engine = new Element("engine");
            engine.setAttribute("engineClass", e.getClass().getName());
            e.save(engine);
            hierarchy.addContent(engine);

            shared.addContent(hierarchy);
        }
        view.setAttribute("hierarchyId", hierarchyToId.get(h));

        root.addContent(view);
    }

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    outputter.output(new Document(root), new FileOutputStream(f));
}