Example usage for org.jdom2.output XMLOutputter XMLOutputter

List of usage examples for org.jdom2.output XMLOutputter XMLOutputter

Introduction

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

Prototype

public XMLOutputter() 

Source Link

Document

This will create an XMLOutputter with a default Format and XMLOutputProcessor .

Usage

From source file:middleware.Reserva.java

public static void EliminarReserva(String reservaEliminar) {
    try {/*w  ww .  j av a  2  s  . c om*/
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo que tiene las reservas
        File xmlFile = new File("reserva.xml");
        //objeto que caragra el archivo tipo document
        Document doc = (Document) builder.build(xmlFile);
        //se obtiene el padre del xml
        Element rootNode = doc.getRootElement();
        //se obtiene el hijo "reserva"
        List reservas = rootNode.getChildren("reserva");
        //se declara un iterator para recorrer el archivo
        Iterator iter = reservas.iterator();
        //se recorre el archivo
        while (iter.hasNext()) {
            Element reserva = (Element) iter.next();
            //se elimina la reserva ya pagada
            if (reserva.getAttributeValue("clave").equals(reservaEliminar)) {
                iter.remove();
            }
        }

        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //se guardan los cambios
        xmlOutput.output(doc, new FileWriter("reserva.xml"));

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }

}

From source file:middleware.Reserva.java

public static void ReservarVuelo(String nombre, String vueloReserva) {
    int numeroReservas = 0;
    int id = 0;/*from  w w w  .  ja  v a2  s.c  o m*/
    try {
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo que tiene las reservas
        File xmlFile = new File("reserva.xml");
        //Se crea el documento a traves del archivo
        Document doc = (Document) builder.build(xmlFile);
        //se obtiene el padre del xml
        Element rootNode = doc.getRootElement();
        XMLOutputter xmlOutput = new XMLOutputter();
        Element reserva = new Element("reserva");
        //se crea una lista de losh hijos reserva
        List list = rootNode.getChildren("reserva");
        //tamao de la lista de reservas
        numeroReservas = list.size();
        //aqui se gerar el id automatico que sera la cantidad de nodos hijos mas 1
        id = numeroReservas + 1;
        //se crea el nodo reserva con id         
        reserva.setAttribute(new Attribute("clave", Integer.toString(id)));
        Element vuelo = new Element("vuelo");
        //se crean los hijos de reserva que son vuelo y nombre
        vuelo.setAttribute(new Attribute("clave", vueloReserva));
        //se agregan el nodo hijo nombre en el nodo reserva 
        vuelo.addContent(new Element("nombre").setText(nombre));
        //se inserta el nodo vuelo en el nodo reserva
        reserva.addContent(vuelo);
        //se agrega el nodo reserva al nodo padre del xml
        doc.getRootElement().addContent(reserva);
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //se guardan los cambios en el xml
        xmlOutput.output(doc, new FileWriter("reserva.xml"));

        System.out.println("Reserva agregada con id: " + id);

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }

}

From source file:middleware.Vuelo.java

public static void EditarCapacidadVuelo(String vuelo) {
    //se crea una lista de vuelos
    ArrayList<Vuelo> listaVuelos = new ArrayList<Vuelo>();
    //se llena la lista co todos los vuelos
    listaVuelos = ConsultarVuelos();/*from   w  ww  .  j  a  va2s . c  o  m*/
    //se crea un objeto vuelo para poder acceder manipular las funciones get y set
    Vuelo objetoVuelo = new Vuelo();
    int capacidadVuelo = 0;
    try {
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo que tiene las reservas
        File xmlFile = new File("disponibilidad.xml");
        //objeto que caragra el archivo tipo document
        Document doc = (Document) builder.build(xmlFile);
        //se obtiene el padre del xml
        Element rootNode = doc.getRootElement();
        //se obtiene el hijo "vuelo"
        List reservas = rootNode.getChildren("vuelo");
        //se declara un iterator para recorrer el archivo
        Iterator iter = reservas.iterator();
        //se recorre el archivo
        while (iter.hasNext()) {
            Element reserva = (Element) iter.next();
            //se elimina el vuelo que se editara 
            if (reserva.getAttributeValue("id").equals(vuelo)) {
                iter.remove();
            }
        }

        XMLOutputter xmlOutput = new XMLOutputter();
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //se guardan los cambios
        xmlOutput.output(doc, new FileWriter("disponibilidad.xml"));

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }
    //se recorre la lista de vuelos del xml
    for (int i = 0; i < listaVuelos.size(); i++) {
        // si vuelo en la lista donde esta parado el for es igual al vuelo que queremos editar de llena el objeto
        if (listaVuelos.get(i).getId().equals(vuelo)) {
            capacidadVuelo = Integer.parseInt(listaVuelos.get(i).getCapacidad());
            capacidadVuelo = capacidadVuelo - 1;
            objetoVuelo.setId(listaVuelos.get(i).getId());
            objetoVuelo.setLinea(listaVuelos.get(i).getLinea());
            objetoVuelo.setOrigen(listaVuelos.get(i).getOrigen());
            objetoVuelo.setDestino(listaVuelos.get(i).getDestino());
            objetoVuelo.setFecha(listaVuelos.get(i).getFecha());
            objetoVuelo.setHora(listaVuelos.get(i).getHora());
            objetoVuelo.setCapacidad(Integer.toString(capacidadVuelo));
            objetoVuelo.setPrecio(listaVuelos.get(i).getPrecio());
        }
    }
    // se llama a la funcion editar vuelo que insertara el vuelo de nuevo en el xml pero con la capacidad nueva
    EditarVuelo(objetoVuelo.getId(), objetoVuelo.getLinea(), objetoVuelo.getOrigen(), objetoVuelo.getDestino(),
            objetoVuelo.getFecha(), objetoVuelo.getHora(), objetoVuelo.getCapacidad(), objetoVuelo.getPrecio());

}

From source file:middleware.Vuelo.java

public static void EditarVuelo(String id, String linea, String origen, String destino, String fecha,
        String hora, String capacidad, String precio) {
    int numeroVuelos = 0;

    try {//  w ww  .  ja v  a  2  s. c  om
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo con los vuelos
        File xmlFile = new File("disponibilidad.xml");
        ////objeto que caragra el archivo tipo document
        Document doc = (Document) builder.build(xmlFile);
        //nodo raiz del xml
        Element rootNode = doc.getRootElement();
        XMLOutputter xmlOutput = new XMLOutputter();
        //se crea nodo vuelo
        Element vuelo = new Element("vuelo");
        //se crea lista de vuelos
        List list = rootNode.getChildren("vuelo");
        //se guarda el tamao de la lista
        numeroVuelos = list.size();
        //id autogenerado de los vuelos

        //se crea el nodo de vuelos          
        vuelo.setAttribute(new Attribute("id", (id)));
        vuelo.addContent(new Element("linea").setText(linea));
        vuelo.addContent(new Element("origen").setText(origen));
        vuelo.addContent(new Element("destino").setText(destino));
        vuelo.addContent(new Element("fecha").setText(fecha));
        vuelo.addContent(new Element("hora").setText(hora));
        vuelo.addContent(new Element("capacidad").setText(capacidad));
        vuelo.addContent(new Element("precio").setText(precio));
        //se agrega el nodo vuelo al noda raiz
        doc.getRootElement().addContent(vuelo);
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //guarda cambios en el xml
        xmlOutput.output(doc, new FileWriter("disponibilidad.xml"));

        System.out.println("Vuelo agregado!");

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }

}

From source file:middleware.Vuelo.java

public static void CargarVuelo(String linea, String origen, String destino, String fecha, String hora,
        String capacidad, String precio) {
    int numeroVuelos = 0;
    int id = 0;/*from  ww  w.  ja v a 2 s.  c om*/
    try {
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo con los vuelos
        File xmlFile = new File("disponibilidad.xml");
        ////objeto que caragra el archivo tipo document
        Document doc = (Document) builder.build(xmlFile);
        //nodo raiz del xml
        Element rootNode = doc.getRootElement();
        XMLOutputter xmlOutput = new XMLOutputter();
        //se crea nodo vuelo
        Element vuelo = new Element("vuelo");
        //se crea lista de vuelos
        List list = rootNode.getChildren("vuelo");
        //se guarda el tamao de la lista
        numeroVuelos = list.size();
        //id autogenerado de los vuelos
        id = numeroVuelos + 1;
        //se crea el nodo de vuelos          
        vuelo.setAttribute(new Attribute("id", Integer.toString(id)));
        vuelo.addContent(new Element("linea").setText(linea));
        vuelo.addContent(new Element("origen").setText(origen));
        vuelo.addContent(new Element("destino").setText(destino));
        vuelo.addContent(new Element("fecha").setText(fecha));
        vuelo.addContent(new Element("hora").setText(hora));
        vuelo.addContent(new Element("capacidad").setText(capacidad));
        vuelo.addContent(new Element("precio").setText(precio));
        //se agrega el nodo vuelo al noda raiz
        doc.getRootElement().addContent(vuelo);
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //guarda cambios en el xml
        xmlOutput.output(doc, new FileWriter("disponibilidad.xml"));

        System.out.println("Vuelo agregado con: " + id);

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }

}

From source file:model.data.manager.Manager.java

License:Open Source License

/**
 * TODO FONCTION BCP TROP LONGUE LOL/*from www. j av  a2s  . co m*/
 */
@Override
public void saving(String path) {
    String currentPublicKey = userManager.getCurrentUser().getKeys().getPublicKey().toString(16);
    AsymKeysImpl keys = userManager.getCurrentUser().getKeys().copy();
    keys.decryptPrivateKey(userManager.getCurrentUser().getClearPwd());
    // Recovery all local data in a new Manager
    Manager manager = new Manager(null);
    manager.recovery(path);

    if (path == null || path.isEmpty())
        path = VARIABLES.ManagerFilePath;
    // Element Root
    Element root = new Element(Manager.class.getName());
    // ArrayList are used for adding data in local file.
    ArrayList<User> users = new ArrayList<User>();
    ArrayList<Item> items = this.userManager.getUserItems(currentPublicKey);
    ArrayList<UserMessage> messages = null; // TODO this.getUserMessages(currentPublicKey);
    ArrayList<Conversations> conversations = new ArrayList<Conversations>();
    ArrayList<Favorites> favorites = new ArrayList<Favorites>();
    HashMap<String, ArrayList<Contrat>> deals = new HashMap<String, ArrayList<Contrat>>();

    Conversations converC = this.messageManager.getUserConversations(currentPublicKey);
    if (converC != null)
        conversations.add(converC);
    ArrayList<Contrat> arrayDealsC = this.contratManager.getDealsCurrentUser();
    if (arrayDealsC != null)
        deals.put(currentPublicKey, arrayDealsC);
    Favorites favoC = this.favoriteManager.getFavoritesCurrentUser();
    if (favoC != null) {
        favoC.encrypt(userManager.getCurrentUser().getClearPwd());
        favoC.sign(keys);
        favorites.add(favoC);
    }

    // Element users
    users.add(this.userManager.getCurrentUser());
    Element usersElement = new Element("users");
    usersElement.addContent(this.userManager.getCurrentUser().getRootElement());
    for (User user : manager.userManager.getUsers()) {
        String userKey = user.getKeys().getPublicKey().toString(16);
        if (!user.getKeys().getPublicKey().toString(16).equals(currentPublicKey)) {
            usersElement.addContent(user.getRootElement());
            users.add(user);
            // Filling ArrayList items
            for (Item i : this.userManager.getUserItems(userKey)) {
                if (!items.contains(i))
                    items.add(i);
            }
            for (Item i : manager.userManager.getUserItems(userKey)) {
                if (!items.contains(i))
                    items.add(i);
            }
            // Filling ArrayList messages
            /* TODO   for (Message m : this.getUserMessages(userKey)) {
                  if(!messages.contains(m))
                     messages.add(m);
               }
               for (Message m : manager.getUserMessages(userKey)) {
                  if(!messages.contains(m))
                     messages.add(m);
               } */

            // Filling ArrayList conversations
            Conversations c;
            c = this.messageManager.getUserConversations(userKey);
            if (c != null && !conversations.contains(c))
                conversations.add(c);
            c = manager.messageManager.getUserConversations(userKey);
            if (c != null && !conversations.contains(c))
                conversations.add(c);
            // Filling ArrayList favorites
            Favorites f;
            f = this.favoriteManager.getUserFavorites(userKey);
            if (f != null && !favorites.contains(f)) {
                favorites.add(f);
            }
            f = manager.favoriteManager.getUserFavorites(userKey);
            if (f != null && !favorites.contains(f))
                favorites.add(f);
            // Filling ArrayList deals
            if (!deals.containsKey(userKey))
                deals.put(userKey, new ArrayList<Contrat>());
            for (Contrat d : this.contratManager.getUserDeals(userKey)) {
                if (!deals.get(userKey).contains(d))
                    deals.get(userKey).add(d);
            }
            for (Contrat d : manager.contratManager.getUserDeals(userKey)) {
                if (!deals.get(userKey).contains(d))
                    deals.get(userKey).add(d);
            }
        }
    }
    // Element items
    Element itemsElement = new Element("items");
    for (Item i : items) {
        itemsElement.addContent(i.getRootElement());
    }
    // Element messages
    Element messagesElement = new Element("messages");
    /* TODO FIX BUG
    for (Message m : messages) {
       messagesElement.addContent(m.getRootElement());
    }
    */
    // Element ReceivedMessages
    Element conversationsElement = new Element("ReceivedMessages");
    for (Conversations c : conversations) {
        conversationsElement.addContent(c.getRootElement());
    }
    // Element Favorites
    Element favoritesElement = new Element("favorites");
    for (Favorites f : favorites) {
        favoritesElement.addContent(f.getRootElement());
    }
    // Element Deals
    Element dealsElement = new Element("deals");
    for (User u : users) {
        String userKey = u.getKeys().getPublicKey().toString(16);
        for (Contrat d : deals.get(userKey)) {
            Element ownerElement = new Element("owner");
            Element dealElement = new Element("deal");
            ownerElement.addContent(userKey);
            dealElement.addContent(ownerElement);
            dealElement.addContent(d.getRootElement());
            dealsElement.addContent(dealElement);
        }
    }
    // Adding all elements in root element
    root.addContent(usersElement);
    root.addContent(itemsElement);
    root.addContent(messagesElement);
    root.addContent(conversationsElement);
    root.addContent(favoritesElement);
    root.addContent(dealsElement);
    // Writing in file
    Document doc = new Document(root);
    XMLOutputter xmlOutput = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    format.setEncoding("UTF8");
    xmlOutput.setFormat(format);
    try {
        xmlOutput.output(doc, new FileWriter(path));
    } catch (IOException e) {
        Printer.printError(this, "saving", "saving : " + e.toString());
    } finally {
        Printer.printInfo(this, "saving", "Data saved localy");
    }
}

From source file:Model.Model.java

public void createXML() {
    try {/*from  w w w  . j  a v a 2  s . co  m*/
        addSubConjuntosToFirstState();
        Element structure = new Element("structure");
        Document doc = new Document(structure);
        structure.addContent(new Element("type").setText("fa"));
        Element automaton = new Element("automaton");
        for (int i = 0; i < subConjuntos.size(); i++) {
            Element state = new Element("state");
            state.setAttribute(new Attribute("id", subConjuntos.get(i).get(0).getIdStateFrom()));
            state.setAttribute(new Attribute("name", "q" + subConjuntos.get(i).get(0).getIdStateFrom()));
            for (int j = 0; j < transicionesAFD.size(); j++) {
                if (subConjuntos.get(i).get(0).getIdStateFrom() == transicionesAFD.get(j).getIdStateFrom()) {
                    if (transicionesAFD.get(j).isEsEstadoInicial()
                            || subConjuntos.get(i).get(0).isEsEstadoInicial()) {
                        state.addContent(new Element("initial"));
                    }
                    if (transicionesAFD.get(j).isEsEstadoFinal()) {
                        state.addContent(new Element("final"));
                    }
                    if (!isNotInSubconjuntos(transicionesAFD.get(j).getIdStateTo()).isEmpty()) {
                        transicionesAFD.get(j)
                                .setIdStateTo(isNotInSubconjuntos(transicionesAFD.get(j).getIdStateTo()));
                    }
                    Element transition = new Element("transition");
                    transition.addContent(new Element("from").setText(transicionesAFD.get(j).getIdStateFrom()));
                    transition.addContent(new Element("to").setText(transicionesAFD.get(j).getIdStateTo()));
                    transition.addContent(new Element("read").setText(transicionesAFD.get(j).getLetter()));
                    automaton.addContent(transition);
                }
            }
            automaton.addContent(state);
        }
        doc.getRootElement().addContent(automaton);
        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.setFormat(Format.getPrettyFormat());
        String[] parts = urlFile.split(Pattern.quote("."));
        String a = parts[0];
        xmlOutput.output(doc, new FileWriter(a + "Transform.jff"));
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:modelo.ArchivoXmlUsuario.java

public void guardar() throws FileNotFoundException, IOException {
    XMLOutputter xmlOut = new XMLOutputter();
    xmlOut.output(this.documento, new PrintWriter(this.ruta));
    xmlOut.output(this.documento, System.out);
}

From source file:Modelo.CrearXml.java

public void crearArchivoXml(LinkedList<EmpleadoContrato> lista) {

    try {//w  w w  .  ja  v  a2  s  .  c o m
        Element empleadoContrato = new Element("EmpleadoContrato");
        Document doc = new Document(empleadoContrato);
        for (int i = 0; i < lista.size(); i++) {
            Element empleado = new Element("empleado");
            empleado.setAttribute(new Attribute("id", lista.get(i).getId()));
            empleado.addContent(new Element("Nombre").setText(lista.get(i).getNombre()));
            empleado.addContent(new Element("Telefono").setText(lista.get(i).getTelefono()));
            empleado.addContent(new Element("Numero de Contrato").setText(lista.get(i).getNumContrato()));
            empleado.addContent(new Element("Actividad").setText(lista.get(i).getActividad()));

            doc.getRootElement().addContent(empleado);
        }
        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, new FileWriter("empleadoC.xml"));

        System.out.println("File Saved!");

    } catch (IOException io) {
        System.out.println(io.getMessage());
    }

}

From source file:Modelo.FileRead.java

public void escribir() {
    try {//from  w w w  .  j a v  a2s.  co  m
        Element company = new Element("familias");
        for (int i = 0; i < fam.size(); i++) {
            Element familia = new Element("Familia");
            Familia aux = fam.get(i);
            familia.setAttribute(new Attribute("nombre", aux.getNombre()));
            ArrayList<MiembroFamilia> mf = fam.get(i).getMiembros();
            for (int j = 0; j < mf.size(); j++) {
                Element miembro = new Element("MiembroFamilia");
                miembro.addContent(new Element("nombre").setText(mf.get(j).getNombre()));
                miembro.addContent(new Element("rut").setText(mf.get(j).getRut()));
                miembro.addContent(new Element("clave").setText(mf.get(j).getClave()));
                familia.addContent(miembro);
            }
            ArrayList<Fotografia> f = fam.get(i).getFotos();
            for (int j = 0; j < f.size(); j++) {
                Element fotos = new Element("Fotografia");
                fotos.addContent(new Element("path").setText(f.get(j).getPath()));
                fotos.addContent(new Element("comentario").setText(f.get(j).getComentario()));
                familia.addContent(fotos);
            }
            company.addContent(familia);
        }
        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(new Document(company), new FileOutputStream(file));
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}