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:Api.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w  . ja  va  2 s  . c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("Content-Type: text/javascript");
    PrintWriter out = response.getWriter();

    // Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("Config.xml");

    try {
        //Se parcea el archivo xml para crear el documento 
        //que se va a tratar.
        Document documento = (Document) builder.build(xmlFile);
        // Se obtiene la raiz del documento. En este caso 'cruisecontrol'
        Element rootNode = documento.getRootElement();

        //            // Obtengo el tag "info" como nodo raiz para poder trabajar 
        //            // los tags de ste.
        //            Element rootNode_Level2 = rootNode.getChild("info");
        //            // Obtengo los nodos "property" del tag info y los almaceno en
        //            // una lista.
        //            List<Element> lista = rootNode_Level2.getChildren("property");
        //
        //            //Imprimo por consola la lista.
        //            for (int i = 0; i < lista.size(); i++) {
        //                System.out.println(((Element) lista.get(i)).getAttributeValue("value"));
        //            }
        // out.println("<!DOCTYPE html>");
        Map<String, Object> actions = new LinkedHashMap<String, Object>();

        for (Element action : rootNode.getChildren()) {

            ArrayList<Map> methods = new ArrayList<Map>();

            for (Element method : action.getChildren()) {

                Map<String, Object> md = new LinkedHashMap<String, Object>();

                if (method.getAttribute("len") != null) {

                    md.put("name", method.getName());
                    md.put("len", method.getAttributeValue("len"));

                } else {

                    md.put("name", method.getName());
                    md.put("params", method.getAttributeValue("params"));

                }

                if (method.getAttribute("formHandler") != null && method.getAttribute("formHandler") != null) {

                    md.put("formHandler", true);

                }

                methods.add(md);
            }

            actions.put(action.getName(), methods);
        }

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    } finally {
        out.close();
    }

}

From source file:AL_gui.java

License:Apache License

public void loadFile(String pathname, String filename) {

    try {/*from   www  .  j a  va 2 s . co  m*/
        // Build & creat the document with SAX, use XML schema validation
        URL path = ClassLoader.getSystemResource("ANNeML.xsd");
        if (path.getFile() == null) {
            jLabel2.setForeground(Color.RED);
            jLabel2.setText("error loading XML schema");
        } else {
            //File argylexsd = new File(path.toURI());
            //XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory(argylexsd);
            XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory("ANNeML.xsd"); //***for .jar deployment
            SAXBuilder builder = new SAXBuilder(schemafac);
            AL_gui.NNetMap = builder.build(pathname);
            java.util.List subnets = XPath.newInstance("//SUBNET").selectNodes(AL_gui.NNetMap);
            java.util.List layers = XPath.newInstance("//LAYER").selectNodes(AL_gui.NNetMap);
            java.util.List inputNeurodes = XPath.newInstance("//NEURODE[SYNAPSE/@ORG_NEURODE='INPUT']")
                    .selectNodes(AL_gui.NNetMap);
            java.util.List hiddenNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                    .selectNodes(AL_gui.NNetMap);
            java.util.List outputNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='OUTPUT']/NEURODE")
                    .selectNodes(AL_gui.NNetMap);
            jLabel2.setForeground(Color.GREEN);
            jLabel2.setText("Valid ANNeML file.");
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(AL_gui.this, "There was an error parsing the file.\n" + e.toString(),
                "Warning", JOptionPane.WARNING_MESSAGE);
    }

}

From source file:Erudite_gui.java

License:Apache License

public void loadFile(String pathname, String filename) {
    jLabel6.setEnabled(true);/*from   ww  w  .j av  a2s  .  co m*/
    jLabel7.setEnabled(true);
    jButton3.setEnabled(true);
    jButton4.setEnabled(true);
    jCheckBox1.setSelected(false);
    jCheckBox1.setEnabled(true);
    jEditorPane1.setEnabled(true);
    DefaultTableModel tblmodel = (DefaultTableModel) jTable2.getModel();
    tblmodel.setRowCount(0);

    try {
        // Build & creat the document with SAX, use XML schema validation
        URL path = ClassLoader.getSystemResource("ANNeML.xsd");
        if (path.getFile() == null) {
            jLabel2.setForeground(Color.RED);
            jLabel2.setText("error loading XML schema");
        } else {
            //File argylexsd = new File(path.toURI());
            //XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory(argylexsd);
            XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory("ANNeML.xsd"); //***for .jar deployment
            SAXBuilder builder = new SAXBuilder(schemafac);
            Erudite_gui.NNetMap = builder.build(pathname);
            JDOMToTreeModelAdapter model = new JDOMToTreeModelAdapter(Erudite_gui.NNetMap);
            XMLTreeCellRenderer renderer = new XMLTreeCellRenderer();
            jTree1.setCellRenderer(renderer);
            jTree1.setModel(model);
            java.util.List subnets = XPath.newInstance("//SUBNET").selectNodes(Erudite_gui.NNetMap);
            java.util.List layers = XPath.newInstance("//LAYER").selectNodes(Erudite_gui.NNetMap);
            java.util.List inputNeurodes = XPath.newInstance("//NEURODE[SYNAPSE/@ORG_NEURODE='INPUT']")
                    .selectNodes(Erudite_gui.NNetMap);
            java.util.List hiddenNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                    .selectNodes(Erudite_gui.NNetMap);
            java.util.List outputNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='OUTPUT']/NEURODE")
                    .selectNodes(Erudite_gui.NNetMap);
            Color colr = new Color(0, 153, 255);
            jLabel2.setForeground(colr);
            jLabel2.setText("Valid ANNeML file.");
            HTMLEditorKit kit = (HTMLEditorKit) jEditorPane1.getEditorKit();
            HTMLDocument doc = (HTMLDocument) jEditorPane1.getDocument();
            kit.insertHTML(doc, jEditorPane1.getCaretPosition(), "<b>" + filename + " loaded...</b>", 0, 0,
                    null);
            jLabel3.setText("Subnet(s): " + subnets.size() + "  Layers: " + layers.size() + "  Inputs: "
                    + inputNeurodes.size() + "  Hidden: " + hiddenNeurodes.size() + "  Outputs: "
                    + outputNeurodes.size());
            jLabel7.setText(java.lang.String.valueOf(inputNeurodes.size()));
            Erudite_gui.inputNID = new String[inputNeurodes.size()];
            Erudite_gui.inputCNAME = new String[inputNeurodes.size()];
            Erudite_gui.outputNID = new String[outputNeurodes.size()];
            Erudite_gui.outputCNAME = new String[outputNeurodes.size()];
            int i = 0;
            for (Iterator it = inputNeurodes.iterator(); it.hasNext();) {
                Element InputNode = (Element) it.next();
                Erudite_gui.inputNID[i] = InputNode.getAttributeValue("N_ID");
                Erudite_gui.inputCNAME[i] = InputNode.getAttributeValue("CNAME");
                tblmodel.addRow(
                        new String[] { null, Erudite_gui.inputNID[i] + " '" + inputCNAME[i] + "' ", null });
                kit.insertHTML(doc, jEditorPane1.getCaretPosition(),
                        "<b>" + inputNID[i] + "</b> " + inputCNAME[i] + "<br>", 0, 0, null);
                i++;
            }
            int y = 0;
            for (Iterator it = outputNeurodes.iterator(); it.hasNext();) {
                Element OutputNode = (Element) it.next();
                Erudite_gui.outputCNAME[y] = OutputNode.getAttributeValue("CNAME");
                Erudite_gui.outputNID[y] = OutputNode.getAttributeValue("N_ID");
                kit.insertHTML(doc, jEditorPane1.getCaretPosition(),
                        "<b>" + outputNID[y] + "</b> " + outputCNAME[y] + "<br>", 0, 0, null);
                y++;
            }
            kit.insertHTML(doc, jEditorPane1.getCaretPosition(),
                    "Ready for input processing or training...<br><br>", 0, 0, null);
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(jPanel1, "There was an error parsing the file.\n" + e.toString(),
                "Warning", JOptionPane.WARNING_MESSAGE);
    }

}

From source file:LineNumberSAXBuilderDemo.java

License:Open Source License

public static void main(String[] args) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    builder.setSAXHandlerFactory(LineNumberSAXHandler.SAXFACTORY);
    Document doc = builder.build(new StringReader(xml));

    for (Iterator<LineNumberElement> iter = doc.getDescendants(Filters.fclass(LineNumberElement.class)); iter
            .hasNext();) {/*w w w .  j  av a 2  s .  c  o m*/
        LineNumberElement e = iter.next();
        System.out.println(e.getName() + ": lines " + e.getStartLine() + " to " + e.getEndLine());
    }

}

From source file:VraagServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Bestandslocatie van de XML file. Later als parameter meegeven
    String xmlUrl = "file:///H:/NetBeansProjects/WebApplication1/GMFM.xml";

    PrintWriter out = new PrintWriter(response.getOutputStream());

    //Maakt HTML pagina aan
    out.println("<html>");
    out.println("<head><title>Formulier</title></head>");
    out.println("<body>");

    try {/* w ww  .  j a v a 2s  . c om*/
        //Maakt een URL aan die naar het XML document wijst. En een builder die vervolgens een document opbouwt.
        URL theDoc = new URL(xmlUrl);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(theDoc);

        // Geeft het root element (Formulier)
        Element root = document.getRootElement();

        /* Maakt een lijst aan waarin alle XML staat die tussen <uitleg> </uitleg> staat. 
         De lijst wordt vervolgens geitereerd totdat alle elementen uit de uitleg zijn geweest en in de html staan.*/
        List uitleg = root.getChildren("UITLEG");
        Iterator uitlegItr = uitleg.iterator();
        while (uitlegItr.hasNext()) {
            Object u = uitlegItr.next();
            Element beschrijving = (Element) u;
            out.println(beschrijving.getChildText("BESCHRIJVING"));
        }

        /* Maakt een lijst aan waarin alle XML staat die tussen <regel> </regel> staat. 
         De lijst wordt vervolgens geitereerd totdat alle elementen uit de regel zijn geweest.*/
        List vragen = root.getChildren("REGEL");
        Iterator itr = vragen.iterator();

        //Er wordt net zolang doorgegaan totdat de laatste vraag is bereikt. Alle vragen worden in een tabel gestopt.
        out.println("<table border =1>");
        out.println("<form >");
        while (itr.hasNext()) {
            Object o = itr.next();
            Element vraag = (Element) o;

            /*Hieronder worden de verschillende invoermogelijkheden opgeslagen dus bijvoorbeeld 4 checkbox buttons naast elkaar.
             Een variabele met NT erachter betekent dat deze een extra knop heeft voor niet getest.
             VALUES NOG TOEVOEGEN AAN VARIABELEN
             Uitbreiden indien nodig!!*/
            StringBuffer row = new StringBuffer("<tr>");
            //                

            /*De vraag wordt opgehaald en in de eerste kolom van de tabel gezet.
            Vervolgens wordt het antwoord opgehaald en wordt gekeken waarmee dit antwoord overeen komt. 
            Dit bepaald vervolgens hoeveel checkbox buttons/tekstvakken er gemaakt worden of dat er gewoon tekst afgedrukt wordt. 
            Uitbreiden als nodig!!!
            */
            row.append("<td>" + vraag.getChildText("VRAAG") + "</td>");
            String antwoord = vraag.getChildText("INVOERMOGELIJKHEID");

            if (antwoord.equals("driecheckbox")) {
                row.append("<td>" + "<input type=\"checkbox\" name=\"driecheckbox\" value=\"0\">"
                        + "<input type=\"checkbox\" name=\"driecheckbox\" value=\"0\">"
                        + "<input type=\"checkbox\" name=\"driecheckbox\" value=\"0\">");
            } else if (antwoord.equals("viercheckboxNT")) {
                row.append("<td>" + "<input type=\"checkbox\" name=\"viercheckboxNT\" value=\"0\" id=\"0\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"1\"id=\"1\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"2\"id=\"2\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"3\"id=\"3\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"\"id=\"4\">" + "</td>");

            } else if (antwoord.equals("vijfcheckbox")) {
                row.append("<td>" + "<input type=\"checkbox\" name=\"vijfcheckbox\" value=\"0\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"1\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"2\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"3\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"4\">");
            } else if (antwoord.equals("tekstvak")) {
                row.append("<td>" + "<INPUT TYPE=\"text\" NAME=\"tekstvak\" SIZE=\"13\" MAXLENGTH=\"20\">");
            } else {
                row.append("<td>" + antwoord);
            }
            //Hier wordt de regel uitgeprint in de html 
            out.println(row.toString());

        }

        //Sluiten van tabel en html 
        out.println("</table>");
        out.println("<input type=\"submit\" value=\"Formulier verzenden\">");
        String[] results = request.getParameterValues("viercheckboxNT");
        for (int i = 0; i < results.length; i++) {
            out.println(results[i]);
        }
        out.println("</form>");

        out.println("</body></html>");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:adruinoSignal.tools.ConfigParser.java

public ConfigParser(String path) throws JDOMException, IOException {
    File f = new File(path);
    SAXBuilder saxBuilder = new SAXBuilder();
    doc = saxBuilder.build(f);
}

From source file:agendavital.modelo.data.InicializarBD.java

public static void cargarXMLS() throws JDOMException, IOException, SQLException, ConexionBDIncorrecta {
    SAXBuilder builder = new SAXBuilder();
    File xmlFolder = new File("Noticias");
    File[] xmlFile = xmlFolder.listFiles();
    System.out.println("LONGITUD " + xmlFile.length);
    for (int i = 0; i < xmlFile.length; i++) {

        Document document = (Document) builder.build(xmlFile[i]);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("Noticia");
        for (Object list1 : list) {
            Element noticia = (Element) list1;
            List noticiaCampos = noticia.getChildren();
            String titulo = noticia.getChildTextTrim("titulo");

            String fecha = noticia.getChildTextTrim("fecha");

            String link = noticia.getChildTextTrim("link");

            String categorias = noticia.getChildTextTrim("categoria");

            String cuerpo = noticia.getChildTextTrim("cuerpo");

            List tags = noticia.getChildren("tag");
            ArrayList<String> etiquetas = new ArrayList<>();
            for (Object tags1 : tags) {
                Element tag = (Element) tags1;

                etiquetas.add(tag.getTextTrim());
            }//from  w  ww . jav  a2 s . c o  m
            Noticia.Insert(titulo, link, fecha, categorias, cuerpo, etiquetas);
        }
    }
}

From source file:AIR.Common.xml.XmlReader.java

License:Open Source License

private void buildDocument(Closeable file) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    if (file instanceof InputStream)
        _doc = builder.build((InputStream) file);
    else if (file instanceof Reader)
        _doc = builder.build((Reader) file);
    _stack.push(new MutablePair<Content, Integer>(_doc.getRootElement(), -1));
    _rootNameSpace = _doc.getRootElement().getNamespace();
    _file = file;/*from w w  w  .  j av  a2s  .  c om*/
}

From source file:AIR.ResourceBundler.Xml.Resources.java

License:Open Source License

public void parse() throws JDOMException, IOException, ResourcesException {
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(_configFile);
    Document document = (Document) builder.build(xmlFile);
    Element rootElement = document.getRootElement();

    String attr = rootElement.getAttributeValue("name");
    name = (attr != null) ? attr : null;
    for (Element childEl : rootElement.getChildren()) {
        String childName = childEl.getName();
        if ("import".equalsIgnoreCase(childName)) {
            parseImport(childEl);//from w  w w  .  ja  v  a 2  s .  c om
        } else if ("fileSet".equalsIgnoreCase(childName)) {
            parseFileSet(childEl);
        } else if ("remove".equalsIgnoreCase(childName)) {
            parseRemove(childEl);
        }

    }
}

From source file:app.simulation.Importer.java

License:MIT License

public void importXML() throws Exception {
    File file = new File(path);

    if (!file.exists())
        throw new FileNotFoundException(path);

    if (!getFileFormat().equalsIgnoreCase("xml"))
        throw new InvalidFileFormatException(getFileFormat());

    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = saxBuilder.build(file);
    Element root = document.getRootElement();
    Element configuration = root.getChild("configuration");

    if (configuration != null) {

        String delayText = configuration.getChildText("delay");
        if (delayText == null)
            throw new AttributeNotFoundException("delay");

        String iterationsText = configuration.getChildText("iterations");
        if (iterationsText == null)
            throw new AttributeNotFoundException("iterations");

        String agentsText = configuration.getChildText("agents");
        if (agentsText == null)
            throw new AttributeNotFoundException("agents");

        String latticeSizeText = configuration.getChildText("latticeSize");
        if (latticeSizeText == null)
            throw new AttributeNotFoundException("latticeSize");

        String descriptionText = configuration.getChildText("description");
        if (descriptionText == null)
            throw new AttributeNotFoundException("description");

        int delay = Integer.parseInt(delayText);
        int iterations = Integer.parseInt(iterationsText);
        int agents = Integer.parseInt(agentsText);
        int latticeSize = Integer.parseInt(latticeSizeText);
        this.configuration = new Configuration(delay, iterations, agents, latticeSize, descriptionText);
    }//from w  w w  .  j a  v  a2s .c o  m

    Element initialCell = root.getChild("initialCell");

    if (initialCell != null) {

        String xText = initialCell.getChildText("x");
        if (xText == null)
            throw new AttributeNotFoundException("x");

        String yText = initialCell.getChildText("y");
        if (yText == null)
            throw new AttributeNotFoundException("y");

        String zText = initialCell.getChildText("z");
        if (zText == null)
            throw new AttributeNotFoundException("z");

        String stateText = initialCell.getChildText("state");
        if (stateText == null)
            throw new AttributeNotFoundException("state");

        Element colorElement = initialCell.getChild("color");
        if (colorElement == null)
            throw new AttributeNotFoundException("color");

        String rText = colorElement.getChildText("r");
        if (rText == null)
            throw new AttributeNotFoundException("r");

        String gText = colorElement.getChildText("g");
        if (gText == null)
            throw new AttributeNotFoundException("g");

        String bText = colorElement.getChildText("b");
        if (bText == null)
            throw new AttributeNotFoundException("b");

        int x = Integer.parseInt(xText);
        int y = Integer.parseInt(yText);
        int z = Integer.parseInt(zText);
        int state = Integer.parseInt(stateText);
        Color color = new Color(Integer.parseInt(rText), Integer.parseInt(gText), Integer.parseInt(bText));
        this.initialCell = new Cell(x, y, z, state, color);
    }

    Element tagRules = root.getChild("rules");
    rules = new ArrayList<Rule>();

    if (tagRules != null) {
        List<Element> elementRules = tagRules.getChildren("rule");

        if (elementRules.size() > 0) {

            for (Element rule : elementRules) {

                String neighbourhood = rule.getChildText("neighbourhood");
                if (neighbourhood == null)
                    throw new AttributeNotFoundException("neighbourhood");

                String stateText = rule.getChildText("state");
                if (stateText == null)
                    throw new AttributeNotFoundException("state");

                Element colorElement = rule.getChild("color");
                if (colorElement == null)
                    throw new AttributeNotFoundException("color");

                String rText = colorElement.getChildText("r");
                if (rText == null)
                    throw new AttributeNotFoundException("r");

                String gText = colorElement.getChildText("g");
                if (gText == null)
                    throw new AttributeNotFoundException("g");

                String bText = colorElement.getChildText("b");
                if (bText == null)
                    throw new AttributeNotFoundException("b");

                int state = Integer.parseInt(stateText);
                Color color = new Color(Integer.parseInt(rText), Integer.parseInt(gText),
                        Integer.parseInt(bText));

                rules.add(new Rule(neighbourhood, state, color));
            }
        }
    }

}