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:hintahaku.HintahakuFrame.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    //Avaa//w w  w.  jav a  2  s  . co  m
    Path viimeisin = Asetukset.getViimeisinKokoonpanoKansio();
    JFileChooser valitsin = new JFileChooser(viimeisin == null ? null : viimeisin.toFile());
    valitsin.setFileFilter(new FileNameExtensionFilter("Kokoonpanot (xml)", "xml"));
    int valinta = valitsin.showOpenDialog(rootPane);
    if (valinta != JFileChooser.APPROVE_OPTION) {
        return;
    }
    Path avattava = valitsin.getSelectedFile().toPath();
    Asetukset.setViimeisinKokoonpanoKansio(avattava.getParent());

    org.jdom2.Document xml;
    try (BufferedReader reader = Files.newBufferedReader(avattava)) {
        xml = new SAXBuilder().build(reader);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Tiedoston avaaminen eponnistui!", "Virhe!",
                JOptionPane.ERROR_MESSAGE);
        return;
    } catch (JDOMException ex) {
        JOptionPane.showMessageDialog(null, "Avattu tiedosto ei ole kokoonpano!", "Virhe!",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    Element juuri = xml.getRootElement();
    if (!"Tallennettu Hintahaku-kokoonpano".equals(juuri.getAttributeValue("info"))) {
        JOptionPane.showMessageDialog(null, "Avattu tiedosto ei ole kokoonpano!", "Virhe!",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    String vanhaTeksti = jLabel11.getText();
    jLabel11.setText("Haetaan kokoonpanon hintatietoja...");
    new SwingWorker<List<RaakaTuote>, Void>() {

        @Override
        protected List<RaakaTuote> doInBackground() throws Exception {
            List<RaakaTuote> lista = new ArrayList<>();
            Pattern urlPattern = Pattern.compile("http://hinta\\.fi/\\d+");
            for (Element tuoteEl : juuri.getChildren()) {
                String url = tuoteEl.getChildText("url");
                int maara = Integer.parseInt(tuoteEl.getChildText("mr"));
                if (!urlPattern.matcher(url).matches() || maara <= 0) {
                    throw new KokoonpanoTiedostoException();
                }

                Document dok;
                try {
                    dok = Jsoup.connect(url).userAgent(USERAGENT).get();
                } catch (HttpStatusException ex) { //Tuotetta ei ole en olemassa
                    dok = null;
                }
                lista.add(new RaakaTuote(url, dok, maara));
            }
            return lista;
        }

        @Override
        protected void done() {
            List<RaakaTuote> lista;
            try {
                lista = get();
            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(null, "Tuntematon virhe!", "Virhe!", JOptionPane.ERROR_MESSAGE);
                jLabel11.setText(vanhaTeksti);
                return;
            } catch (ExecutionException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof IOException) {
                    JOptionPane.showMessageDialog(null, "Ohjelma ei saa yhteytt hinta.fi-palvelimeen!",
                            "Virhe!", JOptionPane.ERROR_MESSAGE);
                } else if (cause instanceof NumberFormatException
                        || cause instanceof KokoonpanoTiedostoException) {
                    JOptionPane.showMessageDialog(null, "Avattu tiedosto on virheellinen!", "Virhe!",
                            JOptionPane.ERROR_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "Tuntematon virhe!", "Virhe!",
                            JOptionPane.ERROR_MESSAGE);
                }
                jLabel11.setText(vanhaTeksti);
                return;
            }

            List<KokoonpanoTuote> lisattavat = new ArrayList<>();
            for (RaakaTuote raakaTuote : lista) {
                if (raakaTuote.dok == null) {
                    Object[] napit = { "Poista tuote", "l nyt" };
                    int valinta = JOptionPane.showOptionDialog(null,
                            "<html>Tuotetta ei lydy en hinta.fi:st:<br><b>" + raakaTuote.url
                                    + "</b><br><br>Haluatko poistaa tuotteen tiedostosta, vai jtt sen vain nyttmtt kokoonpanossa? (Tallentaminen poistaa silti.)",
                            "Varmistus", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, napit,
                            napit[1]);
                    if (valinta == JOptionPane.YES_OPTION) {
                        Iterator<Element> xmlIter = juuri.getChildren().iterator();
                        while (xmlIter.hasNext()) {
                            Element tuoteEl = xmlIter.next();
                            if (raakaTuote.url.equals(tuoteEl.getChildText("url"))) {
                                xmlIter.remove();
                                break;
                            }
                        }
                        try (BufferedWriter writer = Files.newBufferedWriter(avattava)) {
                            new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null,
                                    "Tuotteen poistaminen eponnistui, joten se jtetn tiedostoon!",
                                    "Virhe!", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } else {
                    Tuote tuote = new Tuote(raakaTuote.url, raakaTuote.dok);
                    if (tuote.getParasHinta() == null) {
                        Object[] napit = { "Poista tuote", "Jt kokoonpanoon" };
                        int valinta = JOptionPane.showOptionDialog(null,
                                "<html>Tuotetta ei ole saatavilla en yhdesskn kaupassa:<br><b>"
                                        + tuote.getNimi()
                                        + "</b><br><br>Haluatko poistaa tuotteen tiedostosta?",
                                "Varmistus", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null,
                                napit, napit[1]);
                        if (valinta == JOptionPane.YES_OPTION) {
                            Iterator<Element> xmlIter = juuri.getChildren().iterator();
                            while (xmlIter.hasNext()) {
                                Element tuoteEl = xmlIter.next();
                                if (tuote.getUrl().equals(tuoteEl.getChildText("url"))) {
                                    xmlIter.remove();
                                    break;
                                }
                            }
                            try (BufferedWriter writer = Files.newBufferedWriter(avattava)) {
                                new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
                                continue; //Keskeytetn tuotteen lisminen
                            } catch (IOException ex) {
                                JOptionPane.showMessageDialog(null,
                                        "Tuotteen poistaminen eponnistui, joten se jtetn tiedostoon!",
                                        "Virhe!", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    }

                    lisattavat.add(new KokoonpanoTuote(tuote, raakaTuote.maara));
                }
            }

            Kokoonpano.tyhjennaJaLisaaMonta(lisattavat);
            Kokoonpano.setTiedosto(avattava);
            paivitaKokoonpanonTulos();
            paivitaLisattyMaara();
            jLabel11.setText("Avattu: " + avattava.getFileName().toString());
            jButton7.setEnabled(false);
        }
    }.execute();
}

From source file:hintahaku.Suodattimet.java

public static void tallennaNimella(Path tiedosto) throws IOException {
    Element juuri = new Element("suodattimet");
    juuri.setAttribute("info", "Hintahaku-suodattimet");
    juuri.setAttribute("pvm", new SimpleDateFormat("d.M.y H:mm:ss").format(Calendar.getInstance().getTime()));

    for (Kauppa kauppa : kaupatEventList) {
        Element kauppaxml = new Element("kauppa");
        kauppaxml.addContent(new Element("nimi").setText(kauppa.getKaupanNimi()));
        kauppaxml.addContent(new Element("voiNoutaa").setText(Boolean.toString(kauppa.isVoiNoutaa())));
        kauppaxml.addContent(new Element("suodataPois").setText(Boolean.toString(kauppa.isSuodataPois())));
        juuri.addContent(kauppaxml);//  w w w . ja v a 2 s. c o m
    }

    Document xml = new Document(juuri);
    try (BufferedWriter writer = Files.newBufferedWriter(tiedosto)) {
        new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
    }

    Suodattimet.tiedosto = tiedosto;
}

From source file:info.okoshi.trifulx.Xml.java

License:Open Source License

/**
 * Write XML to output stream.<br>
 * Output stream will be closed on finally.<br>
 *
 * @param out/*from w  ww  . j ava  2 s  . c  om*/
 *          Output stream
 * @param charset
 *          Character set
 * @throws IOException
 *           I/O exception
 */
public void save(OutputStream out, Charset charset) throws IOException {
    try {
        Format jdomFormat = Format.getPrettyFormat();
        jdomFormat.setEncoding(charset.name());
        XMLOutputter outputter = new XMLOutputter();
        outputter.setFormat(jdomFormat);
        outputter.output(document, out);
    } finally {
        out.close();
    }
}

From source file:information.Information.java

License:Open Source License

public static void generarXML() {
    Document documento;/*from www .  jav  a 2s . com*/
    Element raiz = new Element("Salones");
    documento = new Document(raiz);
    for (Salon salon : salons) {
        Element salone = new Element("Salon");
        salone.setAttribute("Nombre", salon.getName());
        for (Room sala : salon.getRooms()) {
            Element salae = new Element("Sala");
            salae.setAttribute("Nombre", sala.getName());
            salae.setAttribute("Horizontal", Boolean.toString(sala.isHorizontal()));
            salae.addContent(new Element("SufijoIP").setText(Integer.toString(sala.getRoomIPSufix())));
            for (Row fila : sala.getRows()) {
                Element filae = new Element("Fila");
                for (ServerComputer equipo : fila.getComputers()) {
                    Element equipoe = new Element("Equipo");
                    equipoe.setAttribute("Numero", Integer.toString(equipo.getComputerNumber()));
                    equipoe.addContent(new Element("IP").setText(equipo.getIP()));
                    equipoe.addContent(new Element("Mac").setText(equipo.getMac()));
                    equipoe.addContent(new Element("Hostname").setText(equipo.getHostname()));
                    for (String[] resultados : equipo.getResults()) {
                        String orden = resultados[0];
                        String resultado = resultados[1];
                        Element resultadoe = new Element("Ejecucion");
                        resultadoe.addContent(new Element("Orden").setText(orden));
                        resultadoe.addContent(new Element("Resultado").setText(resultado));
                        equipoe.addContent(resultadoe);
                    }
                    filae.addContent(equipoe);
                }
                salae.addContent(filae);
            }
            salone.addContent(salae);
        }
        raiz.addContent(salone);
    }

    XMLOutputter xmlOutput = new XMLOutputter();
    try {
        xmlOutput.output(documento, System.out);
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(documento, new FileWriter(informationPath));
    } catch (IOException ex) {
        Logger.getLogger(Information.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:interfacermi.Traza.java

public void insertarTraza(String hora, String actor, String accion) {

    Document document = null;//  w  w  w .j  a va 2 s .c o  m
    Element root = null;
    File xmlFile = new File("Traza.xml");
    //Se comprueba si el archivo XML ya existe o no.
    if (xmlFile.exists()) {
        FileInputStream fis;
        try {
            fis = new FileInputStream(xmlFile);
            SAXBuilder sb = new SAXBuilder();
            document = sb.build(fis);
            //Si existe se obtiene su nodo raiz.
            root = document.getRootElement();
            fis.close();
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    } else {
        //Si no existe se crea su nodo raz.
        document = new Document();
        root = new Element("Traza");
    }

    //Se crea un nodo Hecho para insertar la informacin.
    Element nodohecho = new Element("Hecho");
    //Se crea un nodo hora para insertar la informacin correspondiente a la hora.
    Element nodohora = new Element("Hora");
    //Se crea un nodo actor para insertar la informacin correspondiente al actor.
    Element nodoactor = new Element("Actor");
    //Se crea un nodo accion para insertar la informacin correspondiente a la accin.
    Element nodoaccion = new Element("Accion");

    //Se asignan los valores enviados para cada nodo.
    nodohora.setText(hora);
    nodoactor.setText(actor);
    nodoaccion.setText(accion);
    //Se aade el contenido al nodo Hecho.  
    nodohecho.addContent(nodohora);
    nodohecho.addContent(nodoactor);
    nodohecho.addContent(nodoaccion);
    //Se aade el nodo Hecho al nodo raz.
    root.addContent(nodohecho);
    document.setContent(root);

    //Se procede a exportar el nuevo o actualizado archivo de traza XML   
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());

    try {
        xmlOutput.output(document, new FileWriter("Traza.xml"));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:io.LoadSave.java

License:Open Source License

/**
 * Saves the current status to a .oger file
 *//*from ww w .  j a  v  a2  s  .c o  m*/
public static void save() {
    // get the selected file
    File file = IODialog.showSaveDialog(".oger", true);
    // not canceled
    if (file != null) {
        DefaultTreeModel treeModel = RoomTreeModel.getInstance();
        ParticipantTableModel participantModel = ParticipantTableModel.getInstance();

        // Create the XML root Element
        Element root = new Element("root");

        // Create a JDOM Document based on the root Element
        Document document = new Document(root);

        List<Participant> participants = participantModel.getParticipants();

        // Participants
        Element allParticipantsElement = new Element("allParticipants");

        for (Participant p : participants) {
            Element participantElement = new Element("participant");

            Attribute firstNameAttribute = new Attribute("firstName", p.getFirstName());
            participantElement.setAttribute(firstNameAttribute);

            Attribute lastNameAttribute = new Attribute("lastName", p.getLastName());
            participantElement.setAttribute(lastNameAttribute);

            Attribute mailAttribute = new Attribute("mail", p.geteMailAdress());
            participantElement.setAttribute(mailAttribute);

            Attribute groupAttribute = new Attribute("group", Integer.toString(p.getGroupNumber()));
            participantElement.setAttribute(groupAttribute);

            allParticipantsElement.addContent(participantElement);
        }
        root.addContent(allParticipantsElement);

        // Slots with reviews
        Element allSlotsElement = new Element("Slots");

        // all slots
        SlotNode currentSlotNode;
        RoomNode currentRoomNode;
        DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) treeModel.getRoot();

        DateFormat dateFormatter = new SimpleDateFormat("dd.MM.yy");
        DateFormat beginFormatter = new SimpleDateFormat("HH:mm");
        DateFormat endFormatter = new SimpleDateFormat("HH:mm");
        ;

        for (Enumeration<SlotNode> enumSlots = rootNode.children(); enumSlots.hasMoreElements();) {
            currentSlotNode = (SlotNode) enumSlots.nextElement();
            Slot currentSlot = (Slot) currentSlotNode.getUserObject();

            Element slotElement = new Element("Slot");

            String date = dateFormatter.format(currentSlot.getDate().getTime());
            Attribute dateAttribute = new Attribute("Date", date);
            slotElement.setAttribute(dateAttribute);

            String begin = beginFormatter.format(currentSlot.getBeginTime().getTime());
            Attribute beginAttribute = new Attribute("Begin", begin);
            slotElement.setAttribute(beginAttribute);

            String end = endFormatter.format(currentSlot.getEndTime().getTime());
            Attribute endAttribute = new Attribute("End", end);
            slotElement.setAttribute(endAttribute);

            // all rooms
            Element allRoomsElement = new Element("AllRooms");

            for (Enumeration<RoomNode> enumRooms = currentSlotNode.children(); enumRooms.hasMoreElements();) {
                currentRoomNode = (RoomNode) enumRooms.nextElement();
                Room currentRoom = (Room) currentRoomNode.getUserObject();

                Element roomElement = new Element("Room");

                Attribute beamerAttribute;
                if (currentRoom.hasBeamer()) {
                    beamerAttribute = new Attribute("Beamer", "true");
                } else {
                    beamerAttribute = new Attribute("Beamer", "false");
                }
                roomElement.setAttribute(beamerAttribute);

                Attribute idAttribute = new Attribute("ID", currentRoom.getRoomID());
                roomElement.setAttribute(idAttribute);

                String beginRoom = beginFormatter.format(currentRoom.getBeginTime().getTime());
                Attribute beginRoomAttribute = new Attribute("Begin", beginRoom);
                roomElement.setAttribute(beginRoomAttribute);

                String endRoom = endFormatter.format(currentRoom.getEndTime().getTime());
                Attribute endRoomAttribute = new Attribute("End", endRoom);
                roomElement.setAttribute(endRoomAttribute);

                allRoomsElement.addContent(roomElement);

            }
            slotElement.addContent(allRoomsElement);

            allSlotsElement.addContent(slotElement);

        }

        root.addContent(allSlotsElement);

        try {
            // output
            XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
            xmlOutputter.output(document, new FileOutputStream(file));
            Main.setSaved(true);
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        }
    }
}

From source file:io.smartspaces.master.server.services.internal.support.JdomMasterDomainModelCreator.java

License:Apache License

/**
 * Create a description of the entire space domain.
 *
 * @param activityRepository/*  w  ww . j a va 2s  . co  m*/
 *          the repository for activity entities
 * @param controllerRepository
 *          the repository for controller entities
 * @param resourceRepository
 *          the repository for resources
 * @param automationRepository
 *          the repository for automation entities
 *
 * @return the XML description
 */
public String newModel(ActivityRepository activityRepository, SpaceControllerRepository controllerRepository,
        ResourceRepository resourceRepository, AutomationRepository automationRepository) {

    try {
        Element rootElement = new Element(ELEMENT_NAME_DESCRIPTION_ROOT_ELEMENT);
        Document document = new Document(rootElement);

        rootElement.addContent(newSpaceControllerEntries(controllerRepository));
        rootElement.addContent(newActivityEntries(activityRepository));
        rootElement.addContent(newLiveActivityEntries(activityRepository));
        rootElement.addContent(newLiveActivityGroupEntries(activityRepository));
        rootElement.addContent(newSpaceEntries(activityRepository));
        rootElement.addContent(newResourceEntries(resourceRepository));
        rootElement.addContent(newNamedScriptEntries(automationRepository));

        StringWriter out = new StringWriter();

        Format format = Format.getPrettyFormat();
        XMLOutputter outputter = new XMLOutputter(format);
        outputter.output(document, out);

        return out.toString();
    } catch (IOException e) {
        throw new SmartSpacesException("Could not create domain model", e);
    }
}

From source file:io.wcm.maven.plugins.contentpackage.unpacker.ContentUnpacker.java

License:Apache License

private void writeXmlWithExcludes(InputStream inputStream, OutputStream outputStream)
        throws IOException, JDOMException {
    SAXBuilder saxBuilder = new SAXBuilder();
    Document doc = saxBuilder.build(inputStream);
    applyXmlExcludes(doc.getRootElement(), "");

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setLineSeparator(LineSeparator.UNIX));
    outputter.setXMLOutputProcessor(new OneAttributePerLineXmlProcessor());
    outputter.output(doc, outputStream);
    outputStream.flush();//from   w  ww .j  a  v  a 2  s .  c om
}

From source file:io.wcm.maven.plugins.i18n.SlingI18nMap.java

License:Apache License

/**
 * Build i18n resource XML in Sling i18n Message format.
 * @return XML/*from w ww.  j  a v  a 2 s  .  c o  m*/
 */
public String getI18nXmlString() {
    Format format = Format.getPrettyFormat();
    XMLOutputter outputter = new XMLOutputter(format);
    return outputter.outputString(buildI18nXml());
}

From source file:it.cnr.ilc.clavius.controller.ProofReaderController.java

public void saveProof() {
    System.err.println("salva proofreader.." + getCurrSentenceNumber());

    Document analysis = this.getDocumentTei().getAnalysis();

    Element rootNode = analysis.getRootElement();
    List<Element> sentenceList = rootNode.getChildren("sentence");
    Element sentenceNode = sentenceList.get(getCurrSentenceNumber().intValue());
    List<Element> tokenList = sentenceNode.getChildren("token");

    for (int i = 0; i < tokenList.size(); i++) {
        Element tokenNode = (Element) tokenList.get(i);
        PosTaggedToken tk = res.get(i);//  w w w.j  av  a  2 s .co m
        tokenNode.setAttribute("lemma", tk.getLemma());
        tokenNode.setAttribute("morphoCode",
                tk.getPosTag().get(0).concat(tk.getPerson().get(0)).concat(tk.getNumber().get(0))
                        .concat(tk.getTense().get(0)).concat(tk.getMood().get(0)).concat(tk.getVoice().get(0))
                        .concat(tk.getGender().get(0)).concat(tk.getCases().get(0))
                        .concat(tk.getDegree().get(0))

        );
    }

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    String newAnalysis = outputter.outputString(analysis);
    StringBuilder sb = new StringBuilder(newAnalysis);

    HelperIO.writeOut(sb,
            HandleConstants.getWorkDir().concat(HandleConstants.getLetterRif()).concat("-linguistic-dev.xml"));

}