Example usage for org.jdom2.input SAXBuilder SAXBuilder

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

Introduction

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

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:BL.Servlets.AddNode.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww w  . j  a  v a 2s .  com
 *
 * @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("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet AddUser</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet AddUser at " + request.getContextPath() + "</h1>");
        String NodeType = "residentialProperties";
        Boolean isFound = false;
        try {
            String note_id = keyin("Please Enter note id you need to search: ");
            SAXBuilder saxBuilder = new SAXBuilder();
            String xmlFile = "src\\database.xml";
            Document xmlDoc = saxBuilder.build(new File(xmlFile));
            Element rootElement = xmlDoc.getRootElement();
            //
            List<Element> ListNodeType = rootElement.getChildren(NodeType);
            //
            List<Element> lstNotes = rootElement.getChildren();
            for (int i = 0; i < lstNotes.size(); i++) {
                Element note = (Element) lstNotes.get(i);
                String n_id = note.getAttributeValue("id");
                System.out.println("Note id: " + n_id);
                if (note_id.equalsIgnoreCase(n_id)) {
                    isFound = true;
                    String name = note.getChildText("name");
                    String value = note.getAttributeValue("value");
                    System.out.println(
                            "We found a note with id " + note_id + "; name: " + name + "Value: " + value);
                    break;
                }

            }
            if (!isFound) {
                System.out.println("Sorry, we don't find out any note with id: " + note_id);
            }
            System.out.println("Finished search!");
        } catch (Exception e) {
            // TODO: handle exception
        }
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }
}

From source file:br.com.gsoftwares.util.ImportClient.java

private void lerarq(String caminho) throws Exception {
    //Aqui voc informa o nome do arquivo XML.  
    File f = new File(caminho);
    File[] arquivos = f.listFiles();
    //Criamos uma classe SAXBuilder que vai processar o XML  
    for (File fileTmp : arquivos) {

        SAXBuilder sb = new SAXBuilder();

        //Este documento agora possui toda a estrutura do arquivo.  
        Document d;/* w  ww .j  av  a2 s.c  o  m*/
        try {
            d = sb.build(fileTmp);
            //Recuperamos o elemento root  
            Element nfe = d.getRootElement();

            //Recuperamos os atributos filhos (Attributes)  
            List atributes = nfe.getAttributes();
            Iterator i_atr = atributes.iterator();

            //Iteramos com os atributos filhos  
            while (i_atr.hasNext()) {
                Attribute atrib = (Attribute) i_atr.next();
                //System.out.println("\nattribute de (" + nfe.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
            }
            //Recuperamos os elementos filhos (children)  
            List elements = nfe.getChildren();
            Iterator i = elements.iterator();

            //Iteramos com os elementos filhos, e filhos do dos filhos  
            while (i.hasNext()) {
                Element element = (Element) i.next();
                //System.out.println("element:" + element.getName());
                trataElement(element);
            }
            Salvar();
        } catch (JDOMException | IOException ex) {
            Logger.getLogger(LerArqXML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!", "", JOptionPane.INFORMATION_MESSAGE);
}

From source file:br.com.gsoftwares.util.ImportProduto.java

private void lerarq(String caminho) throws Exception {
    //Aqui voc informa o nome do arquivo XML.  
    File f = new File(caminho);
    File[] arquivos = f.listFiles();
    //Criamos uma classe SAXBuilder que vai processar o XML  
    for (File fileTmp : arquivos) {

        SAXBuilder sb = new SAXBuilder();

        //Este documento agora possui toda a estrutura do arquivo.  
        Document d;/*from   w w  w. ja  v  a 2 s.c om*/
        try {
            d = sb.build(fileTmp);
            //Recuperamos o elemento root  
            Element nfe = d.getRootElement();

            //Recuperamos os atributos filhos (Attributes)  
            List atributes = nfe.getAttributes();
            Iterator i_atr = atributes.iterator();

            //Iteramos com os atributos filhos  
            while (i_atr.hasNext()) {
                Attribute atrib = (Attribute) i_atr.next();
                //System.out.println("\nattribute de (" + nfe.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
            }
            //Recuperamos os elementos filhos (children)  
            List elements = nfe.getChildren();
            Iterator i = elements.iterator();

            //Iteramos com os elementos filhos, e filhos do dos filhos  
            while (i.hasNext()) {
                Element element = (Element) i.next();
                //System.out.println("element:" + element.getName());
                trataElement(element);
            }
            //Salvar();
        } catch (JDOMException | IOException ex) {
            Logger.getLogger(LerArqXML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!", "", JOptionPane.INFORMATION_MESSAGE);
}

From source file:br.com.nfe.util.Chave.java

@Override
public void run() {

    while (true) {
        String chave = "";
        Document doc = null;/*from   w w  w. j  a v  a2 s  .  com*/
        SAXBuilder builder = new SAXBuilder();

        Path path = Paths.get("c:/unimake/uninfe/" + pasta + "/Retorno");
        WatchService watchService = null;
        try {
            watchService = FileSystems.getDefault().newWatchService();
            path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        } catch (IOException io) {
            io.printStackTrace();
        }
        WatchKey key = null;

        while (true) {
            try {
                key = watchService.take();

                for (WatchEvent<?> event : key.pollEvents()) {
                    Kind<?> kind = event.kind();
                    System.out.println("Evento em " + event.context().toString() + " " + kind);
                    try {

                        doc = builder.build(
                                "c:/unimake/uninfe/" + pasta + "/Retorno/" + cNf + "-ret-gerar-chave.xml");

                        Element retorno = doc.getRootElement();

                        List<Element> lista = retorno.getChildren();

                        for (Element e : lista) {

                            chave = e.getAttributeValue("chaveNFe");
                            chave = e.getText();

                        }
                        mudaChave(chave);
                        if (chave.isEmpty() == false) {
                            allDone = true;
                        }
                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }

            boolean reset = key.reset();
            if (!reset) {
                break;
            }
            if (allDone) {
                return;
            }
        }

    }
}

From source file:br.com.sicoob.cro.cop.util.JobXMLLoader.java

/**
 * Le o arquivo {@code jobXMLName} e cria os objetos para o processamento.
 *
 * @throws BatchStartException para algum erro de leitura e inicializacao.
 *///from   w  ww .j  a v  a  2  s.c o  m
public void loadJSL() throws BatchStartException {
    try {
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = tccl.getResourceAsStream(PREFIX.concat(this.jobXMlName.concat(XML_SUFFIX)));

        if (Validation.isNull(inputStream)) {
            throw new BatchStartException(
                    BatchPropertiesUtil.getInstance().getMessage(FILENOTFOUND, this.jobXMlName));
        }

        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(inputStream);
        Element rootNode = document.getRootElement();

        this.job = new Job(rootNode.getAttributeValue(ID), Job.Mode.ASYNC);
        loadSteps(rootNode);

        // valida se o job pode est completo
        if (Validation.notNull(this.job.getId()) && Validation.notNull(this.job.getSteps())
                && this.job.getSteps().size() > 0) {
            LOG.info(BatchPropertiesUtil.getInstance().getMessage(BatchKeys.BATCH_LOADER_SUCCESS.getKey(),
                    this.job.getId()));
        } else {
            throw new BatchStartException(BatchPropertiesUtil.getInstance()
                    .getMessage(BatchKeys.BATCH_LOADER_FAIL.getKey(), this.job.getId()));
        }
    } catch (Exception excecao) {
        LOG.fatal(excecao);
        throw new BatchStartException(excecao);
    }
}

From source file:bureau.Services.java

public void getAdmissionsFromFile() {
    SAXBuilder builder = new SAXBuilder();
    try {/*from w  ww .ja va2s .c o m*/
        //on liste et on parcours les fichiers pour trouver les .xml qui sont en ajout et en edit 
        File repertoire = new File("\\\\172.18.8.70\\temp\\PP_PAT_IN");// \\\\178.18.8.70\\temp
        System.out.println("new file");
        String[] listefichiers;
        int i;
        System.out.println("int i string liste fichier");
        listefichiers = repertoire.list();
        System.out.println("repertoire.list()");
        for (i = 0; i < listefichiers.length; i++) {
            System.out.println("dans la boucle");
            //si le fichier est en ajout
            if (listefichiers[i].startsWith("new")) {
                System.out.println("fichier new trouv");
                Document doc = builder.build("" + repertoire + "\\" + listefichiers[i]);
                Element root = doc.getRootElement();
                Element admissionXML = root;
                int type = 1;
                int ipp;
                int iep;
                ipp = parseInt(admissionXML.getChild("patient").getAttributeValue("ipp"));
                iep = parseInt(admissionXML.getAttributeValue("iep"));
                if (admissionXML.getChild("type").getText().startsWith("c"))
                    type = 3;
                if (admissionXML.getChild("type").getText().startsWith("h"))
                    type = 1;
                if (admissionXML.getChild("type").getText().startsWith("u"))
                    type = 2;
                newAdmission(ipp, type, iep);
                System.out.println("nouvelle admission ajoute");
            }
            if (listefichiers[i].startsWith("update")) {
                System.out.println("fichier en update trouv");
                Document doc = builder.build("" + repertoire + "\\" + listefichiers[i]);
                Element root = doc.getRootElement();
                Element admissionXML = root;
                int type = 1;
                int iep = parseInt(admissionXML.getAttributeValue("iep"));
                if (admissionXML.getChild("type").getText().startsWith("c"))
                    type = 3;
                if (admissionXML.getChild("type").getText().startsWith("h"))
                    type = 1;
                if (admissionXML.getChild("type").getText().startsWith("u"))
                    type = 2;
                if (getAdmissionByIep(iep) == null) {
                    System.out.println("Il n'y a pas d'admission avec cet IEP");
                } else {
                    Admission ad = getAdmissionByIep(iep);
                    ad.setType(type);
                    editAdmission(ad);
                    System.out.println("admission modifie");
                }
                String date_sortie = admissionXML.getChild("date_sortie").getValue();
                DateFormat format = new SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH);
                Date date_s = format.parse(date_sortie);
                String date_entree = admissionXML.getChild("date_sortie").getValue();
                Date date_e = format.parse(date_entree);
                List<Mouvement> listemouv = getMouvementByIep(iep);
                if (listemouv != null) {
                    Mouvement mouv = listemouv.get(listemouv.size());
                    updateMouvement(mouv, mouv.getAdmission(), mouv.getLit(), mouv.getUf(), date_e, date_s);
                } else {
                    System.out.println("pas de mouvement pour cette admission");
                }

            }
            if (listefichiers[i].startsWith("mouv")) {
                System.out.println("fichier new trouv");
                Document doc = builder.build("" + repertoire + "\\" + listefichiers[i]);
                Element root = doc.getRootElement();
                Element mouvementXML = root;
                String service = "Cardiologie";
                int ipp;
                int iep;
                Lit lit = new Lit();
                String date_entree = mouvementXML.getChild("date_entree").getValue();
                DateFormat format = new SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH);
                Date date = format.parse(date_entree);
                ipp = parseInt(mouvementXML.getChild("ipp").getValue());
                iep = parseInt(mouvementXML.getChild("iep").getValue());
                if (mouvementXML.getChild("service").getText().endsWith("2"))
                    service = "Radio 2";
                if (mouvementXML.getChild("service").getText().endsWith("1"))
                    service = "Radio 1";
                List<Lit> liste_lits = getLitByUF(service);
                for (Lit buff_lit : liste_lits) {
                    if (!buff_lit.getOccupe()) {
                        lit = buff_lit;
                    }
                }
                newMouvement(getAdmissionByIep(iep), lit, getUniteFontionnelleByNom(service), date);
                System.out.println("nouvelle admission ajoute");
            }
        }
    } catch (Exception e) {
        System.out.println("Erreur de lecture du fichier d'admission");
    }
}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

public void XMLParser(SimpleNode astNode) {

    // Creamos el builder basado en SAX  
    SAXBuilder builder = new SAXBuilder();

    Element segmento = inicializaKDM(archivo);

    trataNodo(astNode, segmento, 0, "");

    trataNodo2(astNode, segmento, 0, 0, "");

    //logger.info(elementoToString(segmento));
    System.out.println(elementoToString(segmento));

}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

private Element inicializaKDM(String segmentName) {

    // Creamos el builder basado en SAX
    SAXBuilder builder = new SAXBuilder();

    Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");
    Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    Namespace action = Namespace.getNamespace("action", "http://kdm.omg.org/action");
    Namespace code = Namespace.getNamespace("code", "http://kdm.omg.org/code");
    Namespace kdm = Namespace.getNamespace("kdm", "http://kdm.omg.org/kdm");
    Namespace source = Namespace.getNamespace("source", "http://kdm.omg.org/source");

    Element segmento = new Element("Segment", kdm);
    segmento.addNamespaceDeclaration(xmi);
    segmento.addNamespaceDeclaration(xsi);
    segmento.addNamespaceDeclaration(action);
    segmento.addNamespaceDeclaration(code);
    segmento.addNamespaceDeclaration(kdm);
    segmento.addNamespaceDeclaration(source);

    segmento.setAttribute("name", segmentName.substring(0, segmentName.indexOf('.')));

    Element modelo = new Element("model");
    modelo.setAttribute("id", "id.0", xmi);
    idCount++;/*from   w  w w .j a va 2s.c o  m*/
    modelo.setAttribute("name", segmentName.substring(0, segmentName.indexOf('.')));
    modelo.setAttribute("type", "code:CodeModel", xmi);

    Element codeElement = new Element("codeElement");
    codeElement.setAttribute("id", "id.1", xmi);
    idCount++;
    codeElement.setAttribute("name", segmentName);
    codeElement.setAttribute("type", "code:CompilationUnit", xmi);

    modelo.addContent(codeElement);

    elementoTipos = inicializaDataTypes();

    modelo.addContent(elementoTipos);

    segmento.addContent(modelo);

    return segmento;
}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

private Element inicializaDataTypes() {

    // Creamos el builder basado en SAX
    SAXBuilder builder = new SAXBuilder();

    Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");
    Namespace code = Namespace.getNamespace("code", "http://kdm.omg.org/code");

    Element model = new Element("model");
    model.setAttribute("id", "id." + idCount, xmi);
    model.setAttribute("type", "code:CodeModel", xmi);
    idCount++;//from   ww  w .  j  av a 2s .c o m

    Element codeElementP = new Element("codeElement");
    codeElementP.setAttribute("id", "id." + idCount, xmi);
    codeElementP.setAttribute("type", "code:LanguageUnit", xmi);
    idCount++;

    Element codeElementI = new Element("codeElement");

    for (int i = 0; i < dataTypes.length; i++) {

        codeElementI = new Element("codeElement");
        codeElementI.setAttribute("id", "id." + idCount, xmi);
        if (dataTypes[i].equals("Double") || dataTypes[i].equals("Long") || dataTypes[i].equals("Short")) {
            codeElementI.setAttribute("type", "code:DecimalType", xmi);
        } else if (dataTypes[i].equals("Byte")) {
            codeElementI.setAttribute("type", "code:OctetType", xmi);
        } else {
            codeElementI.setAttribute("type", "code:" + dataTypes[i] + "Type", xmi);
        }

        codeElementI.setAttribute("name", dataTypes[i]);

        if (!hsmLanguajeUnitDataType.containsKey(dataTypes[i])) {
            hsmLanguajeUnitDataType.put(dataTypes[i], idCount);
        }

        idCount++;

        codeElementP.addContent(codeElementI);

    }

    //model.addContent(codeElementP);      

    return codeElementP;

}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

private void XMLtoJavaParser() {

    // Creamos el builder basado en SAX  
    SAXBuilder builder = new SAXBuilder();

    try {/*from  w  w  w .  j  ava2  s  . com*/

        String nombreMetodo = null;
        List<String> atributos = new ArrayList<String>();
        String tipoRetorno = null;
        String nombreArchivo = null;
        String exportValue = "";
        String codigoFuente = "";
        HashMap<String, String> tipos = new HashMap<String, String>();

        // Construimos el arbol DOM a partir del fichero xml  
        Document doc = builder.build(new FileInputStream(ruta + "VBParser\\ejemplosKDM\\archivo.kdm"));
        //Document doc = builder.build(new FileInputStream("E:\\WorkspaceParser\\VBParser\\ejemplosKDM\\archivo.kdm"));    

        Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");

        XPathExpression<Element> xpath = XPathFactory.instance().compile("//codeElement", Filters.element());

        List<Element> elements = xpath.evaluate(doc);

        for (Element emt : elements) {

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:CompilationUnit") == 0) {

                nombreArchivo = emt.getAttributeValue("name").substring(0,
                        emt.getAttributeValue("name").indexOf('.'));

            }

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:LanguageUnit") == 0) {

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    tipos.put(hijo.getAttributeValue("id", xmi), hijo.getAttributeValue("name"));

                }

            }
        }

        FileOutputStream fout;

        fout = new FileOutputStream(ruta + "VBParser\\src\\cager\\parser\\test\\" + nombreArchivo + ".java");
        //fout = new FileOutputStream("E:\\WorkspaceParser\\VBParser\\src\\cager\\parser\\test\\"+nombreArchivo+".java");           
        // get the content in bytes
        byte[] contentInBytes = null;

        contentInBytes = ("package cager.parser.test;\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        contentInBytes = ("public class " + nombreArchivo + "{\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        for (Element emt : elements) {
            // System.out.println("XPath has result: " + emt.getName()+" "+emt.getAttribute("type",xmi));
            if (emt.getAttribute("type", xmi).getValue().compareTo("code:MethodUnit") == 0) {

                nombreMetodo = emt.getAttribute("name").getValue();

                if (emt.getAttribute("export") != null)
                    exportValue = emt.getAttribute("export").getValue();

                atributos = new ArrayList<String>();

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    if (hijo.getAttribute("type", xmi) != null) {

                        if (hijo.getAttribute("type", xmi).getValue().compareTo("code:Signature") == 0) {

                            List<Element> parametros = hijo.getChildren();

                            for (Element parametro : parametros) {

                                if (parametro.getAttribute("kind") == null
                                        || parametro.getAttribute("kind").getValue().compareTo("return") != 0) {
                                    atributos.add(tipos.get(parametro.getAttribute("type").getValue()) + " "
                                            + parametro.getAttributeValue("name"));
                                } else {
                                    tipoRetorno = tipos.get(parametro.getAttribute("type").getValue());
                                }

                            }

                        }
                    } else if (hijo.getAttribute("snippet") != null) {

                        codigoFuente = hijo.getAttribute("snippet").getValue();

                    }

                }

                //System.out.println("MethodUnit!! " + emt.getName()+" "+emt.getAttribute("type",xmi)+" "+emt.getAttribute("name").getValue());
                //System.out.println(emt.getAttribute("name").getValue());

                if (tipoRetorno.compareTo("Void") == 0) {
                    tipoRetorno = "void";
                }

                contentInBytes = ("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (")
                        .getBytes();

                fout.write(contentInBytes);
                fout.flush();
                int n = 0;
                for (String parametro : atributos) {

                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        contentInBytes = (" " + parametro + ",").getBytes();
                    } else {
                        contentInBytes = (" " + parametro).getBytes();
                    }

                    fout.write(contentInBytes);
                    fout.flush();
                    n++;
                }

                contentInBytes = (" ) {\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\n/* \n " + codigoFuente + " \n */\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\t}\n\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                System.out.print("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (");
                n = 0;
                for (String parametro : atributos) {
                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        System.out.print(" " + parametro + ", ");
                    } else {
                        System.out.print(" " + parametro);
                    }
                    n++;

                }
                System.out.println(" ) {");
                System.out.println("/* \n " + codigoFuente + " \n */");
                System.out.println("\t}\n");
            }

        }

        contentInBytes = ("}\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();
        fout.close();

        XPathExpression<Attribute> xp = XPathFactory.instance().compile("//@*", Filters.attribute(xmi));
        for (Attribute a : xp.evaluate(doc)) {
            a.setName(a.getName().toLowerCase());
        }

        xpath = XPathFactory.instance().compile("//codeElement/@name='testvb.cls'", Filters.element());
        Element emt = xpath.evaluateFirst(doc);
        if (emt != null) {
            System.out.println("XPath has result: " + emt.getName());
        }

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

}