List of usage examples for org.dom4j Element attribute
Attribute attribute(QName qName);
From source file:com.doculibre.constellio.services.SolrServicesImpl.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from w ww . j a v a 2s. c o m*/ public void updateDismax(RecordCollection collection) { ensureCore(collection); Element dismaxElement = getDismaxElement(collection); Document solrConfigDocument = readSolrConfig(collection); Element root = solrConfigDocument.getRootElement(); boolean defaultSearchFieldFound = false; // 1. keep only one requestHandler with name DISMAX_ATTRIBUTE_NAME for (Iterator<Element> it = root.elementIterator("requestHandler"); it.hasNext();) { Element currentRequestHandlerElement = it.next(); String currentSearchComponentName = currentRequestHandlerElement.attribute("name").getText(); if (currentSearchComponentName.equals(DISMAX_ATTRIBUTE_NAME)) { // first copy other fields that are not defaults if the // query was set as default if (!defaultSearchFieldFound) { Attribute defaultAttribute = currentRequestHandlerElement.attribute("default"); if (defaultAttribute != null && defaultAttribute.getText().equals("true")) { defaultSearchFieldFound = true; defaultAttribute.setText("false"); List<Element> elements = currentRequestHandlerElement.elements(); for (Element element : elements) { if (element.attribute("name") != null && !element.attribute("name").getValue().equals("defaults")) { BaseElement cloneElement = new BaseElement(element.getName()); cloneElement.appendAttributes(element); cloneElement.appendContent(element); dismaxElement.add(cloneElement); } } } } it.remove(); } } if (!defaultSearchFieldFound) { // 2. add the parameters of the default RequestHandler to dismax // requestHandler (escape the parameter with name="defaults") for (Iterator<Element> it = root.elementIterator("requestHandler"); it.hasNext();) { Element currentRequestHandlerElement = it.next(); Attribute defaultAttribute = currentRequestHandlerElement.attribute("default"); if (defaultAttribute != null && defaultAttribute.getText().equals("true")) { defaultAttribute.setText("false"); List<Element> elements = currentRequestHandlerElement.elements(); for (Element element : elements) { if (element.attribute("name") != null && !element.attribute("name").getValue().equals("defaults")) { BaseElement cloneElement = new BaseElement(element.getName()); cloneElement.appendAttributes(element); cloneElement.appendContent(element); dismaxElement.add(cloneElement); } } break; } } } root.add(dismaxElement); writeSolrConfig(collection, solrConfigDocument); initCore(collection); }
From source file:com.doculibre.constellio.services.SolrServicesImpl.java
License:Open Source License
@SuppressWarnings("unchecked") @Override//from ww w. j a v a 2 s. co m public boolean usesDisMax(RecordCollection collection) { ensureCore(collection); Document solrconfigXmlDocument = readSolrConfig(collection); Element root = solrconfigXmlDocument.getRootElement(); for (Iterator<Element> it = root.elementIterator("requestHandler"); it.hasNext();) { Element currentRequestHandlerElement = it.next(); String currentSearchComponentName = currentRequestHandlerElement.attribute("name").getText(); if (currentSearchComponentName.equals(DISMAX_ATTRIBUTE_NAME)) { return true; } } return false; }
From source file:com.doculibre.constellio.utils.izpack.UsersXmlFileUtils.java
License:Open Source License
@SuppressWarnings("unchecked") private static ConstellioUser toConstellioUser(Element element) { ConstellioUser constellioUser = new ConstellioUser(); constellioUser.setFirstName(element.attributeValue(FIRST_NAME)); constellioUser.setLastName(element.attributeValue(LAST_NAME)); constellioUser.setUsername(element.attributeValue(LOGIN)); constellioUser.setPasswordHash(element.attributeValue(PASSWORD_HASH)); Attribute locale = element.attribute(LOCALE); if (locale != null) { constellioUser.setLocaleCode(locale.getValue()); } else {//ww w .ja v a2 s. co m constellioUser.setLocale(ConstellioSpringUtils.getDefaultLocale()); } Iterator<Element> rolesIt = element.elementIterator(ROLES); if (rolesIt != null) { Element roles = rolesIt.next(); for (Iterator<Element> it = roles.elementIterator(ROLE); it.hasNext();) { Element currentRole = it.next(); constellioUser.addRole(currentRole.attributeValue(VALUE)); } } return constellioUser; }
From source file:com.dp2345.util.SettingUtils.java
License:Open Source License
/** * /*from w w w .j ava2 s .co m*/ * * @param setting * */ public static void set(Setting setting) { try { File dp2345XmlFile = new ClassPathResource(CommonAttributes.DP2345_XML_PATH).getFile(); Document document = new SAXReader().read(dp2345XmlFile); List<Element> elements = document.selectNodes("/dp2345/setting"); for (Element element : elements) { try { String name = element.attributeValue("name"); String value = beanUtils.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); fileOutputStream = new FileOutputStream(dp2345XmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } IOUtils.closeQuietly(fileOutputStream); } Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.dsh105.nexus.command.module.information.WolframAlphaCommand.java
License:Open Source License
@Override public boolean onCommand(CommandPerformEvent event) { if (event.getArgs().length == 0) { return false; }/* w w w . j a v a 2s . com*/ String apiKey = Nexus.getInstance().getConfig().getWolframAlphaKey(); if (apiKey.isEmpty()) { event.errorWithPing("Failed to query WolframAlpha - API key has not been configured."); Nexus.LOGGER.warning("User attempted to access WolframAlpha - API key is invalid!"); return true; } String input = StringUtil.combineSplit(0, event.getArgs(), " "); StringBuilder answer = new StringBuilder(); try { String apiUrl = String.format(API_URL, URLEncoder.encode(input, "UTF-8"), apiKey); Nexus.LOGGER.info("Requesting WolframAlpha interpretation at " + apiUrl); SAXReader reader = new SAXReader(); Document document = reader.read(Unirest.get(apiUrl).asBinary().getBody()); Element root = document.getRootElement(); if (Boolean.valueOf(root.attribute("success").getValue())) { for (Iterator pods = root.elementIterator("pod"); pods.hasNext();) { Element pod = (Element) pods.next(); String primary = pod.attributeValue("primary"); if (primary != null && Boolean.valueOf(primary)) { for (Iterator subpods = pod.elementIterator("subpod"); subpods.hasNext();) { Element subpod = (Element) subpods.next(); String result = subpod.element("plaintext").getText(); if (result != null && !result.isEmpty()) { answer.append(result.replaceAll("\\n", " - ").replaceAll("\\s+", " ")); } } } } if (answer.length() > 0) { event.respondWithPing( answer + " (" + URLShortener.shorten(String.format(QUERY_URL, input)) + ")"); return true; } } List<String> tips = new ArrayList<>(); if (root.element("tips") != null) { for (Iterator tipElements = root.element("tips").elementIterator("tip"); tipElements.hasNext();) { if (tips.size() > 3) { break; } Element tip = (Element) tipElements.next(); String result = tip.attributeValue("text"); if (result != null && !result.isEmpty()) { tips.add(result.replaceAll("\\s+", " ")); } } } event.errorWithPing("WolframAlpha could not interpret that!"); if (!tips.isEmpty()) { event.errorWithPing(Colors.BOLD + "Tips" + Colors.BOLD + ": " + StringUtil.combineSplit(0, tips.toArray(new String[tips.size()]), "; ")); } return true; } catch (UnirestException e) { throw new WolframAlphaQueryException("Failed to execute WolframAlpha query: " + input, e); } catch (DocumentException e) { throw new WolframAlphaQueryException("Failed to execute WolframAlpha query: " + input, e); } catch (UnsupportedEncodingException e) { throw new WolframAlphaQueryException("Failed to encode URL", e); } }
From source file:com.erpak.jtrackplanner3d.xml.LibraryReader.java
License:Open Source License
/** * create a new LibraryReader object with the library file name * @param fileName Name of the library file *///from w w w.j a va 2 s . c om public LibraryReader(File libraryFile) { TrackSystem trackSystem = null; TracksTreeCellRenderer renderer = new TracksTreeCellRenderer(); try { renderer.setStraigthTrackIcon(new ImageIcon(ResourcesManager.getResource("StraigthTrackIcon"))); renderer.setCurvedTrackIcon(new ImageIcon(ResourcesManager.getResource("CurvedTrackIcon"))); renderer.setStraightTurnoutTrackIcon( new ImageIcon(ResourcesManager.getResource("StraigthTurnoutTrackIcon"))); renderer.setCrossingTrackIcon(new ImageIcon(ResourcesManager.getResource("CrossingTrackIcon"))); } catch (Exception ex) { logger.error("Unable to load tree node icons"); logger.error(ex.toString()); } try { Element trackSystemInfoNode; Element element; Element subElement; Attribute attribute; Iterator iter; DefaultMutableTreeNode treeTop; DefaultMutableTreeNode treeCategory; DefaultMutableTreeNode treeElement; // Load the xml library file InputStream in = new FileInputStream(libraryFile); EntityResolver resolver = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { logger.debug("Public id : " + publicId); logger.debug("System Id : " + systemId); if (publicId.equals("-//TrackPlanner//DTD track_system V 1.0//EN")) { InputStream in = getClass().getResourceAsStream("ressources/track_system.dtd"); return new InputSource(in); } return null; } }; SAXReader reader = new SAXReader(); reader.setEntityResolver(resolver); // Read the xml library file Document document = reader.read(in); Element root = document.getRootElement(); logger.debug("Root name : " + root.getName()); // Get "track_system_info" node trackSystemInfoNode = root.element("track_system_infos"); // Get track_system_info_node attributes trackSystem = new TrackSystem(trackSystemInfoNode.attribute("name").getValue(), trackSystemInfoNode.attribute("version").getValue()); trackSystem.setScale(trackSystemInfoNode.attribute("scale").getValue()); trackSystem.setManufacturer(trackSystemInfoNode.attribute("manufacturer").getValue()); // Get the "track_system_caracteristics" node element = trackSystemInfoNode.element("track_system_caracteristics"); trackSystem.setBallastWidth(Float.parseFloat(element.attribute("ballast_width").getValue())); trackSystem.setTrackWidth(Float.parseFloat(element.attribute("railway_width").getValue())); // Get the "track_system_colors" node element = trackSystemInfoNode.element("track_system_colors"); for (iter = element.elementIterator(); iter.hasNext();) { subElement = (Element) iter.next(); trackSystem.addColor(subElement.attribute("name").getValue(), subElement.attribute("r").getValue(), subElement.attribute("g").getValue(), subElement.attribute("b").getValue()); } // Set the top node of tree with tracksystem treeTop = new DefaultMutableTreeNode(trackSystem.getName()); // iterate "straight_tracks" node element = root.element("straight_tracks"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (iter = element.elementIterator("straight_track"); iter.hasNext();) { subElement = (Element) iter.next(); logger.debug("Adding reference : " + subElement.attribute("reference").getValue()); treeElement = new DefaultMutableTreeNode(new StraightTrackSymbol(trackSystem, subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), Float.parseFloat(subElement.attribute("length").getValue()), subElement.attribute("color").getValue())); treeCategory.add(treeElement); } // iterate "curved_tracks" node element = root.element("curved_tracks"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (iter = element.elementIterator("curved_track"); iter.hasNext();) { subElement = (Element) iter.next(); logger.debug("Adding reference : " + subElement.attribute("reference").getValue()); treeElement = new DefaultMutableTreeNode(new CurvedTrackSymbol(trackSystem, subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), Float.parseFloat(subElement.attribute("radius").getValue()), Float.parseFloat(subElement.attribute("angle").getValue()), subElement.attribute("color").getValue())); treeCategory.add(treeElement); } // iterate "straight_turnouts" node element = root.element("straight_turnouts"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (iter = element.elementIterator("straight_turnout"); iter.hasNext();) { subElement = (Element) iter.next(); logger.debug("Adding reference : " + subElement.attribute("reference").getValue()); treeElement = new DefaultMutableTreeNode(new StraightTurnoutSymbol(trackSystem, subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), Float.parseFloat(subElement.attribute("length").getValue()), Float.parseFloat(subElement.attribute("radius").getValue()), Float.parseFloat(subElement.attribute("angle").getValue()), subElement.attribute("direction").getValue(), subElement.attribute("color").getValue())); treeCategory.add(treeElement); } // iterate through "curved_turnouts" node element = root.element("curved_turnouts"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (Iterator i = root.elementIterator("curved_turnouts"); i.hasNext();) { element = (Element) i.next(); logger.debug("Node : " + element.getName()); } // iterate through "three_way_turnouts" node element = root.element("three_way_turnouts"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (iter = element.elementIterator("symetric_three_way_turnout"); iter.hasNext();) { subElement = (Element) iter.next(); logger.debug("Adding reference : " + subElement.attribute("reference").getValue()); treeElement = new DefaultMutableTreeNode(new SymetricThreeWayTurnoutSymbol(trackSystem, subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), subElement.attribute("reference").getValue(), Float.parseFloat(subElement.attribute("length").getValue()), Float.parseFloat(subElement.attribute("radius").getValue()), Float.parseFloat(subElement.attribute("angle").getValue()), subElement.attribute("color").getValue())); treeCategory.add(treeElement); } // iterate through "crossings" node element = root.element("crossings"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (Iterator i = root.elementIterator("crossings"); i.hasNext();) { element = (Element) i.next(); logger.debug("Node : " + element.getName()); } // iterate through "double_slip_switchs" node element = root.element("double_slip_switchs"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (Iterator i = root.elementIterator("double_slip_switchs"); i.hasNext();) { element = (Element) i.next(); logger.debug("Node : " + element.getName()); } // iterate through "special_tracks" node element = root.element("special_tracks"); treeCategory = new DefaultMutableTreeNode(element.getName()); treeTop.add(treeCategory); logger.debug("Node : " + element.getName()); for (Iterator i = root.elementIterator("special_tracks"); i.hasNext();) { element = (Element) i.next(); logger.debug("Node : " + element.getName()); } // fill the tree tree = new JTree(treeTop); } catch (Exception ex) { logger.error("Unable to load track trackSystem library", ex); // Todo : Throws an exception and display an error box instaed of displaying atree with scrap data tree = new JTree(); } logger.debug("Parsing done for trackSystem : " + trackSystem); tree.setName("Track systems"); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setCellRenderer(renderer); }
From source file:com.eurelis.opencms.workflows.workflows.A_OSWorkflowManager.java
License:Open Source License
/** * Get the OpenCMS RFS OSWorkflow configuration file and update it with the given filepath. * /*from w w w. j a v a 2s.c o m*/ * @param listOfWorkflowsFilepath * the path of the file containing the list of available workflow descriptions * @return the path in RFS of the updated file * @throws DocumentException * this exception is thrown if an error occurs during the parsing of the document * @throws IOException * this exception is thrown if a problem occurs during overwriting of the config file */ private String updateOSWorkflowConfigFile(String listOfWorkflowsFilepath) throws CmsException, DocumentException, IOException { // get file path String configFilePath = this.getWebINFPath() + ModuleSharedVariables.SYSTEM_FILE_SEPARATOR + OSWORKFLOWCONFIGFILE_RFSFILEPATH; File listOfWorkflowsFile = new File(listOfWorkflowsFilepath); // Load Jdom parser SAXReader reader = new SAXReader(); Document document = reader.read(configFilePath); Node propertyNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH); if (propertyNode != null) { if (propertyNode.getNodeType() == Node.ELEMENT_NODE) { // convert Node into element Element propertyElement = (Element) propertyNode; // update the Attribute Attribute valueAttribute = propertyElement .attribute(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_ATTRIBUTNAME); valueAttribute.setValue(listOfWorkflowsFile.toURI().toString()); } else { LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH + " in the file " + configFilePath + " doesn't correspond to an element"); } } else { Node parentNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH); if (parentNode != null) { if (parentNode.getNodeType() == Node.ELEMENT_NODE) { // convert Node into element Element parentElement = (Element) parentNode; // add new property Element propertyElement = parentElement.addElement("property"); // add attributs propertyElement.addAttribute("key", "resource"); propertyElement.addAttribute("value", listOfWorkflowsFile.toURI().toString()); } else { LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH + " in the file " + configFilePath + " doesn't correspond to an element"); } } else { LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH + " in the file " + configFilePath + " has not been found."); } } /* * Get a string of the resulting file */ // creating of a buffer that will collect result ByteArrayOutputStream xmlContent = new ByteArrayOutputStream(); // Pretty print the document to xmlContent OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(xmlContent, format); writer.write(document); writer.flush(); writer.close(); // get the config file content as a String String documentContent = new String(xmlContent.toByteArray()); /* * Overwrite the config file */ FileWriter.writeFile(configFilePath, documentContent); return configFilePath; }
From source file:com.feilong.tools.dom4j.Dom4jUtil.java
License:Apache License
/** * elemenet ./*from ww w . j av a 2s . co m*/ * * @param element * element * @param attributeName * ?? * @return the attribute value */ public static String getAttributeValue(Element element, String attributeName) { if (Validator.isNullOrEmpty(element)) { log.warn("element is null"); return null; } Attribute attribute = element.attribute(attributeName); if (Validator.isNullOrEmpty(attribute)) { log.warn("element has no attribute which named:{}", attributeName); return null; } String text = attribute.getText(); return text; }
From source file:com.flaptor.hounder.util.HtmlParser.java
License:Apache License
@SuppressWarnings("unchecked") private void extractLinks(Document htmlDoc, Output out) { List links = htmlDoc.selectNodes("//A"); for (Iterator iter = links.iterator(); iter.hasNext();) { Element link = (Element) iter.next(); Attribute href = link.attribute("href"); if (null != href) { try { out.addLink(href.getValue(), link.getText()); } catch (Exception e) { logger.warn("Exception occurred, ignoring link " + link.getText() + " at " + href.getValue(), e);/*from w ww . j a v a 2s .c om*/ } } } }
From source file:com.flaptor.util.parser.HtmlParser.java
License:Apache License
@SuppressWarnings("unchecked") private void extractLinks(Document htmlDoc, ParseOutput out) { try {/*w w w . ja v a 2s .co m*/ Node baseNode = htmlDoc.selectSingleNode("//BASE|//Base|//base"); if (null != baseNode) { Attribute href = ((Element) baseNode).attribute("href"); if (null == href) { href = ((Element) baseNode).attribute("HREF"); if (null == href) { href = ((Element) baseNode).attribute("Href"); } } if (null != href) { String base = href.getValue(); if (null != base) { out.setBaseUrl(base); } } } List links = htmlDoc.selectNodes("//A|//a"); for (Iterator iter = links.iterator(); iter.hasNext();) { Element link = (Element) iter.next(); Attribute href = link.attribute("href"); if (null != href) { try { out.addLink(href.getValue(), link.getText()); } catch (URISyntaxException e) { logger.debug( "Exception occurred, ignoring link " + link.getText() + " at " + href.getValue(), e); } } } } catch (URISyntaxException e) { logger.debug("Exception occurred, ignoring links in " + out.getUrl(), e); } }