List of usage examples for org.dom4j Element getTextTrim
String getTextTrim();
From source file:com.heren.turtle.server.utils.XmlUtils.java
License:Open Source License
/** * delete the label of xml that is not use * * @param message//from w w w . j ava2 s. c om * @return */ public static Map<String, Object> getMessageContainsMap(String message) throws DocumentException { message = replaceWrongPart(message); Document document = DocumentHelper.parseText(message); Element rootElement = document.getRootElement(); Element request = rootElement.element("request"); List elements = request.elements(); Map<String, Object> result = new HashMap<>(); for (Object element : elements) { Element subElement = (Element) element; if (subElement.isTextOnly()) { result.put(subElement.getName(), subElement.getTextTrim()); } else { List<Map<String, String>> subList = new ArrayList<>(); List subEle = subElement.elements(); for (Object aSubEle : subEle) { Element itemElements = (Element) aSubEle; Map<String, String> subMap = new HashMap<>(); List grandSubElements = itemElements.elements(); for (Object grandSubElement : grandSubElements) { Element grandItemElements = (Element) grandSubElement; subMap.put(grandItemElements.getName().trim(), grandItemElements.getTextTrim()); } subList.add(subMap); } result.put(subElement.getName(), subList); } } return result; }
From source file:com.iisigroup.cap.utils.CapXmlUtil.java
License:Open Source License
@SuppressWarnings("unchecked") private static JSONObject travelXML(Element el) { JSONObject json = new JSONObject(); String nodeName = el.getName(); if (el.elements().isEmpty()) { putJSONValue(json, nodeName, el.getTextTrim()); } else {//from w w w . j a v a 2s . c o m JSONObject json2 = new JSONObject(); for (Element el2 : (List<Element>) el.elements()) { putJSONValue(json2, el2.getName(), travelXML(el2).get(el2.getName())); } putJSONValue(json, nodeName, json2); } return json; }
From source file:com.jeeframework.util.xml.XMLProperties.java
License:Open Source License
/** * Returns the value of the specified property. * * @param name the name of the property to get. * @param ignoreEmpty Ignore empty property values (return null) * @return the value of the specified property. *///w ww .ja va 2 s . c om public synchronized String getProperty(String name, boolean ignoreEmpty) { String value = propertyCache.get(name); if (value != null) { return value; } String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML hierarchy. Element element = document.getRootElement(); for (String aPropName : propName) { element = element.element(aPropName); if (element == null) { // This node doesn't match this part of the property name which // indicates this property doesn't exist so return null. return null; } } // At this point, we found a matching property, so return its value. // Empty strings are returned as null. value = element.getTextTrim(); if (ignoreEmpty && "".equals(value)) { return null; } else { // check to see if the property is marked as encrypted Attribute encrypted = element.attribute(ENCRYPTED_ATTRIBUTE); if (encrypted != null) { value = EncryptUtil.desDecrypt(encryptKey, value); } // else { // // rewrite property as an encrypted value // Log.info("Rewriting XML property " + name + " as an encrypted value"); // setProperty(name, value, false); // } // Add to cache so that getting property next time is fast. propertyCache.put(name, value); return value; } }
From source file:com.jeeframework.util.xml.XMLProperties.java
License:Open Source License
/** * Return all values who's path matches the given property * name as a String array, or an empty array if the if there * are no children. This allows you to retrieve several values * with the same property name. For example, consider the * XML file entry:/*from w ww . ja va 2s .c om*/ * <pre> * <foo> * <bar> * <prop>some value</prop> * <prop>other value</prop> * <prop>last value</prop> * </bar> * </foo> * </pre> * If you call getProperties("foo.bar.prop") will return a string array containing * {"some value", "other value", "last value"}. * * @param name the name of the property to retrieve * @return all child property values for the given node name. */ public List<String> getProperties(String name, boolean asList) { List<String> result = new ArrayList<String>(); String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML hierarchy, // stopping one short. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { element = element.element(propName[i]); if (element == null) { // This node doesn't match this part of the property name which // indicates this property doesn't exist so return empty array. return result; } } // We found matching property, return names of children. Iterator<Element> iter = element.elementIterator(propName[propName.length - 1]); Element prop; String value; boolean updateEncryption = false; while (iter.hasNext()) { prop = iter.next(); // Empty strings are skipped. value = prop.getTextTrim(); if (!"".equals(value)) { // check to see if the property is marked as encrypted Attribute encrypted = prop.attribute(ENCRYPTED_ATTRIBUTE); if (encrypted != null) { value = EncryptUtil.desDecrypt(encryptKey, value); } else { // rewrite property as an encrypted value prop.addAttribute(ENCRYPTED_ATTRIBUTE, "true"); updateEncryption = true; } result.add(value); } } if (updateEncryption) { Log.info("Rewriting values for XML property " + name + " using encryption"); saveProperties(); } return result; }
From source file:com.jiusit.onePurchase.pay.Pay.java
License:Open Source License
public static Map<String, String> xml2Map(String xml) { Map<String, String> map = new HashMap<String, String>(); try {/* w w w. j a v a2s . c o m*/ Document document = DocumentHelper.parseText(xml); Element root = document.getRootElement(); for (Iterator it = root.elementIterator(); it.hasNext();) { Element element = (Element) it.next(); map.put(element.getName(), element.getTextTrim()); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; }
From source file:com.jonschang.investing.stocks.service.YahooHistoricalStockQuoteService.java
License:LGPL
private void pullKeyEventData(String urlString, Stock stock, BusinessCalendar cal, TimeInterval interval, DateRange range, Map<Date, StockQuote> dateToQuoteMap) throws Exception { URL url = getDateYearsUrl(urlString, stock.getSymbol(), range.getStart(), range.getEnd()); SAXReader reader = new SAXReader(); Document doc = reader.read(url.openConnection().getInputStream()); Element rootElement = doc.getRootElement(); // ok, so the date range specifiable to the keyevents service is not very fine-grained, // therefore, we'll assume that if there are any StockEvent's at all in a StockQuote, // that we pulled them here at an earlier call. List<Element> seriesList = rootElement.elements("series"); if (seriesList.size() != 1) throw new ServiceException( "Expecting only a single 'series' tag in the XML document returned from " + url.toURI()); Element series = seriesList.get(0); List<Element> valuesList = series.elements("values"); if (valuesList.size() != 1) throw new ServiceException( "Expecting only a single 'values' tag in the XML document returned from " + url.toURI()); List<Element> values = valuesList.get(0).elements("value"); int type = 0; if (urlString.compareTo(m_splitUrl) == 0) type = 1; // split else if (urlString.compareTo(m_dividendUrl) == 0) type = 2; // dividend StockEventSplit split = null;//from ww w . j a v a 2s . c o m StockEventDividend div = null; List<Element> ps = series.elements("p"); for (Element p : ps) { if (urlString.compareTo(m_splitUrl) == 0) split = new StockEventSplit(); else if (urlString.compareTo(m_dividendUrl) == 0) div = new StockEventDividend(); List<Element> theseValues = p.elements("v"); if (theseValues.size() != values.size()) throw new ServiceException("Expecting the number of 'v' tags to match the number of 'values'"); Date vDate = new SimpleDateFormat("yyyyMMdd").parse(p.attribute("ref").getText()); cal.setTimeInMillis(vDate.getTime()); cal.normalizeToInterval(interval); vDate = cal.getTime(); StockQuote quote = dateToQuoteMap.get(vDate); if (quote == null) continue; if (quote.getStockEvents() != null && !((type == 1 && stockEventsHas(StockEventSplit.class, quote.getStockEvents())) || (type == 2 && stockEventsHas(StockEventDividend.class, quote.getStockEvents())))) continue; List<StockEvent> events = quote.getStockEvents(); if (events == null) { events = new ArrayList<StockEvent>(); quote.setStockEvents(events); } int idx = 0; for (Element v : theseValues) { Element value = values.get(idx); if (value.attribute("id").getText().compareTo("denominator") == 0) { split.setDenominator(Double.valueOf(v.getTextTrim()).floatValue()); } else if (value.attribute("id").getText().compareTo("numerator") == 0) { split.setNumerator(Double.valueOf(v.getTextTrim()).floatValue()); } else if (value.attribute("id").getText().compareTo("dividend") == 0) { div.setDividend(Double.valueOf(v.getTextTrim())); } idx++; } // split if (type == 1) { split.setStockQuote(quote); events.add(split); } else // dividend if (type == 2) { div.setStockQuote(quote); events.add(div); } } }
From source file:com.liferay.alloy.tools.builder.faces.FacesBuilder.java
License:Open Source License
private void _buildTaglibXMLFile(List<Component> components, Map<String, Object> context) throws Exception { context.put("components", components); context.put("version", PropsUtil.getString("builder.faces.version")); for (Document doc : getComponentDefinitionDocs()) { Element root = doc.getRootElement(); Element descriptionElement = root.element("description"); String description = null; if (descriptionElement != null) { description = descriptionElement.getTextTrim(); }/*from ww w .j av a2 s .co m*/ context.put("description", description); Element extensionElement = root.element("extension"); if (extensionElement != null) { List<Element> extensionElements = extensionElement.elements(); context.put("extensionElements", extensionElements); } String taglibXMLContent = processTemplate("taglib.xml.ftl", context); StringBuilder sb = new StringBuilder(4); sb.append(_TAGLIB_XML_OUTPUT_DIR); sb.append("/"); sb.append(_NAMESPACE); sb.append(".taglib.xml"); File taglibXMLFile = new File(sb.toString()); writeFile(taglibXMLFile, taglibXMLContent, true); } }
From source file:com.liferay.portal.ejb.PortletManagerImpl.java
License:Open Source License
private Set _readPortletXML(String servletContextName, String xml, Map portletsPool) throws DocumentException, IOException { Set portletIds = new HashSet(); if (xml == null) { return portletIds; }/*from ww w .ja v a 2s . c om*/ /*EntityResolver resolver = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { InputStream is = getClass().getClassLoader().getResourceAsStream( "com/liferay/portal/resources/portlet-app_1_0.xsd"); return new InputSource(is); } };*/ SAXReader reader = new SAXReader(); //reader.setEntityResolver(resolver); Document doc = reader.read(new StringReader(xml)); Element root = doc.getRootElement(); Set userAttributes = new HashSet(); Iterator itr1 = root.elements("user-attribute").iterator(); while (itr1.hasNext()) { Element userAttribute = (Element) itr1.next(); String name = userAttribute.elementText("name"); userAttributes.add(name); } itr1 = root.elements("portlet").iterator(); while (itr1.hasNext()) { Element portlet = (Element) itr1.next(); String portletId = portlet.elementText("portlet-name"); if (servletContextName != null) { portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId; } portletIds.add(portletId); Portlet portletModel = (Portlet) portletsPool.get(portletId); if (portletModel == null) { portletModel = new Portlet(new PortletPK(portletId, _SHARED_KEY, _SHARED_KEY)); portletsPool.put(portletId, portletModel); } if (servletContextName != null) { portletModel.setWARFile(true); } portletModel.setPortletClass(portlet.elementText("portlet-class")); Iterator itr2 = portlet.elements("init-param").iterator(); while (itr2.hasNext()) { Element initParam = (Element) itr2.next(); portletModel.getInitParams().put(initParam.elementText("name"), initParam.elementText("value")); } Element expirationCache = portlet.element("expiration-cache"); if (expirationCache != null) { portletModel.setExpCache(new Integer(GetterUtil.getInteger(expirationCache.getText()))); } itr2 = portlet.elements("supports").iterator(); while (itr2.hasNext()) { Element supports = (Element) itr2.next(); String mimeType = supports.elementText("mime-type"); Iterator itr3 = supports.elements("portlet-mode").iterator(); while (itr3.hasNext()) { Element portletMode = (Element) itr3.next(); Set mimeTypeModes = (Set) portletModel.getPortletModes().get(mimeType); if (mimeTypeModes == null) { mimeTypeModes = new HashSet(); portletModel.getPortletModes().put(mimeType, mimeTypeModes); } mimeTypeModes.add(portletMode.getTextTrim().toLowerCase()); } } Set supportedLocales = portletModel.getSupportedLocales(); supportedLocales.add(Locale.getDefault().getLanguage()); itr2 = portlet.elements("supported-locale").iterator(); while (itr2.hasNext()) { Element supportedLocaleEl = (Element) itr2.next(); String supportedLocale = supportedLocaleEl.getText(); supportedLocales.add(supportedLocale); } portletModel.setResourceBundle(portlet.elementText("resource-bundle")); Element portletInfo = portlet.element("portlet-info"); String portletInfoTitle = null; String portletInfoShortTitle = null; String portletInfoKeyWords = null; if (portletInfo != null) { portletInfoTitle = portletInfo.elementText("title"); portletInfoShortTitle = portletInfo.elementText("short-title"); portletInfoKeyWords = portletInfo.elementText("keywords"); } portletModel .setPortletInfo(new PortletInfo(portletInfoTitle, portletInfoShortTitle, portletInfoKeyWords)); Element portletPreferences = portlet.element("portlet-preferences"); String defaultPreferences = null; String prefsValidator = null; if (portletPreferences != null) { Element prefsValidatorEl = portletPreferences.element("preferences-validator"); String prefsValidatorName = null; if (prefsValidatorEl != null) { prefsValidator = prefsValidatorEl.getText(); portletPreferences.remove(prefsValidatorEl); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(baos, OutputFormat.createCompactFormat()); writer.write(portletPreferences); defaultPreferences = baos.toString(); } portletModel.setDefaultPreferences(defaultPreferences); portletModel.setPreferencesValidator(prefsValidator); if (!portletModel.isWARFile() && Validator.isNotNull(prefsValidator) && GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) { try { PreferencesValidator prefsValidatorObj = PortalUtil.getPreferencesValidator(portletModel); prefsValidatorObj.validate(PortletPreferencesSerializer.fromDefaultXML(defaultPreferences)); } catch (Exception e) { _log.warn("Portlet with the name " + portletId + " does not have valid default preferences"); } } List roles = new ArrayList(); itr2 = portlet.elements("security-role-ref").iterator(); while (itr2.hasNext()) { Element role = (Element) itr2.next(); roles.add(role.elementText("role-name")); } portletModel.setRolesArray((String[]) roles.toArray(new String[0])); portletModel.getUserAttributes().addAll(userAttributes); } return portletIds; }
From source file:com.liferay.portlet.PortletPreferencesSerializer.java
License:Open Source License
public static PortletPreferences fromDefaultXML(String xml) throws PortalException, SystemException { PortletPreferencesImpl prefs = new PortletPreferencesImpl(); if (Validator.isNull(xml)) { return prefs; }/* w ww . j a v a 2 s . c o m*/ Map preferences = prefs.getPreferences(); try { Document doc = new SAXReader().read(new StringReader(xml)); Element root = doc.getRootElement(); Iterator itr1 = root.elements("preference").iterator(); while (itr1.hasNext()) { Element prefEl = (Element) itr1.next(); String name = prefEl.elementTextTrim("name"); List values = new ArrayList(); Iterator itr2 = prefEl.elements("value").iterator(); while (itr2.hasNext()) { Element valueEl = (Element) itr2.next(); /*if (valueEl.nodeCount() <= 0) { values.add(valueEl.getText()); } else { values.add(valueEl.node(0).asXML()); }*/ values.add(valueEl.getTextTrim()); } boolean readOnly = GetterUtil.get(prefEl.elementText("read-only"), false); Preference preference = new Preference(name, (String[]) values.toArray(new String[0]), readOnly); preferences.put(name, preference); } return prefs; } catch (DocumentException de) { throw new SystemException(de); } }
From source file:com.liferay.util.xml.descriptor.StrictXMLDescriptor.java
License:Open Source License
private int _compare(Object obj1, Object obj2) { Element el1 = (Element) obj1; Element el2 = (Element) obj2; String el1Name = el1.getName(); String el2Name = el2.getName(); if (!el1Name.equals(el2Name)) { return el1Name.compareTo(el2Name); }/* w w w.j ava 2 s . c o m*/ String el1Text = el1.getTextTrim(); String el2Text = el2.getTextTrim(); if (!el1Text.equals(el2Text)) { return el1Text.compareTo(el2Text); } int attributeComparison = _compareAttributes(el1, el2); if (attributeComparison != 0) { return attributeComparison; } int childrenComparison = _compareChildren(el1, el2); if (childrenComparison != 0) { return childrenComparison; } return 0; }