Example usage for org.dom4j.io XMLWriter close

List of usage examples for org.dom4j.io XMLWriter close

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying Writer

Usage

From source file:skoa.helpers.Acciones.java

License:Open Source License

/**
 * inserta iconos sobre el plano de una estancia, en el fichero xml, de 1 en 1
 * @param insertar/*w w w.j  a v a 2  s  .  c om*/
 * @param nombreIcono
 */
public static void insertaIconos(JLabel insertar, String nombreIcono, String planta, String estancia) {
    String x = Integer.toString(insertar.getX());
    String y = Integer.toString(insertar.getY());
    String ancho = Integer.toString(insertar.getWidth());
    String largo = Integer.toString(insertar.getHeight());
    String inombre = "";
    String idirgrup = "";
    String itipo = "";
    String isubtipo = "";

    try {

        // instancia del la clase File para leer el archivo xml
        File aFile = new File(NuevoProyecto.archivo);

        // instancia del la clase xmlReader para recorer el arbol del xml
        SAXReader xmlReader = new SAXReader();
        // xmlReader.setEncoding("UTF-8");
        xmlReader.setEncoding("iso-8859-1");

        // leemos un obtenemos el nodo raiz
        Document doc = xmlReader.read(aFile);

        // obtenemos el node vivienda
        Element node = (Element) doc.selectSingleNode("//vivienda");

        Element node2 = null;// (Element) doc.selectSingleNode(//
        // "//vivienda/planta");;
        Element node3 = null;
        //String aux;
        //String auxi;
        org.dom4j.Element modificar;

        // leemos el contador de nodo
        String cont = node.valueOf("@contador");
        int contador = Integer.parseInt(cont);
        contador++;

        String nuevoContador = Integer.toString(contador);
        while (nuevoContador.length() != 6) {
            nuevoContador = "0" + nuevoContador;
        }

        Attribute atributoc = node.attribute("contador");
        atributoc.setText(Integer.toString(contador));

        // recoremos los hijos dle nodo vivienda
        if (nombreIcono != null) {
            for (Iterator i = node.elementIterator(); i.hasNext();) {
                node = (Element) i.next();

                // si es la planta buscada
                if (node.getName().equals("planta") && node.valueOf("@alias").equals(planta)) {
                    node2 = node;
                    for (Iterator ia = node2.elementIterator(); ia.hasNext();) {
                        node2 = (Element) ia.next();

                        // estancia
                        if (node2.valueOf("@nombre").equals(estancia)) {
                            node3 = node2;

                            // recorremos el nodo para acceder a
                            // actuadores,sensores,iconos
                            for (Iterator ib = node3.elementIterator(); ib.hasNext();) {
                                node3 = (Element) ib.next();

                                if (node3.getName().equals("actuadores")) {

                                    String[] fieldsToInclude = { "regulacion", "conmutacion", "persianas",
                                            "electrovalvula" };

                                    for (String field : fieldsToInclude) {

                                        if (nombreIcono.equals(field)) {
                                            Attribute atributo = node3.attribute(field);
                                            atributo.setText("si");
                                        }
                                    }
                                } // end if actuadores y sensores

                                if (node3.getName().equals("iconos")) {
                                    String[] fieldsToInclude = { "regulacion", "conmutacion", "persianas",
                                            "electrovalvula", "puerta", "movimiento", "temperatura",
                                            "combinado", "inundacion", "contadores" };

                                    for (String field : fieldsToInclude) {
                                        if (nombreIcono.equals(field)) {
                                            for (MiFormato miFormato : DispositivoNuevo.parametros) {

                                                if ((miFormato.x.equals(x)) && (miFormato.y.equals(y))) {
                                                    inombre = miFormato.nombre;
                                                    idirgrup = miFormato.direccionGrupo;
                                                    itipo = miFormato.tipoEstructura;
                                                    isubtipo = miFormato.subtipo;
                                                }
                                            }

                                            org.dom4j.Element anadir = node3.addElement("label")
                                                    .addAttribute("tipo", field).addAttribute("x", x)
                                                    .addAttribute("y", y).addAttribute("ancho", ancho)
                                                    .addAttribute("largo", largo)
                                                    .addAttribute("id", nuevoContador) // Integer.toString(contador));
                                                    .addAttribute("direccionGrupo", idirgrup)
                                                    .addAttribute("tipoEstructura", itipo)
                                                    .addAttribute("subtipo", isubtipo);
                                            // anadir.addAttribute("nombred", inombre)

                                        }

                                    }
                                }

                                // iconos++++++++++++++++++++++++++++++++++++++++++++++++

                                if (node3.getName().equals("cantidad")) {
                                    String[][] fieldsToInclude = {
                                            new String[] { "regulacion", "@lucreg", "lucreg" },
                                            new String[] { "conmutacion", "@bombs", "bombs" },
                                            new String[] { "persianas", "@blinds", "blinds" },
                                            new String[] { "electrovalvula", "@valves", "valves" },
                                            new String[] { "puerta", "@doors", "doors" },
                                            new String[] { "movimiento", "@presencia", "presencia" }, };

                                    for (String[] field : fieldsToInclude) {

                                        if (nombreIcono.equals(field[0])) {
                                            String valor = node3.valueOf(field[1]);
                                            int numero = Integer.parseInt(valor) + 1;

                                            Attribute atributo = node3.attribute(field[2]);
                                            atributo.setText(Integer.toString(numero));
                                        }
                                    }
                                } // end if cantidad

                            } // end for node3
                        } // end if estancia==estancia seleccionada
                    } // end for node2
                } // end consulta si es la planta que busco
            } // end for
        }

        //String auxiliar = doc.asXML();
        //FileWriter archivo;
        //archivo = new FileWriter(principal.archivo);

        OutputFormat format = OutputFormat.createPrettyPrint();
        // format.setEncoding("UTF-8");
        format.setEncoding("iso-8859-1");

        // XMLWriter writer = new XMLWriter(new FileWriter(
        // principal.archivo ) );

        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

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

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

}

From source file:skoa.helpers.Acciones.java

License:Open Source License

/**
 * Metodo para inicializar a "no" los actuadores y sensores
 * @param nombrePlanta/*from   www . j a va 2 s. com*/
 * @param nombreEstancia
 */
public static void inicializarEstancia(String nombrePlanta, String nombreEstancia) {
    try {
        //referencia al archivo
        File aFile = new File(NuevoProyecto.archivo);

        //referencia para leer el arbol del xml
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");

        //cargamos el nodo raiz
        Document doc = xmlReader.read(aFile);
        Element node = (Element) doc.selectSingleNode("//vivienda");

        Element node2 = null;
        Element node3 = null;
        String aux;
        String auxi;

        //recorremos el nodo vivienda
        for (Iterator i = node.elementIterator(); i.hasNext();) {
            node = (Element) i.next();
            if (node.getName().equals("planta")) {
                aux = node.valueOf("@alias");

                if (aux.equals(nombrePlanta)) { // si es la planta que busco

                    node2 = node;

                    for (Iterator ia = node2.elementIterator(); ia.hasNext();) {
                        node2 = (Element) ia.next();
                        aux = node2.valueOf("@nombre");

                        // estancia_nueva.seleccionado;
                        auxi = nombreEstancia;

                        // si es la estancia que  busco
                        if (aux.equals(auxi)) {

                            org.dom4j.Element anadir2 = node2.addElement("actuadores")
                                    .addAttribute("regulacion", "no").addAttribute("conmutacion", "no")
                                    .addAttribute("persianas", "no").addAttribute("electrovalvula", "no");

                            org.dom4j.Element anadir3 = node2.addElement("sensores")
                                    .addAttribute("puerta", "no").addAttribute("movimiento", "no")
                                    .addAttribute("temperatura", "no").addAttribute("combinado", "no")
                                    .addAttribute("inundacion", "no").addAttribute("contadores", "no");

                            org.dom4j.Element anadir4 = node2.addElement("iconos");

                            org.dom4j.Element anadir5 = node2.addElement("cantidad").addAttribute("blinds", "0")
                                    .addAttribute("lucreg", "0").addAttribute("bombs", "0")
                                    .addAttribute("valves", "0").addAttribute("doors", "0")
                                    .addAttribute("presencia", "0");
                        } // end if si es la estancia que quiero
                    } // end for node2
                } // end if es la planta que busco
            } // end if si es una planta
        } // end for

        //String auxiliar = doc.asXML();
        //FileWriter archivo;
        //archivo = new FileWriter(principal.archivo);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");

        //actualizamos el archivo
        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

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

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

From source file:skoa.helpers.Acciones.java

License:Open Source License

/**
 * Metodo para eliminar una planta del xml
 * @param planta/*  w w w  .j a  v a2 s  . c o  m*/
 */
public static void eliminarPlantaXML(String planta) {
    try {

        //referencia para leer el archivo
        File aFile = new File(NuevoProyecto.archivo);

        //referencia para leer el arbol xml
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        //xmlReader.setEncoding("iso-8859-1");

        //cargamos la raiz
        Document doc = xmlReader.read(aFile);
        Element node = (Element) doc.selectSingleNode("//vivienda");

        //recorremos el arbol
        for (Iterator i = node.elementIterator(); i.hasNext();) {
            node = (Element) i.next();

            // si es la planta que busco
            System.out.println(node.valueOf("@alias") + " " + planta);
            if (node.getName().equals("planta") && node.valueOf("@alias").equals(planta)) {
                node.getParent().remove(node);

                // ++++++++++++++ MENSAJE ALERTA
                String mostrar = "Planta Eliminada";

                //muestro una ventana de notificacion
                JOptionPane.showMessageDialog(null, mostrar, "Informacin", 1);

            } // end if
        } // end for

        //String auxiliar = doc.asXML();
        //FileWriter archivo;
        //archivo = new FileWriter(principal.archivo);

        OutputFormat format = OutputFormat.createPrettyPrint();
        // format.setEncoding("UTF-8");
        format.setEncoding("iso-8859-1");

        //actualziamos el archivo
        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:skoa.helpers.Acciones.java

License:Open Source License

/**
 * Metodo que elimina una isntancia en el archvio xml
 * @param planta//from  ww w .j a va 2  s .c  om
 * @param estancia
 */
public static void eliminarEstanciaXML(String planta, String estancia) {
    try {

        //referencia para leer el archivo
        File aFile = new File(NuevoProyecto.archivo);

        //referencia para leer el arbol xml
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        //xmlReader.setEncoding("iso-8859-1");

        //cargamos la raiz
        Document doc = xmlReader.read(aFile);
        Element node = (Element) doc.selectSingleNode("//vivienda");
        Element node2;

        for (Iterator i = node.elementIterator(); i.hasNext();) {
            node = (Element) i.next();

            // si es la planta que busco
            if (node.getName().equals("planta") && node.valueOf("@alias").equals(planta)) {
                node2 = node;
                for (Iterator ia = node2.elementIterator(); ia.hasNext();) {
                    node2 = (Element) ia.next();

                    // estoy en la estancia buscada
                    if (node2.getName().equals("estancia") && node2.valueOf("@nombre").equals(estancia)) {
                        node2.getParent().remove(node2);
                        // ++++++++++++++ MENSAJE ALERTA
                        String mostrar = "Estancia Eliminada";
                        JOptionPane.showMessageDialog(null, mostrar, "Informacin", 1);
                    }
                } // end for2
            } // end if
        } // end for

        OutputFormat format = OutputFormat.createPrettyPrint();
        // format.setEncoding("UTF-8");
        format.setEncoding("iso-8859-1");

        //actualziamos el archivo
        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:skoa.helpers.Acciones.java

License:Open Source License

/**
 * Metodo que modifica en el xml // w ww.java  2 s .c om
 * la instacia selecionada en la vista ModificarPlano.planta_seleccionada
 */
public static void modificarPlanoXML() {
    try {
        //referencia para leer el archivo
        File aFile = new File(NuevoProyecto.archivo);

        //referencia para leer el arbol xml
        SAXReader xmlReader = new SAXReader();
        //xmlReader.setEncoding("UTF-8");
        xmlReader.setEncoding("iso-8859-1");

        //cargamos la raiz
        Document doc = xmlReader.read(aFile);
        Element node = (Element) doc.selectSingleNode("//vivienda");
        Element node2 = null;

        //recorremos el arbol
        for (Iterator i = node.elementIterator(); i.hasNext();) {
            node = (Element) i.next();
            if (node.getName().equals("planta")
                    && node.valueOf("@alias").equals(ModificarPlano.planta_seleccionada)) {
                node2 = node;
                for (Iterator ia = node2.elementIterator(); ia.hasNext();) {
                    node2 = (Element) ia.next();

                    if (node2.getName().equals("estancia")
                            && node2.valueOf("@nombre").equals(ModificarPlano.estancia_seleccionada)) {

                        Attribute atributo1 = node2.attribute("imagen");
                        atributo1.setText(ModificarPlano.direcPlano);

                    } // end if estancia
                } // end for node2
            } // end if planta
        } // end for node

        //volver a inicializar todas las cantidades a 0 y "no" en actuadores y sensores
        Acciones.inicializarEstancia(ModificarPlano.planta_seleccionada, ModificarPlano.estancia_seleccionada);

        ////String aux = doc.asXML();
        //FileWriter archivo;
        //archivo = new FileWriter(principal.archivo);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("iso-8859-1");
        //format.setEncoding("UTF-8");

        //actualziamos el archivo
        //XMLWriter writer = new XMLWriter(new FileWriter(principal.archivo));
        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:skoa.helpers.Acciones.java

License:Open Source License

/**
 * Metodo para inicializar los nodos dentro del arbol del xml
 * @param planta/*from  w w  w  .  ja v a  2s . com*/
 * @param estancia
 * @param tipo
 * @param doc
 * @throws IOException
 */
public static void inicializar(String planta, String estancia, String tipo, Document doc) throws IOException {
    try {

        //cargamos el nodo vivienda
        Element node = (Element) doc.selectSingleNode("//vivienda");
        Element node2, node3, node4 = null;

        int cero = 0;

        //recoremos sus hijos
        for (Iterator i = node.elementIterator(); i.hasNext();) {
            node = (Element) i.next();

            //si  es el nodo que estamos buscando
            if (node.getName().equals("planta") && node.valueOf("@alias").equals(planta)) {
                node2 = node;
                for (Iterator ia = node2.elementIterator(); ia.hasNext();) {
                    node2 = (Element) ia.next();

                    //si es la estancia que estamos buscando
                    if (node2.getName().equals("estancia") && node2.valueOf("@nombre").equals(estancia)) {
                        node3 = node2;

                        //recorremos sus hijos
                        for (Iterator ib = node3.elementIterator(); ib.hasNext();) {
                            node3 = (Element) ib.next();

                            if (node3.getName().equals("cantidad")) {
                                String[][] fieldsToInclude = {
                                        new String[] { "regulacion", "@lucreg", "lucreg" },
                                        new String[] { "conmutacion", "@bombs", "bombs" },
                                        new String[] { "persianas", "@blinds", "blinds" },
                                        new String[] { "electrovalvula", "@valves", "valves" },
                                        new String[] { "puerta", "@doors", "doors" },
                                        new String[] { "movimiento", "@presencia", "presencia" }, };

                                for (String[] field : fieldsToInclude) {
                                    if (tipo.equals(field[0])) {
                                        int cuantas = Integer.parseInt(node3.valueOf(field[1])) - 1;

                                        if (cuantas == 0) {
                                            cero = 1;
                                        }

                                        Attribute atributo1 = node3.attribute(field[2]);
                                        atributo1.setText(String.valueOf(cuantas));
                                    }
                                }
                            } // end if Cantidad

                        } // end for dentro estancias

                    }
                }
            }
        }

        OutputFormat format = OutputFormat.createPrettyPrint();
        // format.setEncoding("UTF-8");
        format.setEncoding("iso-8859-1");

        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

        // si el contador llego a 0 hay que poner NO en actuadores/sensores
        if (cero == 1) {
            inicializar2(planta, estancia, tipo);

        }

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

}

From source file:skoa.helpers.Acciones.java

License:Open Source License

/**
 * Inicializa los componente dentro del xml en "no"
 * @param planta/* w w w. j  a v a 2 s  .  com*/
 * @param estancia
 * @param tipo
 */
public static void inicializar2(String planta, String estancia, String tipo) {

    try {
        //referencia al archivo
        File aFile = new File(NuevoProyecto.archivo);

        //referencia para lerr el arbol xml
        SAXReader xmlReader = new SAXReader();
        // xmlReader.setEncoding("UTF-8");
        xmlReader.setEncoding("iso-8859-1");

        //cargamos la raiz
        Document doc = xmlReader.read(aFile);
        Element node = (Element) doc.selectSingleNode("//vivienda");
        Element node2, node3, node4 = null;

        String buscar = "";
        if (tipo.equals("regulacion") || tipo.equals("conmutacion") || tipo.equals("persianas")
                || tipo.equals("electrovalvula")) {
            buscar = "actuadores";

        }

        if (tipo.equals("puerta") || tipo.equals("movimiento") || tipo.equals("temperatura")
                || tipo.equals("combinado") || tipo.equals("inundacion") || tipo.equals("contadores")) {

            buscar = "sensores";

        }

        //recoremos el arbol
        for (Iterator i = node.elementIterator(); i.hasNext();) {
            node = (Element) i.next();

            if (node.getName().equals("planta") && node.valueOf("@alias").equals(planta)) {
                node2 = node;

                //recorremos el nodo estancia planta
                for (Iterator ia = node2.elementIterator(); ia.hasNext();) {
                    node2 = (Element) ia.next();

                    // dentro de la estancia que busco
                    if (node2.getName().equals("estancia") && node2.valueOf("@nombre").equals(estancia)) {
                        node3 = node2;

                        //recorremos el nodo estancia
                        for (Iterator ib = node3.elementIterator(); ib.hasNext();) {
                            node3 = (Element) ib.next();

                            // si es lo que estoy buscando (sensores/actuadores)
                            if (node3.getName().equals(buscar)) {
                                String[] fieldsToInclude = { "regulacion", "conmutacion", "persianas",
                                        "electrovalvula", "puerta", "movimiento", "temperatura", "combinado",
                                        "inundacion", "contadores" };

                                for (String field : fieldsToInclude) {

                                    if (tipo.equals("regulacion")) {
                                        Attribute atributo = node3.attribute(field);
                                        if (atributo != null)
                                            atributo.setText("no");
                                    }
                                }

                            } // end for dentro estancias
                        }
                    }
                }
            }
        } // end for

        OutputFormat format = OutputFormat.createPrettyPrint();
        // format.setEncoding("UTF-8");
        format.setEncoding("iso-8859-1");

        //actualizamos el xml
        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:skoa.views.EstanciaNueva.java

License:Open Source License

private static void navegar() {
    try {//from   w ww .  j ava  2 s.c o m
        File aFile = new File(NuevoProyecto.archivo);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        Document doc = xmlReader.read(aFile);
        Element node = (Element) doc.selectSingleNode("//vivienda");

        for (Iterator i = node.elementIterator(); i.hasNext();) {
            node = (Element) i.next();

            if (!node.getName().equals("email")) {

                if (node.valueOf("@alias").equals(EstanciaNueva.seleccionado)) {
                    //ESTEFAN?A: Aadido para que se coja la imagen del plano desde la carpeta
                    //donde est el ejecutable. Esto se hace para que no hayan rutas absolutas
                    //y si se cambia la carpeta de ejecutables de directorio, siga funcionando.
                    //SIEMPRE Y CUANDO, SE MANTENGA EL MISMO NOMBRE DE LA CARPETA DONDE SE SACARON
                    //LAS IM?GENES DE LOS PLANOS AL CREAR EL PROYECTO, Y EL MISMO NOMBRE DE LA
                    //IMAGEN.
                    File dir_iniciall = new File("./");
                    String a = dir_iniciall.getAbsolutePath();
                    System.out.println("raiz=" + a);
                    int ind = EstanciaNueva.imagen_e.indexOf(a);
                    int lon = a.length();
                    String b = EstanciaNueva.imagen_e.substring(ind + lon);
                    System.out.println("ruta relativa=" + b);
                    System.out.println("ruta absoluta=" + EstanciaNueva.imagen_e);
                    org.dom4j.Element anadir = node.addElement("estancia")
                            .addAttribute("nombre", EstanciaNueva.nombre_e) //.addAttribute("imagen", estancia_nueva.imagen_e)
                            .addAttribute("imagen", b);
                    break;
                } //end if auxi
            } //end if
        } //end for

        OutputFormat format = OutputFormat.createPrettyPrint();

        //format.setEncoding("UTF-8"); 
        format.setEncoding("iso-8859-1");

        XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
        writer.write(doc);
        writer.close();

        Acciones.inicializarEstancia(EstanciaNueva.seleccionado, EstanciaNueva.nombre_e);

    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }

}

From source file:skoa.views.ModificarEmail.java

License:Open Source License

public static void main() {
    llamado = 1;//from   w ww .jav a2  s.  co  m

    MOSTRAR_CONFIGURACION.setViewportView(Arbol.generarArbol());
    FRAME_MODIFICAR_EMAIL.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    FRAME_MODIFICAR_EMAIL.setTitle(resourceMap.getString("FRAME_MODIFICAR_PLANO.title"));
    FRAME_MODIFICAR_EMAIL.setResizable(true);
    FRAME_MODIFICAR_EMAIL.setSize(900, 600);
    FRAME_MODIFICAR_EMAIL.setLocation(120, 20);
    FRAME_MODIFICAR_EMAIL.addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent evt) {
            FRAME_MODIFICAR_EMAIL.setVisible(false);
            try {
                if (ConfiguracionProyecto.llamado == 0) {
                    ConfiguracionProyecto.main();
                } else {
                    ConfiguracionProyecto.FRAME_CONFIGURACION.setVisible(true);
                }

            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    ModificarEmail.email_envio.setSize(150, 20);
    ModificarEmail.email_envio.setText("");
    ModificarEmail.email_envio.addFocusListener(new FocusListener() {

        public void focusLost(FocusEvent e) {

            String aux = ((JTextField) e.getSource()).getText(); //lee texto escrito
            ModificarEmail.mail = aux;

        }//end focuslost

        public void focusGained(FocusEvent e) {
            // No hacemos nada
        }
    });

    JMenuBar jMenuBar1 = new javax.swing.JMenuBar();

    JMenu jMenuUsando = new javax.swing.JMenu();
    jMenuUsando.setText(resourceMap.getString("jMenuUsando.text") + NuevoProyecto.nombre_archivo);
    jMenuUsando.setEnabled(false);
    jMenuBar1.add(jMenuUsando);

    jMenuBar1.add(jMenuUsando);
    FRAME_MODIFICAR_EMAIL.setJMenuBar(jMenuBar1);

    //Solicitar email
    JLabel etiquetaModificarEmail = new JLabel();
    etiquetaModificarEmail.setText(resourceMap.getString("etiquetaModificarEmail.text"));

    JButton botonModificarEmail = new JButton(resourceMap.getString("botonModificarEmail.text"));
    botonModificarEmail.setSize(40, 20);
    botonModificarEmail.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            try {
                File f = new File(NuevoProyecto.archivo);

                if (!f.exists()) {
                    if (ModificarEmail.mail.length() != 0) {
                        Document documento = DocumentHelper.createDocument();
                        org.dom4j.Element root = documento.addElement("vivienda");

                        org.dom4j.Element email = root.addElement("email").addAttribute("direccion",
                                ModificarEmail.mail);
                        FileWriter archivo = new FileWriter(NuevoProyecto.archivo, true);
                        OutputFormat format = OutputFormat.createPrettyPrint();

                        //format.setEncoding("UTF-8");
                        format.setEncoding("iso-8859-1");

                        XMLWriter writer = new XMLWriter(archivo, format);

                        writer.write(documento);
                        writer.close();

                        String mostrar = "Se ha introducido su email";
                        mostrar += "\n";
                        mostrar += ModificarEmail.mail;
                        mostrar += "\n";
                        mostrar += "en el fichero de configuracin";
                        JOptionPane.showMessageDialog(null, mostrar, "Informacin", 1);

                        ModificarEmail.email_envio.setCaretPosition(0);
                        ModificarEmail.email_envio.setText("");

                        try {

                            File aFile = new File(NuevoProyecto.archivo);
                            SAXReader xmlReader = new SAXReader();
                            //xmlReader.setEncoding("UTF-8");
                            xmlReader.setEncoding("iso-8859-1");
                            Document doc = xmlReader.read(aFile);
                            Element node = (Element) doc.selectSingleNode("//vivienda/email");

                            ModificarEmail.nombreviv.setText(
                                    resourceMap.getString("etiquetaEmailActual.text") + ModificarEmail.mail);

                        } catch (DocumentException e1) {
                            e1.printStackTrace();
                        }

                    } else {
                        JOptionPane.showMessageDialog(null, resourceMap.getString("dialog.error.email.text"),
                                resourceMap.getString("dialog.error.title"), 1);
                    }
                } else {
                    navegar();

                } //end else

            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    });

    JSeparator jSeparatorV = new javax.swing.JSeparator();
    JSeparator jSeparatorH = new javax.swing.JSeparator();

    jSeparatorV.setOrientation(javax.swing.SwingConstants.VERTICAL);

    Label etiquetaArbol = new java.awt.Label();
    etiquetaArbol.setText(resourceMap.getString("etiquetaArbol.text"));

    try {

        File aFile = new File(NuevoProyecto.archivo);
        SAXReader xmlReader = new SAXReader();
        //xmlReader.setEncoding("UTF-8");
        xmlReader.setEncoding("iso-8859-1");
        Document doc = xmlReader.read(aFile);
        Element node = (Element) doc.selectSingleNode("//vivienda/email");

        nombreviv.setText(resourceMap.getString("etiquetaEmailActual.text") + node.valueOf("@direccion"));
        nombreviv.setSize(450, 30);

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

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
            ModificarEmail.FRAME_MODIFICAR_EMAIL.getContentPane());
    ModificarEmail.FRAME_MODIFICAR_EMAIL.getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addComponent(MOSTRAR_CONFIGURACION, javax.swing.GroupLayout.PREFERRED_SIZE,
                                            150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(2, 2, 2)) // .addComponent(scrollbar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jSeparatorH, javax.swing.GroupLayout.PREFERRED_SIZE, 135,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(5, 5, 5).addComponent(etiquetaArbol, javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(10, 10, 10)
                    .addComponent(jSeparatorV, javax.swing.GroupLayout.PREFERRED_SIZE, 27,
                            javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup().addGap(32, 32, 32)
                                    .addComponent(etiquetaModificarEmail).addGap(18, 18, 18)
                                    .addComponent(email_envio, javax.swing.GroupLayout.PREFERRED_SIZE, 150,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(botonModificarEmail))
                            .addGroup(layout.createSequentialGroup().addGap(50, 50, 50).addComponent(nombreviv,
                                    javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup().addGap(120, 120, 120) //.addComponent(boton2)
                    )).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparatorV, javax.swing.GroupLayout.Alignment.TRAILING,
                    javax.swing.GroupLayout.DEFAULT_SIZE, 8, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() //                  .addContainerGap()
                    .addGap(55, 55, 55)
                    .addComponent(etiquetaArbol, javax.swing.GroupLayout.PREFERRED_SIZE,
                            javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparatorH, javax.swing.GroupLayout.DEFAULT_SIZE, 7,
                            javax.swing.GroupLayout.DEFAULT_SIZE)
                    .addComponent(MOSTRAR_CONFIGURACION, javax.swing.GroupLayout.DEFAULT_SIZE, 450,
                            javax.swing.GroupLayout.DEFAULT_SIZE)
                    .addGap(175, 175, 175).addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() //                       .addGap(42, 42, 42)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(nombreviv, javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(55, 55, 55))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(etiquetaModificarEmail)
                            .addComponent(email_envio, javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(botonModificarEmail))
                    .addGap(42, 42, 42).addGap(475, 475, 475) //.addComponent(boton2)
    ));

    FRAME_MODIFICAR_EMAIL.setVisible(true);

}

From source file:skoa.views.ModificarEmail.java

License:Open Source License

private static void navegar() {
    try {//  www.ja  v  a  2s .  c  o m
        if (ModificarEmail.mail.length() != 0) {
            File aFile = new File(NuevoProyecto.archivo);
            SAXReader xmlReader = new SAXReader();

            //xmlReader.setEncoding("UTF-8");
            xmlReader.setEncoding("iso-8859-1");

            Document doc = xmlReader.read(aFile);

            Element node = (Element) doc.selectSingleNode("//vivienda/email");
            if (node == null) {
                node = (Element) doc.selectSingleNode("//vivienda");//[@nombre]" );
                org.dom4j.Element anadir = node.addElement("email");//( "plantas" );

                node = (Element) doc.selectSingleNode("//vivienda/email");
                anadir = node.addAttribute("direccion", ModificarEmail.mail);
                NuevoProyecto.email_fichero = ModificarEmail.mail;
            } //end if
            else {
                Attribute atributo = node.attribute("direccion");
                atributo.setText(ModificarEmail.mail);

            } //end else
            String aux = doc.asXML();
            FileWriter archivo;

            archivo = new FileWriter(NuevoProyecto.archivo);
            OutputFormat format = OutputFormat.createPrettyPrint();

            //format.setEncoding("UTF-8");
            format.setEncoding("iso-8859-1");

            XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo));
            writer.write(doc);
            writer.close();

            String mostrar = "Se ha introducido su email";
            mostrar += "\n";
            mostrar += ModificarEmail.mail;
            mostrar += "\n";
            mostrar += "en el fichero de configuracin";
            JOptionPane.showMessageDialog(null, mostrar, "Informacin", 1);

            try {

                File aFile1 = new File(NuevoProyecto.archivo);
                SAXReader xmlReader1 = new SAXReader();
                //xmlReader1.setEncoding("UTF-8");
                xmlReader1.setEncoding("iso-8859-1");
                Document doc1 = xmlReader1.read(aFile1);
                Element node1 = (Element) doc1.selectSingleNode("//vivienda/email");

                ModificarEmail.nombreviv.setText("E-mail de contacto Actual:       " + ModificarEmail.mail);

            } catch (DocumentException e1) {
                e1.printStackTrace();
            }
        } else {
            String mostrar2 = "Ha de introducir una direccin de email";
            JOptionPane.showMessageDialog(null, mostrar2, "Alerta", 1);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}