List of usage examples for org.jdom2 Document getRootElement
public Element getRootElement()
Element
for this Document
From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java
License:Apache License
/** * Create/update the schema.xml file for the given core according to the core definition. * * @param engine the engine configuration *///from ww w .j av a2 s .c om private void createSchemaXml(SolrCoreConfiguration engine) throws MarmottaException { log.info("generating schema.xml for search program {}", engine.getName()); SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING); File schemaTemplate = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "schema-template.xml"); File schemaFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "schema.xml"); try { Document doc = parser.build(schemaTemplate); Element schemaNode = doc.getRootElement(); Element fieldsNode = schemaNode.getChild("fields"); if (!schemaNode.getName().equals("schema") || fieldsNode == null) throw new MarmottaException(schemaTemplate + " is an invalid SOLR schema file"); schemaNode.setAttribute("name", engine.getName()); Program<Value> program = engine.getProgram(); for (FieldMapping<?, Value> fieldMapping : program.getFields()) { String fieldName = fieldMapping.getFieldName(); String solrType = null; try { solrType = solrProgramService.getSolrFieldType(fieldMapping.getFieldType().toString()); } catch (MarmottaException e) { solrType = null; } if (solrType == null) { log.error("field {} has an invalid field type; ignoring field definition", fieldName); continue; } Element fieldElement = new Element("field"); fieldElement.setAttribute("name", fieldName); fieldElement.setAttribute("type", solrType); // Set the default properties fieldElement.setAttribute("stored", "true"); fieldElement.setAttribute("indexed", "true"); fieldElement.setAttribute("multiValued", "true"); // FIXME: Hardcoded Stuff! if (solrType.equals("location")) { fieldElement.setAttribute("indexed", "true"); fieldElement.setAttribute("multiValued", "false"); } // Handle extra field configuration final Map<String, String> fieldConfig = fieldMapping.getFieldConfig(); if (fieldConfig != null) { for (Map.Entry<String, String> attr : fieldConfig.entrySet()) { if (SOLR_FIELD_OPTIONS.contains(attr.getKey())) { fieldElement.setAttribute(attr.getKey(), attr.getValue()); } } } fieldsNode.addContent(fieldElement); if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_COPY_FIELD_OPTION)) { String[] copyFields = fieldConfig.get(SOLR_COPY_FIELD_OPTION).split("\\s*,\\s*"); for (String copyField : copyFields) { if (copyField.trim().length() > 0) { // ignore 'empty' fields Element copyElement = new Element("copyField"); copyElement.setAttribute("source", fieldName); copyElement.setAttribute("dest", copyField.trim()); schemaNode.addContent(copyElement); } } } else { Element copyElement = new Element("copyField"); copyElement.setAttribute("source", fieldName); copyElement.setAttribute("dest", "lmf.text_all"); schemaNode.addContent(copyElement); } //for suggestions, copy all fields to lmf.spellcheck (used for spellcheck and querying); //only facet is a supported type at the moment if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) { String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION); if (suggestionType.equals("facet")) { Element copyElement = new Element("copyField"); copyElement.setAttribute("source", fieldName); copyElement.setAttribute("dest", "lmf.spellcheck"); schemaNode.addContent(copyElement); } else { log.error("suggestionType " + suggestionType + " not supported"); } } } if (!schemaFile.exists() || schemaFile.canWrite()) { FileOutputStream out = new FileOutputStream(schemaFile); XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent(" ")); xo.output(doc, out); out.close(); } else { log.error("schema file {} is not writable", schemaFile); } } catch (JDOMException e) { throw new MarmottaException("parse error while parsing SOLR schema template file " + schemaTemplate, e); } catch (IOException e) { throw new MarmottaException("I/O error while parsing SOLR schema template file " + schemaTemplate, e); } }
From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java
License:Apache License
/** * Create/update the solrconfig.xml file for the given core according to the core configuration. * * @param engine the solr core configuration *//*from w w w . j av a 2s. c om*/ private void createSolrConfigXml(SolrCoreConfiguration engine) throws MarmottaException { File configTemplate = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "solrconfig-template.xml"); File configFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "solrconfig.xml"); try { SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING); Document solrConfig = parser.build(configTemplate); FileOutputStream out = new FileOutputStream(configFile); // Configure suggestion service: add fields to suggestion handler Program<Value> program = engine.getProgram(); for (Element handler : solrConfig.getRootElement().getChildren("requestHandler")) { if (handler.getAttribute("class").getValue().equals(SuggestionRequestHandler.class.getName())) { for (Element lst : handler.getChildren("lst")) { if (lst.getAttribute("name").getValue().equals("defaults")) { //set suggestion fields for (FieldMapping<?, Value> fieldMapping : program.getFields()) { String fieldName = fieldMapping.getFieldName(); final Map<String, String> fieldConfig = fieldMapping.getFieldConfig(); if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) { String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION); if (suggestionType.equals("facet")) { Element field_elem = new Element("str"); field_elem.setAttribute("name", SuggestionRequestParams.SUGGESTION_FIELD); field_elem.setText(fieldName); lst.addContent(field_elem); } else { log.error("suggestionType " + suggestionType + " not supported"); } } } } } } } XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent(" ")); xo.output(solrConfig, out); out.close(); } catch (JDOMException e) { throw new MarmottaException("parse error while parsing SOLR schema template file " + configTemplate, e); } catch (IOException e) { throw new MarmottaException("I/O error while parsing SOLR schema template file " + configTemplate, e); } }
From source file:at.newmedialab.lmf.util.geonames.builder.GeoLookupImpl.java
License:Apache License
/** * Query the geonames-api for a place with the provided name. * @param name the name of the place to lookup at geonames * @return the URI of the resolved place, or null if no such place exists. */// ww w. j a v a2s . co m private String queryPlace(String name) { if (StringUtils.isBlank(name)) return null; StringBuilder querySB = new StringBuilder(); queryStringAppend(querySB, "q", name); queryStringAppend(querySB, "countryBias", countryBias); for (char fc : featureClasses) { queryStringAppend(querySB, "featureClass", String.valueOf(fc)); } for (String fc : featureCodes) { queryStringAppend(querySB, "featureCode", fc); } for (String c : countries) { queryStringAppend(querySB, "country", c); } for (String cc : continentCodes) { queryStringAppend(querySB, "continentCode", cc); } if (fuzzy < 1) { queryStringAppend(querySB, "fuzzy", String.valueOf(fuzzy)); } queryStringAppend(querySB, "maxRows", "1"); queryStringAppend(querySB, "type", "xml"); queryStringAppend(querySB, "isNameRequired", "true"); queryStringAppend(querySB, "style", "short"); if (StringUtils.isNotBlank(geoNamesUser)) queryStringAppend(querySB, "username", geoNamesUser); if (StringUtils.isNotBlank(geoNamesPasswd)) queryStringAppend(querySB, "password", geoNamesPasswd); final String url = geoNamesUrl + "search?" + querySB.toString(); HttpGet get = new HttpGet(url); try { return http.execute(get, new ResponseHandler<String>() { /** * Parses the xml-response from the geonames webservice and build the uri for the result * @return the URI of the resolved place, or null if no place was found. */ @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { final int statusCode = response.getStatusLine().getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { return null; } try { SAXBuilder builder = new SAXBuilder(); final HttpEntity entity = response.getEntity(); if (entity == null) throw new ClientProtocolException("Body Required"); final Document doc = builder.build(entity.getContent()); final Element root = doc.getRootElement(); final Element status = root.getChild("status"); if (status != null) { final int errCode = Integer.parseInt(status.getAttributeValue("value")); if (errCode == 15) { // NO RESULT should not be an exception return null; } throw new GeoNamesException(errCode, status.getAttributeValue("message")); } final Element gName = root.getChild("geoname"); if (gName == null) return null; final String geoId = gName.getChildTextTrim("geonameId"); if (geoId == null) return null; return String.format(GEONAMES_URI_PATTERN, geoId); } catch (NumberFormatException e) { throw new ClientProtocolException(e); } catch (IllegalStateException e) { throw new ClientProtocolException(e); } catch (JDOMException e) { throw new IOException(e); } } }); } catch (GeoNamesException e) { log.debug("Lookup at GeoNames failed: {} ({})", e.getMessage(), e.getErrCode()); } catch (ClientProtocolException e) { log.error("Could not query geoNames: " + e.getLocalizedMessage(), e); } catch (IOException e) { log.error("Could not query geoNames: " + e.getLocalizedMessage(), e); } return null; }
From source file:backtesting.BackTesterNinety.java
public static boolean CheckBacktestSettingsInCache(LocalDate startDate, LocalDate endDate) { try {//w w w . ja va2s . c om File inputFile = new File("backtest/cache/_settings.xml"); if (!inputFile.exists()) { return false; } SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); Element rootElement = document.getRootElement(); Attribute attStart = rootElement.getAttribute("start"); LocalDate start = LocalDate.parse(attStart.getValue()); Attribute attEnd = rootElement.getAttribute("end"); LocalDate end = LocalDate.parse(attEnd.getValue()); return startDate.isEqual(start) && endDate.isEqual(end); } catch (JDOMException e) { e.printStackTrace(); logger.severe("Error in loading from XML: JDOMException.\r\n" + e); } catch (IOException ioe) { ioe.printStackTrace(); logger.severe("Error in loading from XML: IOException.\r\n" + ioe); } return false; }
From source file:bg.LanguageManager.java
private HashMap<String, String> readLanguageFile(Language lan) { SAXBuilder builder = new SAXBuilder(); HashMap<String, String> lanTextList = new HashMap<String, String>(); Document document = new Document(); try {//from w ww . j a va2s.c om switch (lan) { 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: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 ww . j a va 2 s . c o m*/ 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.//w w w . java 2 s .c om * * @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; try {/* w w w. j a v a 2 s . c o m*/ 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; try {/*from w w w.j a v a2s.c o m*/ 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; SAXBuilder builder = new SAXBuilder(); Path path = Paths.get("c:/unimake/uninfe/" + pasta + "/Retorno"); WatchService watchService = null; try {/*from ww w . j a v a 2 s . c om*/ 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; } } } }