Example usage for org.jdom2.input SAXBuilder build

List of usage examples for org.jdom2.input SAXBuilder build

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder build.

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationFrowModuleImpl.java

License:Open Source License

private boolean prepareXMLAccess(ValidationContext validationContext)
        throws JDOMException, IOException, Exception {
    boolean successfullyCommitted = false;
    Properties properties = validationContext.getValidationProperties();
    File metadataXML = validationContext.getMetadataXML();
    InputStream inputStream = new FileInputStream(metadataXML);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(inputStream);
    // Assigning JDOM Document to the validation context
    validationContext.setMetadataXMLDocument(document);
    String xmlPrefix = properties.getProperty("module.f.metadata.xml.prefix");
    String xsdPrefix = properties.getProperty("module.f.table.xsd.prefix");
    // Setting the namespaces to access metadata.xml and the different
    // table.xsd//from  ww w .  ja  v  a2 s.com
    Element rootElement = document.getRootElement();
    String namespaceURI = rootElement.getNamespaceURI();
    Namespace xmlNamespace = Namespace.getNamespace(xmlPrefix, namespaceURI);
    Namespace xsdNamespace = Namespace.getNamespace(xsdPrefix, namespaceURI);
    // Assigning prefix to the validation context
    validationContext.setXmlPrefix(xmlPrefix);
    validationContext.setXsdPrefix(xsdPrefix);
    // Assigning namespace info to the validation context
    validationContext.setXmlNamespace(xmlNamespace);
    validationContext.setXsdNamespace(xsdNamespace);
    if (validationContext.getXmlNamespace() != null && validationContext.getXsdNamespace() != null
            && validationContext.getXmlPrefix() != null && validationContext.getXsdPrefix() != null
            && validationContext.getMetadataXMLDocument() != null
            && validationContext.getValidationProperties() != null) {
        this.setValidationContext(validationContext);
        successfullyCommitted = true;
    } else {
        successfullyCommitted = false;
        this.setValidationContext(null);
        throw new Exception();
    }
    return successfullyCommitted;
}

From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationFrowModuleImpl.java

License:Open Source License

private boolean prepareValidationData(ValidationContext validationContext)
        throws JDOMException, IOException, Exception {
    boolean successfullyCommitted = false;
    Properties properties = validationContext.getValidationProperties();
    // Gets the tables to be validated
    List<SiardTable> siardTables = new ArrayList<SiardTable>();
    Document document = validationContext.getMetadataXMLDocument();
    Element rootElement = document.getRootElement();
    String workingDirectory = validationContext.getConfigurationService().getPathToWorkDir();
    String siardSchemasElementsName = properties.getProperty("module.f.siard.metadata.xml.schemas.name");
    // Gets the list of <schemas> elements from metadata.xml
    List<Element> siardSchemasElements = rootElement.getChildren(siardSchemasElementsName,
            validationContext.getXmlNamespace());
    for (Element siardSchemasElement : siardSchemasElements) {
        // Gets the list of <schema> elements from metadata.xml
        List<Element> siardSchemaElements = siardSchemasElement.getChildren(
                properties.getProperty("module.f.siard.metadata.xml.schema.name"),
                validationContext.getXmlNamespace());
        // Iterating over all <schema> elements
        for (Element siardSchemaElement : siardSchemaElements) {
            String schemaFolderName = siardSchemaElement
                    .getChild(properties.getProperty("module.f.siard.metadata.xml.schema.folder.name"),
                            validationContext.getXmlNamespace())
                    .getValue();//  w  w w.j av a 2 s .  com
            Element siardTablesElement = siardSchemaElement.getChild(
                    properties.getProperty("module.f.siard.metadata.xml.tables.name"),
                    validationContext.getXmlNamespace());
            List<Element> siardTableElements = siardTablesElement.getChildren(
                    properties.getProperty("module.f.siard.metadata.xml.table.name"),
                    validationContext.getXmlNamespace());
            // Iterating over all containing table elements
            for (Element siardTableElement : siardTableElements) {
                Element siardColumnsElement = siardTableElement.getChild(
                        properties.getProperty("module.f.siard.metadata.xml.columns.name"),
                        validationContext.getXmlNamespace());
                List<Element> siardColumnElements = siardColumnsElement.getChildren(
                        properties.getProperty("module.f.siard.metadata.xml.column.name"),
                        validationContext.getXmlNamespace());
                String tableName = siardTableElement
                        .getChild(properties.getProperty("module.f.siard.metadata.xml.table.folder.name"),
                                validationContext.getXmlNamespace())
                        .getValue();
                SiardTable siardTable = new SiardTable();
                // Add Table Root Element
                siardTable.setTableRootElement(siardTableElement);
                siardTable.setMetadataXMLElements(siardColumnElements);
                siardTable.setTableName(tableName);
                String siardTableFolderName = siardTableElement
                        .getChild(properties.getProperty("module.f.siard.metadata.xml.table.folder.name"),
                                validationContext.getXmlNamespace())
                        .getValue();
                StringBuilder pathToTableSchema = new StringBuilder();
                // Preparing access to the according XML schema file
                pathToTableSchema.append(workingDirectory);
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(properties.getProperty("module.f.siard.path.to.content"));
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(schemaFolderName.replaceAll(" ", ""));
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(siardTableFolderName.replaceAll(" ", ""));
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(siardTableFolderName.replaceAll(" ", ""));
                pathToTableSchema.append(properties.getProperty("module.f.siard.table.xsd.file.extension"));
                // Retrieve the according XML schema
                File tableSchema = validationContext.getSiardFiles().get(pathToTableSchema.toString());

                // --> Hier
                StringBuilder pathToTableXML = new StringBuilder();
                pathToTableXML.append(workingDirectory);
                pathToTableXML.append(File.separator);
                pathToTableXML.append(properties.getProperty("module.f.siard.path.to.content"));
                pathToTableXML.append(File.separator);
                pathToTableXML.append(schemaFolderName.replaceAll(" ", ""));
                pathToTableXML.append(File.separator);
                pathToTableXML.append(siardTableFolderName.replaceAll(" ", ""));
                pathToTableXML.append(File.separator);
                pathToTableXML.append(siardTableFolderName.replaceAll(" ", ""));
                pathToTableXML.append(properties.getProperty("module.f.siard.table.xml.file.extension"));
                File tableXML = validationContext.getSiardFiles().get(pathToTableXML.toString());

                SAXBuilder schemaBuilder = new SAXBuilder();
                Document tableSchemaDocument = schemaBuilder.build(tableSchema);
                Element tableSchemaRootElement = tableSchemaDocument.getRootElement();

                // Getting the tags from XML schema to be validated

                siardTable.setTableXSDRootElement(tableSchemaRootElement);

                SAXBuilder xmlBuilder = new SAXBuilder();
                Document tableXMLDocument = xmlBuilder.build(tableXML);
                Element tableXMLRootElement = tableXMLDocument.getRootElement();
                Namespace xMLNamespace = tableXMLRootElement.getNamespace();
                List<Element> tableXMLElements = tableXMLRootElement.getChildren(
                        properties.getProperty("module.f.siard.table.xml.row.element.name"), xMLNamespace);
                siardTable.setTableXMLElements(tableXMLElements);
                siardTables.add(siardTable);
                // Writing back the List off all SIARD tables to the
                // validation context
                validationContext.setSiardTables(siardTables);
            }
        }
    }
    if (validationContext.getSiardTables().size() > 0) {
        this.setValidationContext(validationContext);
        successfullyCommitted = true;
    } else {
        this.setValidationContext(null);
        successfullyCommitted = false;
        throw new Exception();
    }
    return successfullyCommitted;
}

From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationGtableModuleImpl.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   w ww .j a  va 2  s.  c  o  m*/
public boolean validate(File siardDatei) throws ValidationGtableException {
    boolean valid = true;
    try {
        /*
         * Extract the metadata.xml from the temporare work folder and build
         * a jdom document
         */

        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        /*
         * Nicht vergessen in
         * "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property
         * name="configurationService" ref="configurationService" />
         */
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());

        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        // declare ArrayLists
        List listSchemas = new ArrayList();
        List listTables = new ArrayList();
        List listColumns = new ArrayList();

        /*
         * read the document and for each schema and table entry verify
         * existence in temporary extracted structure
         */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");

        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            String schemaName = schema.getChild("name", ns).getText();

            String lsSch = (new StringBuilder().append(schemaName).toString());

            // select table elements and loop
            List<Element> tables = schema.getChild("tables", ns).getChildren("table", ns);
            for (Element table : tables) {
                String tableName = table.getChild("name", ns).getText();

                // Concatenate schema and table
                String lsTab = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                        .toString());

                // select column elements and loop
                List<Element> columns = table.getChild("columns", ns).getChildren("column", ns);
                for (Element column : columns) {
                    String columnName = column.getChild("name", ns).getText();

                    // Concatenate schema, table and column
                    String lsCol = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                            .append(" / ").append(columnName).toString());
                    listColumns.add(lsCol); // concatenating Strings
                }
                listTables.add(lsTab); // concatenating Strings (table
                // names)
            }
            listSchemas.add(lsSch); // concatenating Strings (schema
            // names)
        }
        HashSet hashSchemas = new HashSet(); // check for duplicate schemas
        for (Object value : listSchemas)
            if (!hashSchemas.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                        + getTextResourceService().getText(MESSAGE_DASHES)
                        + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_SCHEMA, value));
            }
        HashSet hashTables = new HashSet(); // check for duplicate tables
        for (Object value : listTables)
            if (!hashTables.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                        + getTextResourceService().getText(MESSAGE_DASHES)
                        + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_TABLE, value));
            }
        HashSet hashColumns = new HashSet(); // check for duplicate columns
        for (Object value : listColumns)
            if (!hashColumns.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                        + getTextResourceService().getText(MESSAGE_DASHES)
                        + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_COLUMN, value));
            }

    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                + getTextResourceService().getText(MESSAGE_DASHES) + "IOException " + ioe.getMessage());

    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                + getTextResourceService().getText(MESSAGE_DASHES) + "JDOMException " + e.getMessage());
        return valid;
    }
    return valid;
}

From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationHcontentModuleImpl.java

License:Open Source License

@Override
public boolean validate(File siardDatei) throws ValidationHcontentException {
    boolean valid = true;
    try {//from ww  w. jav  a  2  s  .  c o m
        /*
         * Extract the metadata.xml from the temporary work folder and build
         * a jdom document
         */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /*
         * read the document and for each schema and table entry verify
         * existence in temporary extracted structure
         */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            Element schemaFolder = schema.getChild("folder", ns);
            File schemaPath = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("content")
                    .append(File.separator).append(schemaFolder.getText()).toString());
            if (schemaPath.isDirectory()) {
                Element[] tables = schema.getChild("tables", ns).getChildren("table", ns)
                        .toArray(new Element[0]);
                for (Element table : tables) {
                    Element tableFolder = table.getChild("folder", ns);
                    File tablePath = new File(new StringBuilder(schemaPath.getAbsolutePath())
                            .append(File.separator).append(tableFolder.getText()).toString());
                    if (tablePath.isDirectory()) {
                        File tableXml = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xml").toString());
                        File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xsd").toString());
                        if (verifyRowCount(tableXml, tableXsd)) {

                            valid = validate(tableXml, tableXsd) && valid;
                        }
                    }
                }
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_H)
                + getTextResourceService().getText(MESSAGE_DASHES) + "IOException " + ioe.getMessage());
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_H)
                + getTextResourceService().getText(MESSAGE_DASHES) + "JDOMException " + e.getMessage());
    } catch (SAXException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_H)
                + getTextResourceService().getText(MESSAGE_DASHES) + "SAXException " + e.getMessage());
    }

    return valid;
}

From source file:ch.rotscher.maven.plugins.InstallWithVersionOverrideMojo.java

License:Apache License

private void replaceVersion(File originalPomFile, File newPomFile, String newVersion)
        throws IOException, JDOMException {

    //we assume that the version of "internal" dependencies are declared with ${project.version}
    FileWriter writer = new FileWriter(newPomFile);
    SAXBuilder parser = new SAXBuilder();
    XMLOutputter xmlOutput = new XMLOutputter();
    // display nice nice
    xmlOutput.setFormat(Format.getPrettyFormat());

    //parse the document
    Document doc = parser.build(originalPomFile);
    Element versionElem = findVersionElement(doc);
    versionElem.setText(newVersion);/*  w w  w .j a v a  2s.  co  m*/
    xmlOutput.output(doc, writer);
    writer.flush();
    writer.close();
}

From source file:ch.unifr.diuf.diva.did.Script.java

License:Open Source License

/**
 * Loads an XML script//from   w  w w  . j a v a 2 s .co m
 * @param fname file name of the script
 * @throws JDOMException if the XML is not correctly formated
 * @throws IOException if there is a problem to read the XML
 */
public Script(String fname) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Document xml = builder.build(new File(fname));
    root = xml.getRootElement();
    scriptName = fname;

    addCommand("image", new ImageCreator(this));
    addCommand("alias", new Alias(this));
    addCommand("print", new TextPrinter(this));
    addCommand("apply-fade", new FadeGradients(this));
    addCommand("gradient-degradations", new NoiseGradients(this));
    addCommand("manual-gradient-degradations", new ManualGradientModification(this));
    addCommand("apply-mix", new MixImages(this));
    addCommand("save", new SaveImage(this));
    addCommand("delete", new DeleteImage(this));
    addCommand("pepper-salt", new PepperSalt(this));
    addCommand("gaussian-noise", new GaussianNoise(this));
    addCommand("selective-blur", new SelectiveBlur(this));
    addCommand("selective-hv-blur", new SelectiveHVBlur(this));
    addCommand("calc", new Calc(this));
    addCommand("result", new Result(this));
    addCommand("square-dist", new SquareDiff(this));
    addCommand("abs-dist", new AbsDiff(this));
    addCommand("gradient-diff", new CompareOrientations(this));
    addCommand("co-occurences", new CoOcMatrix(this));
    addCommand("non-null-mean", new NonNullMean(this));
    addCommand("variance", new Variance(this));
    addCommand("correlation", new Correlation(this));
    addCommand("scaled-difference", new ScaledDifference(this));
    addCommand("scale-offset-ind-dist", new ScaleOffsetInvDist(this));
    addCommand("decrease-max-contrast", new DecreaseMaxContrast(this));
}

From source file:Codigo.XMLReader.java

/**
 * Metodo utilizado para cargar todos los estadios del mundial Brasil 2014
 * desde un documento XML que contiene informacion de cada uno de ellos
 * @return Lista con los estadios del mundial
 *//*from   w ww  .  j ava 2s  .  co  m*/
public ListaEstadios cargarListaDeEstadios() {

    // Se crea la lista con los estadios que se va a retornar
    ListaEstadios listaEstadios = new ListaEstadios();
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    try {
        File xmlFile = new File(getClass().getResource("/XML/Estadios.xml").toURI());
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'tables'
        Element raizXML = document.getRootElement();
        //Se obtiene la lista de hijos de la raiz 'Estadios'
        List list = raizXML.getChildren("Estadio");

        //Se recorre la lista de hijos de 'tables'
        for (int i = 0; i < list.size(); i++) {
            //Se obtiene el elemento 'Estadio'
            Element estadio = (Element) list.get(i);

            //Se obtiene el valor que esta entre los tags '<Nombre></Nombre>'
            String nombreEstadio = estadio.getChildText("Nombre");
            //Se obtiene el valor que esta entre los tags '<Ciudad></Ciudad>'
            String ciudadEstadio = estadio.getChildText("Ciudad");
            //Se obtiene el valor que esta entre los tags '<Capacidad></Capacidad>'
            int capacidadEstadio = Integer.parseInt(estadio.getChildTextTrim("Capacidad"));

            // Se crea un NodoEstadio con la informacion del estadio.
            NodoEstadio nuevoEstadio = new NodoEstadio(nombreEstadio, ciudadEstadio, capacidadEstadio);
            // Se inserta el nuevo estadio en la lista de estadios
            listaEstadios.insertarAlFinal(nuevoEstadio);
        }
        return listaEstadios;

    } catch (IOException | JDOMException | URISyntaxException io) {
        System.out.println(io.getMessage());
        return null;
    }
}

From source file:Codigo.XMLReader.java

/**
 * Metodo utilizado para cargar del XML la lisa de equipos que participan
 * en el mundial// ww w  .  j  ava 2 s. c  o  m
 * @return Lista con los equipos participantes
 */
public ListaEquipos cargarListaEquipos() {

    // Se crea la lista con los equipos que se va a retornar
    ListaEquipos listaEquipos = new ListaEquipos();
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    try {
        File xmlFile = new File(getClass().getResource("/XML/Equipos.xml").toURI());
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'Equipos'
        Element raizXML = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'Equipos' (Todos los equipos del mundial)
        List listEquipos = raizXML.getChildren("Equipo");

        //Se recorre la lista de hijos de 'Equipos'
        for (int i = 0; i < listEquipos.size(); i++) {
            //Se obtiene el elemento 'equipo'
            Element equipo = (Element) listEquipos.get(i);
            // Se obtienen los datos del equipo actual
            String nombreEquipo = equipo.getChildText("Nombre");
            String nombreEntrenador = equipo.getChildText("Entrenador");
            int partidosJugados = Integer.parseInt(equipo.getChildTextTrim("PartidosJugados"));
            int partidosGanados = Integer.parseInt(equipo.getChildTextTrim("PartidosGanados"));
            int partidosEmpatados = Integer.parseInt(equipo.getChildTextTrim("PartidosEmpatados"));
            int partidosPerdidos = Integer.parseInt(equipo.getChildTextTrim("PartidosPerdidos"));
            int golesAFavor = Integer.parseInt(equipo.getChildTextTrim("GolesAFavor"));
            int golesEnContra = Integer.parseInt(equipo.getChildTextTrim("GolesEnContra"));
            int golDiferencia = Integer.parseInt(equipo.getChildTextTrim("GolDiferencia"));
            int puntos = Integer.parseInt(equipo.getChildTextTrim("Puntos"));
            // Se obtiene la lista de jugadores con su informacion del XML
            List listJugadores = equipo.getChild("Jugadores").getChildren("Jugador");

            // Se crea la lista de jugadores que va a contener el equipo actual
            ListaJugadores jugadores = new ListaJugadores();

            // Se recorre la lista de jugadores
            for (int j = 0; j < listJugadores.size(); j++) {
                // Se obtiene el jugador 'j' de la lista de Jugadores
                Element jugador = (Element) listJugadores.get(j);
                // Se obtienen los datos del jugador 'j'
                String nombreJugador = jugador.getChildText("Nombre");
                int numeroCamiseta = Integer.parseInt(jugador.getChildTextTrim("NumeroCamiseta"));
                String posicion = jugador.getChildTextTrim("Posicion");
                int edad = Integer.parseInt(jugador.getChildTextTrim("Edad"));
                int estatura = Integer.parseInt(jugador.getChildTextTrim("Estatura"));
                int goles = Integer.parseInt(jugador.getChildTextTrim("Goles"));

                //Se crea un nuevo NodoJugador donde se va a almacenar el jugador
                NodoJugador jugadorNuevo = new NodoJugador(nombreJugador, posicion, edad, estatura,
                        numeroCamiseta, goles);

                // Se inserta el nuevo NodoJugador en la lista de jugadores
                jugadores.insertarOrdenadoPorEdad(jugadorNuevo);
            }

            // Se crea un nuevo NodoEquipo que almacena la informacion del equipo actual
            NodoEquipo equipoActual = new NodoEquipo(nombreEquipo, nombreEntrenador, jugadores, partidosJugados,
                    partidosGanados, partidosEmpatados, partidosPerdidos, golesAFavor, golesEnContra,
                    golDiferencia, puntos);

            // Se inserta el NodoEquipo actual en la lista de equipos
            listaEquipos.insertarOrdenado(equipoActual);
        }
        // Retorna la lista de todos los equipos
        return listaEquipos;

    } catch (IOException | JDOMException | URISyntaxException io) {
        System.out.println(io.getMessage());
        return null;
    }
}

From source file:Codigo.XMLReader.java

/**
 * Metodo utilizado para crear los grupos del mundial con la informacion de todos
 * los encuentros por grupo//from   www  .  j a  v a  2  s.  c om
 * @param pEquipos equipos participantes del mundial
 * @param pEstadios estadio del mundial
 * @return lista de los grupos del mundial
 */
public ListaGrupos cargarCalendarioYGrupos(ListaEquipos pEquipos, ListaEstadios pEstadios) {

    // Formato que se va a establecer en la creacion de cada fecha
    SimpleDateFormat formatoFecha = new SimpleDateFormat("d/M/yy h:mm a");
    // Se crea la lista de los Grupos del mundial, que se va a retornar
    ListaGrupos listaDeGrupos = new ListaGrupos();
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    try {
        File xmlFile = new File(getClass().getResource("/XML/CalendarioGrupos.xml").toURI());
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'Grupos'
        Element raizXML = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'Grupos' (Todos los grupos del mundial)
        List listaGruposXML = raizXML.getChildren("Grupo");

        // RECORRE LA LISTA DE GRUPOS DEL MUNDIAL
        for (int i = 0; i < listaGruposXML.size(); i++) {
            //Se obtiene el elemento 'Grupo' en la posicion i de la lista
            Element grupo = (Element) listaGruposXML.get(i);

            // Obtengo el atributo con la letra del grupo
            char letraDelGrupo = grupo.getAttributeValue("letra").charAt(0);

            // Se obtine la lista de los equipos que conforma el grupo
            List selecciones = grupo.getChild("Equipos").getChildren("Equipo");
            // Se crea un arreglo que almacenara las selecciones integrantes
            NodoEquipo[] equiposDelGrupo = new NodoEquipo[selecciones.size()];
            // RECORRE LA LISTA DE EQUIPOS PERTENECIENTES A ESTE GRUPO
            for (int j = 0; j < selecciones.size(); j++) {
                Element equipo = (Element) selecciones.get(j);
                // Obtiene el nombre del equipo 'j'
                NodoEquipo nombreDelEquipo = pEquipos.getNodoEquipo(equipo.getText());
                // Inserta nombre del equipo, en el arreglo de equiposDelGrupo
                equiposDelGrupo[j] = nombreDelEquipo;
            }

            // SE CREA LA LISTA QUE ALMACENARA LOS ENCUENTROS DEL GRUPO                
            ListaCalendario calendarioDelGrupo = new ListaCalendario();
            // Se obtiene la lista de todo los Encuentros correspondientes al grupo
            List listaDeEncuentros = grupo.getChild("Encuentros").getChildren("Partido");
            // RECORRE LA LISTA DE PARTIDOS CORRESPONDIENTES A LOS EQUIPOS DEL GRUPO ACTUAL
            for (int j = 0; j < listaDeEncuentros.size(); j++) {
                Element partido = (Element) listaDeEncuentros.get(j);

                // Obtiene los datos de fecha y hora del encuentro
                String fechaDelPartido = partido.getChildText("Fecha");
                String horaDelPartido = partido.getChildText("Hora");
                Date fechaYHora = formatoFecha.parse(fechaDelPartido + " " + horaDelPartido);

                // Obtiene los datos de condiciones climaticas del encuentro
                String humedad = partido.getChildText("Humedad");
                String velocidadViento = partido.getChildText("VelocidadViento");
                String temperatura = partido.getChildText("Temperatura");
                String condicionClimatica = partido.getChildText("CondicionClimatica");

                // Obtiene el estadio sede del encuentro
                String nombreEstadioSede = partido.getChildText("Sede");
                NodoEstadio estadioSede = pEstadios.getNodoEstadio(nombreEstadioSede);

                // Obtiene los equipos casa y visita que se enfrentan en el encuentro
                String nombreEquipoCasa = partido.getChildText("EquipoCasa");
                NodoEquipo equipoCasa = pEquipos.getNodoEquipo(nombreEquipoCasa);
                String nombreEquipoVisita = partido.getChildText("EquipoVisita");
                NodoEquipo equipoVisita = pEquipos.getNodoEquipo(nombreEquipoVisita);

                // Obtiene la cantidad de goles por equipo, en el encuentro
                int golesCasa = Integer.parseInt(partido.getChild("GolesCasa").getAttributeValue("goles"));
                String anotadoresCasa = "";
                int golesVisita = Integer.parseInt(partido.getChild("GolesVisita").getAttributeValue("goles"));
                String anotadoresVisita = "";

                // COMPRUEBA SI HUBIERON ANOTACIONES, DE LOS LOCALES, PARA OBTENER LOS ANOTADORES
                if (golesCasa > 0) {
                    List anotadores = partido.getChild("GolesCasa").getChild("Anotadores")
                            .getChildren("Anotador");
                    // RECORRE LA LISTA PARA OBTENER LOS ANOTADORES Y EL MINUTO DEL GOL
                    for (int k = 0; k < anotadores.size(); k++) {
                        Element anotador = (Element) anotadores.get(k);
                        // OBTENGO LOS DATOS DEL ANOTADOR 'k'
                        String nombre = anotador.getChildText("Nombre");
                        String minuto = anotador.getChildText("Minuto");
                        if (k < (anotadores.size() - 1)) {
                            anotadoresCasa += minuto + '\'' + "  " + nombre + '\n';
                        } else {
                            anotadoresCasa += minuto + '\'' + "  " + nombre;
                        }
                    }
                }
                // COMPRUEBA SI HUBIERON ANOTACIONES, DE LA VISITA, PARA OBTENER LOS ANOTADORES
                if (golesVisita > 0) {
                    List anotadores = partido.getChild("GolesVisita").getChild("Anotadores")
                            .getChildren("Anotador");
                    // RECORRE LA LISTA PARA OBTENER LOS ANOTADORES Y EL MINUTO DEL GOL
                    for (int k = 0; k < anotadores.size(); k++) {
                        Element anotador = (Element) anotadores.get(k);
                        // OBTENGO LOS DATOS DEL ANOTADOR 'k'
                        String nombre = anotador.getChildText("Nombre");
                        String minuto = anotador.getChildText("Minuto");
                        if (k < (anotadores.size() - 1)) {
                            anotadoresVisita += minuto + '\'' + "  " + nombre + '\n';
                        } else {
                            anotadoresVisita += minuto + '\'' + "  " + nombre;
                        }
                    }
                }
                // Crea un nuevo nodo Encuentro y lo inserta en la lista de Calendario
                NodoEncuentro encuentro = new NodoEncuentro(fechaYHora, humedad, velocidadViento, temperatura,
                        estadioSede, equipoCasa, equipoVisita, golesCasa, golesVisita, anotadoresCasa,
                        anotadoresVisita, condicionClimatica);

                // Inserta el nuevo nodo en la lista de Encuentros
                calendarioDelGrupo.insertarOrdenadoPorFecha(encuentro);
            }
            // Crea un nodo Grupo con toda la informacion del grupo actual
            NodoGrupo grupoDelMundial = new NodoGrupo(letraDelGrupo, equiposDelGrupo, calendarioDelGrupo);
            // Inserta el grupo a la lista de grupos
            listaDeGrupos.insertarOrdenado(grupoDelMundial);
        }
        // Retorna la lista de todos los equipos
        return listaDeGrupos;

    } catch (IOException | JDOMException | URISyntaxException | ParseException io) {
        System.out.println(io.getMessage());
        return null;
    }
}

From source file:codigoFonte.Sistema.java

public boolean addUser(User u) throws IOException {

    boolean success = false, matriculaExists = false;
    File file = new File("Sistema.xml");
    Document newDocument = null;//from w  ww  . j ava 2  s  .c  o  m
    Element root = null;
    Attribute matricula = null, nome = null, tipo = null, senha = null;
    Element user = null;

    if (u.getTipo().isEmpty() || u.getTipo().isEmpty() || u.getPassword().isEmpty()) {
        return success;
    }

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    } else {
        root = new Element("sistema");

        newDocument = new Document(root);
    }

    if (root.getChildren().size() > 0) {
        List<Element> listUsers = root.getChildren();
        for (Element a : listUsers) {
            if (a.getAttributeValue("matrcula").equals(u.getMatricula())) {
                matriculaExists = true;
            }
        }
    }

    if (!matriculaExists) {
        user = new Element("user");

        matricula = new Attribute("matrcula", this.newId());
        tipo = new Attribute("tipo", u.getTipo());
        nome = new Attribute("nome", u.getNome());
        senha = new Attribute("senha", u.getPassword());

        user.setAttribute(matricula);
        user.setAttribute(nome);
        user.setAttribute(tipo);
        user.setAttribute(senha);
        //user.setAttribute(divida);

        root.addContent(user);

        success = true;
    }
    //        

    XMLOutputter out = new XMLOutputter();

    try {
        FileWriter arquivo = new FileWriter(file);
        out.output(newDocument, arquivo);
    } catch (IOException ex) {
        Logger.getLogger(Sistema.class.getName()).log(Level.SEVERE, null, ex);
    }

    return success;
}