Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:codigoFonte.Sistema.java

public User pesquisarUser(String matricula) {
    File file = new File("Sistema.xml");
    Document newDocument = null;
    Element root = null;//from w ww. j  ava  2  s  .c  o m
    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;
    Element root = null;/*from w w w . ja  v a  2  s  . c o m*/
    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;
    Element root = null;//from   w w  w.  j  a va  2  s  .c  om
    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;
    Element root = null;//from   ww  w.ja va2s . co m
    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.abyala.decisiontree.SimpleDecisionTreeParser.java

License:Open Source License

protected DecisionTree parseDocument(final Document doc) throws DecisionTreeParserException {
    final Element rootElement = doc.getRootElement();
    final Map<String, InputType> types = parseInputTypes(rootElement.getChild("input-types"));
    final ResultSpec resultSpec = parseResultClass(rootElement.getChild("result-type"));
    final Node rootNode = parseTable(rootElement.getChild("tree"), types, resultSpec);
    return new DecisionTree(rootNode, types.values());
}

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 av a  2s .  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.canvas.templates.model.CanvasTemplateManager.java

License:Open Source License

@Override
protected boolean isValidTemplateFile(File file) throws IOException {
    if (file == null || !file.exists()) {
        return false;
    }// w w  w .  j av  a 2s. c o  m

    // Ensure the template is of the right kind
    String xmlString = ZipUtils.extractZipEntry(file, ZIP_ENTRY_MANIFEST);
    if (xmlString == null) {
        return false;
    }

    // If the attribute "type" exists then return true if its value is "canvas".
    // If the attribute doesn't exist it was from an older version (before 2.1)
    try {
        Document doc = JDOMUtils.readXMLString(xmlString);
        Element root = doc.getRootElement();
        Attribute attType = root.getAttribute(ITemplateXMLTags.XML_TEMPLATE_ATTRIBUTE_TYPE);
        if (attType != null) {
            return CanvasModelTemplate.XML_CANVAS_TEMPLATE_ATTRIBUTE_TYPE_MODEL.equals(attType.getValue());
        }
    } catch (JDOMException ex) {
        return false;
    }

    return true;
}

From source file:com.archimatetool.editor.model.impl.EditorModelManager.java

License:Open Source License

private void loadState() throws IOException, JDOMException {
    if (backingFile.exists()) {
        Document doc = JDOMUtils.readXMLFile(backingFile);
        if (doc.hasRootElement()) {
            Element rootElement = doc.getRootElement();
            for (Object e : rootElement.getChildren("model")) { //$NON-NLS-1$
                Element modelElement = (Element) e;
                String filePath = modelElement.getAttributeValue("file"); //$NON-NLS-1$
                if (filePath != null) {
                    loadModel(new File(filePath));
                }//from  ww  w .j  av a 2  s  .  c o  m
            }
        }
    }
}

From source file:com.archimatetool.model.util.RelationshipsMatrix.java

License:Open Source License

private void loadKeyLetters() {
    //URL url = Platform.getBundle(BUNDLE_ID).getResource(RELATIONSHIPS_KEYS_FILE);
    URL url = Platform.getBundle(BUNDLE_ID).getEntry(RELATIONSHIPS_KEYS_FILE);

    // Load the JDOM Document from XML
    Document doc = null;
    try {//from  ww  w .ja  v a 2 s.  c  o  m
        doc = new SAXBuilder().build(url);
    } catch (Exception ex) {
        ex.printStackTrace();
        return;
    }

    for (Object object : doc.getRootElement().getChildren(XML_ELEMENT_KEY)) {
        Element elementKey = (Element) object;

        String keyLetter = elementKey.getAttributeValue(XML_ATTRIBUTE_CHAR);
        if (keyLetter == null || keyLetter.length() != 1) {
            System.err.println(getClass() + ": Key letter incorrect: " + keyLetter); //$NON-NLS-1$
            continue;
        }

        String relationName = elementKey.getAttributeValue(XML_ATTRIBUTE_RELATIONSHIP);
        if (relationName == null) {
            System.err.println(getClass() + ": Relationship name incorrect: " + relationName); //$NON-NLS-1$
            continue;
        }

        EClass relationship = (EClass) IArchimatePackage.eINSTANCE.getEClassifier(relationName);
        if (relationship == null) {
            System.err.println(getClass() + ": Couldn't find relationship " + relationName); //$NON-NLS-1$
            continue;
        }

        relationsKeyMap.put(keyLetter.charAt(0), relationship);
        relationsValueMap.put(relationship, keyLetter.charAt(0));
    }
}

From source file:com.archimatetool.model.util.RelationshipsMatrix.java

License:Open Source License

private void loadRelationships() {
    //URL url = Platform.getBundle(BUNDLE_ID).getResource(RELATIONSHIPS_FILE);
    URL url = Platform.getBundle(BUNDLE_ID).getEntry(RELATIONSHIPS_FILE);

    // Load the JDOM Document from XML
    Document doc = null;
    try {/*from ww w.j  a v  a2s .  c  om*/
        doc = new SAXBuilder().build(url);
    } catch (Exception ex) {
        ex.printStackTrace();
        return;
    }

    // Iterate through all "source" elements
    Element elementElements = doc.getRootElement().getChild(XML_ELEMENT_ELEMENTS);
    if (elementElements == null) { // oops
        System.err.println(getClass() + ": Couldn't find elements element."); //$NON-NLS-1$
        return;
    }

    for (Object object : elementElements.getChildren(XML_ELEMENT_SOURCE)) {
        Element elementSource = (Element) object;

        // Source element name
        String sourceName = elementSource.getAttributeValue(XML_ATTRIBUTE_ELEMENT);
        if (sourceName == null) {
            continue;
        }

        // Get EClass source from mapping
        EClass source = (EClass) IArchimatePackage.eINSTANCE.getEClassifier(sourceName);
        if (source == null) {
            System.err.println(getClass() + ": Couldn't find source " + sourceName); //$NON-NLS-1$
            continue;
        }

        // Create a new list of type TargetMatrix
        List<TargetMatrix> matrixList = new ArrayList<TargetMatrix>();

        // Put it in the main matrix map
        matrixMap.put(source, matrixList);

        // Iterate through all child "target" elements
        for (Object objectChild : elementSource.getChildren(XML_ELEMENT_TARGET)) {
            Element elementTarget = (Element) objectChild;

            // Target element name
            String targetName = elementTarget.getAttributeValue(XML_ATTRIBUTE_ELEMENT);
            if (targetName == null) {
                continue;
            }

            // Get EClass target from mapping
            EClass target = (EClass) IArchimatePackage.eINSTANCE.getEClassifier(targetName);
            if (target == null) {
                System.err.println(getClass() + ": Couldn't find target " + targetName); //$NON-NLS-1$
                continue;
            }

            // Create a new TargetMatrix and add it to the list
            TargetMatrix matrix = new TargetMatrix();
            matrixList.add(matrix);

            // Set target class 
            matrix.targetClass = target;

            // Get relations string
            String relations = elementTarget.getAttributeValue(XML_ATTRIBUTE_RELATIONS);
            if (relations == null) {
                continue;
            }

            // Take each character and add the relationship from the mapping
            for (int i = 0; i < relations.length(); i++) {
                char key = relations.charAt(i);
                EClass relationship = relationsKeyMap.get(key);
                if (relationship != null) {
                    matrix.getRelationships().add(relationship);
                } else {
                    System.err.println(getClass() + ": Found unmapped key char: " + key); //$NON-NLS-1$
                }
            }
        }
    }
}