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:codigoFonte.Sistema.java

public boolean editarUser(User u) {
    File file = new File("Sistema.xml");
    Document newDocument = null;//from  w w w  .j ava 2 s.  c  o m
    Element root = null;
    boolean success = false;

    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();
    }

    List<Element> listusers = root.getChildren();
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(u.getMatricula())) {
            e.getAttribute("nome").setValue(u.getNome());
            e.getAttribute("tipo").setValue(u.getTipo());
            e.getAttribute("senha").setValue(u.getPassword());

            success = true;

            XMLOutputter out = new XMLOutputter();

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

From source file:codigoFonte.Sistema.java

public ArrayList<User> listarUser() {
    File file = new File("Sistema.xml");
    Document newDocument = null;//from  ww  w  .j  ava 2  s.  co m
    Element root = null;
    ArrayList<User> users = new ArrayList<User>();
    ;
    ArrayList<Livro> livros = new ArrayList<Livro>();

    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);
    }

    List<Element> listusers = root.getChildren();
    for (Element e : listusers) {
        User user = new User(null, null, null, null);
        List<Element> listlivro = e.getChildren("livro");
        List<Element> historico = e.getChildren("histrico");

        if (!listlivro.isEmpty())

            for (Element l : listlivro) {
                Livro livro = new Livro(null, null, null, 0);
                livro.setAutor(l.getAttributeValue("autor"));
                livro.setEditora(l.getAttributeValue("editora"));
                livro.setTitulo(l.getAttributeValue("ttulo"));
                livros.add(livro);
            }

        //List<Element> historico = e.getChildren("histrico");
        ArrayList<Livro> historicoObjeto = new ArrayList<Livro>();
        if (!historico.isEmpty()) {
            for (Element h : historico) {
                Livro livroHistorico = new Livro(null, null, null, 0);
                livroHistorico.setAutor(h.getAttributeValue("autor"));
                livroHistorico.setEditora(h.getAttributeValue("editora"));
                livroHistorico.setTitulo(h.getAttributeValue("ttulo"));
                historicoObjeto.add(livroHistorico);
            }
        }

        user.setMatricula(e.getAttributeValue("matrcula"));
        user.setNome(e.getAttributeValue("nome"));
        user.setTipo(e.getAttributeValue("tipo"));
        user.setLivros(livros);

        users.add(user);
    }
    return users;
}

From source file:codigoFonte.Sistema.java

public User pesquisarUser(String matricula) {
    File file = new File("Sistema.xml");
    Document newDocument = null;//www  .  j  a v  a 2 s  .  co  m
    Element root = null;
    User user = null;

    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);
    }

    List<Element> listusers = root.getChildren();
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(matricula)) {
            List<Element> listlivros = e.getChildren("livro");
            user = new User(null, null, null, null);
            if (!listlivros.isEmpty()) {
                for (Element l : listlivros) {
                    Livro livro = new Livro(null, null, null, 0);
                    livro.setAutor(l.getAttributeValue("autor"));
                    livro.setEditora(l.getAttributeValue("editora"));
                    livro.setTitulo(l.getAttributeValue("ttulo"));
                    livro.setEntrega(l.getAttributeValue("dataEntrega"));
                    livro.setAluguel(l.getAttributeValue("dataAluguel"));
                    livro.setId(l.getAttributeValue("id"));
                    user.getLivros().add(livro);
                }
            }
            List<Element> historico = e.getChildren("historico");
            if (!historico.isEmpty()) {
                for (Element h : historico) {
                    Livro livroHistorico = new Livro(null, null, null, 0);
                    livroHistorico.setAutor(h.getAttributeValue("autor"));
                    livroHistorico.setEditora(h.getAttributeValue("editora"));
                    livroHistorico.setTitulo(h.getAttributeValue("ttulo"));
                    livroHistorico.setEntrega(h.getAttributeValue("dataEntrega"));
                    livroHistorico.setAluguel(h.getAttributeValue("dataAluguel"));
                    livroHistorico.setId(h.getAttributeValue("id"));
                    user.getHistorico().add(livroHistorico);
                }
            }
            user.setMatricula(matricula);
            user.setTipo(e.getAttributeValue("tipo"));
            user.setNome(e.getAttributeValue("nome"));
            user.setPassword(e.getAttributeValue("senha"));

            return user;
        }
    }
    return user;
}

From source file:codigoFonte.Sistema.java

public boolean removeUser(User u) {
    File file = new File("Sistema.xml");
    Document newDocument = null;/*  w  ww  .  ja v a  2s.c  o  m*/
    Element root = null;
    Element user = null;
    boolean success = false;

    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);
    }

    List<Element> listusers = root.getChildren("user");
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(u.getMatricula()) && e.getChildren("livro").size() == 0) {
            root.removeContent(e);

            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);
            }

            success = true;
            return success;
        }
    }
    return success;
}

From source file:codigoFonte.Sistema.java

public boolean autentica(User u) {
    File file = new File("Sistema.xml");
    Document newDocument = null;//from ww w  . ja v  a2  s  .c  o m
    Element root = null;
    boolean autenticado = false;

    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);
    }

    User user = null;
    List<Element> listusers = root.getChildren();
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(u.getMatricula())
                && e.getAttributeValue("senha").equals(u.getPassword())) {
            autenticado = true;
            return autenticado;
        }
    }
    return autenticado;
}

From source file:codigoFonte.Sistema.java

public boolean autenticaAdmin(String username, String password) {
    File file = new File("Sistema.xml");
    Document newDocument = null;/*  w  w  w .j a  v  a  2s .  c  o m*/
    Element root = null;
    boolean autenticado = false;

    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.getAttributeValue("username").equals(username)
            && root.getAttributeValue("password").equals(password)) {
        autenticado = true;
        return autenticado;
    }
    return autenticado;
}

From source file:com.accenture.control.Xml.java

public List<Plano> lerXML() {
    List<CtAlm> listCtALM = new ArrayList<CtAlm>();
    List<Plano> listPlano = new ArrayList<Plano>();
    try {/*from w  ww  .j a  v a2  s .  c o  m*/

        String valor = null;

        //Aqui voc informa o nome do arquivo XML.
        logger.info("Inicio mtodo:  new File(FILE);");
        File f = new File(FILE);
        logger.info("Inicio mtodo:  new FileInputStream(f);");
        //            logger.info("Inicio mtodo:  new FileInputStream(f);");
        //            InputStream inputStream = new FileInputStream(f);
        //            logger.info("Inicio mtodo:  new InputStreamReader(inputStream, \"UTF-8\";");
        //            Reader reader = new InputStreamReader(inputStream, "UTF-8");
        //
        //            InputSource is = new InputSource(reader);
        logger.info(
                "Inicio do mtodo:  new BufferedReader(new InputStreamReader(new FileInputStream(f), \"UTF-8\"))");
        BufferedReader myBuffer = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
        logger.info(
                "Fim do mtodo:  new BufferedReader(new InputStreamReader(new FileInputStream(f), \"UTF-8\"))");
        logger.info("Inicio do mtodo: new InputSource(myBuffer)");
        InputSource is = new InputSource(myBuffer);
        logger.info("Fim do mtodo: new InputSource(myBuffer)");

        logger.info("Arquivo xml: " + FILE);

        logger.info("Criando objeto Document doc");
        Document doc = null;
        logger.info("Criado objeto Document doc e setado como null");
        logger.info("Criando objeto SAXBuilder builder");
        SAXBuilder builder = new SAXBuilder();
        logger.info("Criado objeto SAXBuilder builder new SAXBuilder()");
        logger.info("inicio - doc = builder.build(is);");
        doc = builder.build(is);
        logger.info("fim - doc = builder.build(is);");

        logger.info("inicio - org.jdom2.Element ct = doc.getRootElement();");
        org.jdom2.Element ct = doc.getRootElement();
        logger.info("fim - org.jdom2.Element ct = doc.getRootElement();");
        //            org.jdom2.Element ct = doc.getRootElement().getChild("Entity").getChild("Fields");

        if (Integer.parseInt(ct.getAttributeValue("TotalResults")) == 0) {
            logger.info("Nenhum CT foi encontrado no arquivo XML");
            System.out.println("A busca no retornou resultados");
            JOptionPane.showMessageDialog(null, "Nenhum CT foi encontrado.", "ALM",
                    JOptionPane.INFORMATION_MESSAGE);
            return null;
        } else {

            List<org.jdom2.Element> lista = ct.getChildren();
            logger.info("Tamanho da listaroot do xml: " + lista.size());
            List<org.jdom2.Element> lista2 = ct.getChild("Entity").getChild("Fields").getChildren();
            logger.info("Tamanho da lista de campo do xml: " + lista2.size());
            Iterator i = lista.iterator();

            while (i.hasNext()) {
                logger.info("Iniciando o loop das entity");
                CtAlm ctALM = new CtAlm();
                Plano p = new Plano();
                org.jdom2.Element element = (org.jdom2.Element) i.next();
                System.out.println("Type:" + element.getAttributeValue("Type"));

                Iterator j = lista2.iterator();
                int cont = 0;

                while (j.hasNext()) {
                    logger.info("Iniciando o loop dos fields");
                    org.jdom2.Element element2 = (org.jdom2.Element) j.next();
                    //                System.out.println("Name:" + element2.getAttributeValue("Name"));

                    System.out.println("Name:"
                            + element.getChild("Fields").getChildren().get(cont).getAttributeValue("Name"));
                    ctALM.setCampo(
                            element.getChild("Fields").getChildren().get(cont).getAttributeValue("Name"));
                    System.out.println("Value:"
                            + element.getChild("Fields").getChildren().get(cont).getChildText("Value"));
                    ctALM.setValor(element.getChild("Fields").getChildren().get(cont).getChildText("Value"));
                    String nomeCampo = element.getChild("Fields").getChildren().get(cont)
                            .getAttributeValue("Name");
                    String valorCampo = element.getChild("Fields").getChildren().get(cont)
                            .getChildText("Value");

                    switch (nomeCampo) {
                    case "user-template-08":
                        p.setQtdSistemas(Integer.parseInt(valorCampo));
                        break;

                    case "user-template-09":
                        p.setQtdStep(Integer.parseInt(valorCampo));
                        break;

                    case "user-template-01":
                        p.setSistemaMaster(valorCampo);
                        break;

                    case "user-template-03":
                        p.setCenarioTeste(valorCampo);
                        break;

                    case "user-template-06":
                        p.setRequisito(valorCampo);
                        break;

                    case "user-template-05":
                        p.setFornecedor(valorCampo);
                        break;

                    case "description":

                        String descricao = valorCampo;
                        //                                convertFromUTF8(descricao);
                        logger.debug("Campo Descrio: " + descricao);
                        //                                try{
                        //                                   logger.debug("Parse no campo Descrio: "+ descricao );
                        //                                   descricao = Jsoup.parse(descricao).text();
                        //                                }catch(Exception ex){
                        //                                     logger.error("Erro parser ",ex);
                        //                                }

                        logger.debug("Setando no objeto plano: p.setDescCasoTeste(descricao);");
                        p.setDescCasoTeste(descricao);
                        logger.debug("Setado no objeto plano: p.setDescCasoTeste(descricao);");
                        break;

                    case "user-template-28":
                        p.setTpRequisito(valorCampo);
                        break;

                    case "user-template-22":
                        p.setSistemasEnvolvidos(valorCampo);
                        break;

                    case "user-template-24":
                        p.setComplexidade(valorCampo);
                        break;

                    case "name":
                        p.setCasoTeste(valorCampo);
                        break;

                    case "subtype-id":
                        p.setType(valorCampo);
                        break;
                    }

                    logger.info("Fim do loop dos fields - nome do campo: " + nomeCampo);
                    logger.info("contador do campo: " + cont);
                    cont++;
                }
                logger.info("Adicionando CT na lista de plano");
                listPlano.add(p);
                logger.info("Adicionando " + p.getCasoTeste() + " CT adicoando na lista");
                logger.info("Fim do loop das entity");
            }

        }

    } catch (JDOMException ex) {
        JOptionPane.showMessageDialog(null, "Ocorreu o erro: " + ex.getMessage() + ex.getLocalizedMessage(),
                "Erro", JOptionPane.ERROR_MESSAGE);
        logger.error("Erro : ", ex);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Ocorreu o erro: " + ex.getMessage() + ex.getLocalizedMessage(),
                "Erro", JOptionPane.ERROR_MESSAGE);
        logger.error("Erro : ", ex);
    }

    logger.info("Tamanho da Lista de CTS extraidos do XML : " + listPlano.size());
    return listPlano;

}

From source file:com.archimatetool.jdom.JDOMUtils.java

License:Open Source License

/**
 * Reads and returns a JDOM Document from file with Schema validation
 * @param xmlFile The XML File// ww w . j a  v  a 2 s. c  o  m
 * @param schemaFile One or more Schema files
 * @return The JDOM Document or null if not found
 * @throws JDOMException
 * @throws IOException
 */
public static Document readXMLFile(File xmlFile, File... schemaFiles) throws IOException, JDOMException {
    XMLReaderJDOMFactory factory = new XMLReaderXSDFactory(schemaFiles);
    SAXBuilder builder = new SAXBuilder(factory);

    // This allows UNC mapped locations to load
    return builder.build(new FileInputStream(xmlFile));
}

From source file:com.archimatetool.jdom.JDOMUtils.java

License:Open Source License

/**
 * Reads and returns a JDOM Document from file without Schema Validation
 * @param file The XML File/*from w  w  w.j  a  v a2s .  c o m*/
 * @return The JDOM Document or null if not found
 * @throws JDOMException
 * @throws IOException
 */
public static Document readXMLFile(File file) throws IOException, JDOMException {
    SAXBuilder builder = new SAXBuilder();
    // This allows UNC mapped locations to load
    return builder.build(new FileInputStream(file));
}

From source file:com.archimatetool.jdom.JDOMUtils.java

License:Open Source License

/**
 * Reads and returns a JDOM Document from String without Schema Validation
 * @param xmlString//  ww w .  j a va 2 s.com
 * @return
 * @throws JDOMException
 * @throws IOException
 */
public static Document readXMLString(String xmlString) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    return builder.build(new StringReader(xmlString));
}