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:bg.LanguageManager.java

private HashMap<String, String> readLanguageFile() {
    SAXBuilder builder = new SAXBuilder();
    HashMap<String, String> lanTextList = new HashMap<String, String>();
    Document document = new Document();
    try {/*  w  w  w  .  jav a2  s .  c om*/
        switch (this.lanSet) {
        case EN:
            document = (Document) builder.build(new File("src\\resource\\language\\en.xml"));
            break;
        case ZH_TW:
            document = (Document) builder.build(new File("src\\resource\\language\\zh-tw.xml"));
            break;
        }
    } catch (IOException | JDOMException ex) {
        Logger.getLogger(TwTextSpliterGUI.class.getName()).log(Level.SEVERE, null, ex);
        UIMessager.showError("Open language resource file failed");
        return null;
    }

    Element root_node = document.getRootElement();

    Element textfield_node = root_node.getChild(NodeCategory.TEXTFIELD.getText());
    Element msg_node = root_node.getChild(NodeCategory.MESSAGE.getText());
    Element button_node = root_node.getChild(NodeCategory.BUTTONTEXT.getText());

    addTextFieldChildrenText(lanTextList, textfield_node);
    addMsgChildrenText(lanTextList, msg_node);
    addButtonChildrenText(lanTextList, button_node);
    return lanTextList;
}

From source file:BL.Servlets.AddNode.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w.  j  av  a2 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("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;/*ww w. j  a  v  a 2  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;/*w w  w  .  ja  va2  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  av a 2 s  .c om
        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  va  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 {/* ww w  .ja v a2 s .  com*/
        //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:ca.nrc.cadc.uws.util.XmlUtil.java

License:Open Source License

/**
 * Build a XML Document from string, without schema validation
 * //from   w w w . jav  a  2  s  . co m
 * @param xml
 * @return
 * @throws IOException 
 * @throws JDOMException 
 */
public static Document buildDocument(String xml) throws JDOMException, IOException {
    SAXBuilder parser = new SAXBuilder(PARSER, false);
    return parser.build(new StringReader(xml));
}

From source file:ca.nrc.cadc.uws.util.XmlUtil.java

License:Open Source License

public static Document buildDocument(Reader reader, Map<String, String> schemaMap)
        throws IOException, JDOMException {
    SAXBuilder sb = createBuilder(schemaMap);
    return sb.build(reader);
}

From source file:ca.nrc.cadc.uws.util.XmlUtil.java

License:Open Source License

public static Document validateXml(Reader reader, Map<String, String> schemaMap)
        throws IOException, JDOMException {
    SAXBuilder builder = createBuilder(schemaMap);
    return builder.build(reader);
}