List of usage examples for org.dom4j DocumentHelper parseText
public static Document parseText(String text) throws DocumentException
parseText
parses the given text as an XML document and returns the newly created Document.
From source file:de.innovationgate.wgpublisher.expressions.tmlscript.RhinoExpressionEngineImpl.java
License:Open Source License
public Document convertNativeXMLtoDOM(Object xmlObj) throws DocumentException { int scriptType = determineTMLScriptType(xmlObj); if (scriptType == RhinoExpressionEngine.TYPE_XMLOBJECT) { String xmlText = (String) ScriptableObject.callMethod((XMLObject) xmlObj, "toXMLString", new Object[] {}); return DocumentHelper.parseText(xmlText); } else {/*from w w w . j av a 2s . co m*/ return null; } }
From source file:de.innovationgate.wgpublisher.webtml.actions.TMLAction.java
License:Open Source License
public static TMLAction buildActionFromScriptModule(WGCSSJSModule mod, ObjectStrategy defaultObjectStrategy) throws TMLActionException, WGAPIException { String code = mod.getCode().trim(); TMLAction action = null;/*from w w w .j a va2 s . c o m*/ // See if code is surrounded by <tml:action> Tag. Parse it out to get // flags if (code.startsWith("<tml:action")) { List<String> codelines = WGUtils.deserializeCollection(code, "\n"); if (codelines.size() < 2) { throw new TMLActionException( "Too few lines for action script module. A script module that begins with <tml:action> must a) have this tag on a separate line and b) end with </tml:action> on a separate line"); } // Take first and last line of code and try to parse them as XML String actionXML = ACTION_XML_PREFIX + ((String) codelines.get(0)) + ((String) codelines.get(codelines.size() - 1)) + ACTION_XML_SUFFIX; String actionCode = ""; if (codelines.size() >= 3) { actionCode = WGUtils.serializeCollection(codelines.subList(1, codelines.size() - 1), "\n"); } // Parse out action flags boolean master = false; boolean async = false; boolean debounce = true; int timeout = RhinoExpressionEngine.DEFAULT_SCRIPTTIMEOUT; try { Document actionDOM = DocumentHelper.parseText(actionXML); Element actionElement = actionDOM.getRootElement() .element(new QName("action", new Namespace("tml", "urn:webtml"))); master = WGUtils.stringToBoolean(actionElement.attributeValue("master", "false")); async = WGUtils.stringToBoolean(actionElement.attributeValue("async", "false")); debounce = WGUtils.stringToBoolean(actionElement.attributeValue("debounce", "true")); try { timeout = Integer.parseInt(actionElement.attributeValue("timeout", new Integer(RhinoExpressionEngine.DEFAULT_SCRIPTTIMEOUT).toString())); } catch (NumberFormatException e) { throw new TMLActionException( "Unparseable action timeout: " + actionElement.attributeValue("timeout")); } action = new TMLAction(actionCode, master, async, debounce, ORIGIN_SCRIPT_MODULE); action.setTimeout(timeout); } catch (DocumentException e) { throw new TMLActionException("Unable to build action from script module", e); } } // No tag surrounds the action code. Take the code unmodified else { action = new TMLAction(code, false, false, true, ORIGIN_SCRIPT_MODULE); } if (action != null) { action.setDesignReference(new DesignResourceReference(mod)); action.setModuleDate(mod.getLastModified()); action.setID(action.getModuleDatabase() + "/" + action.getModuleName()); // Determine object strategy: May be modified by strategy determined on module. ObjectStrategy objectStrategy = defaultObjectStrategy; String determinedObjectStrategyStr = (String) mod .getExtensionData(RhinoExpressionEngine.EXTDATA_OBJECTSTRATEGY); if (determinedObjectStrategyStr != null) { objectStrategy = ObjectStrategy.valueOf(determinedObjectStrategyStr); } action.setObjectStrategy(objectStrategy); // Determine name of eventually included object from original filename String sourceFileName = mod.getSourceFileName(); if (sourceFileName != null) { String objectName = DesignDirectory.getTMLScriptObjectName(sourceFileName); action.setObjectName(objectName); } } return action; }
From source file:de.innovationgate.wgpublisher.webtml.Item.java
License:Open Source License
public void tmlEndTag() throws WGException, TMLException { String itemName = this.getName(); TMLContext tmlContext = this.getTMLContext(); List result = null;/* ww w . j a v a 2 s .c o m*/ String type = this.getType(); // add warning on illegal use of highlight attribute if (stringToBoolean(getHighlight())) { if (!type.equals("content")) { addWarning("Highlighting can only be used with type 'content' - skipped."); } } // Retrieve value if (type.equals("content")) { result = tmlContext.itemlist(itemName, buildNamedActionParameters(false)); if (stringToBoolean(getHighlight())) { if (this.stringToBoolean(this.getScriptlets())) { addWarning("Highlighting cannot be used with scriptlets - skipped."); } else if (this.getAliases() != null) { addWarning("Highlighting cannot be used with aliases - skipped."); } else if (getXpath() != null) { addWarning("Highlighting cannot be used together with xpath - skipped."); } else { // highlight itemvalue with information from lucene query result = Collections.singletonList(tmlContext.highlightitem(itemName, getHighlightprefix(), getHighlightsuffix(), getStatus().encode)); getStatus().encode = "none"; } } } else if (type.equals("profile")) { TMLUserProfile profile = tmlContext.getprofile(); if (profile == null) { this.addWarning("Current user has no profile", true); return; } result = profile.itemlist(itemName); } else if (type.equals("portlet")) { TMLPortlet portlet = tmlContext.getportlet(); if (portlet == null) { this.addWarning("Current user has no portlet registration", true); return; } result = portlet.itemlist(itemName); } else if (type.equals("tmlform")) { TMLForm form = tmlContext.gettmlform(); if (form == null) { addWarning("There is no current WebTML form at this position in the current request"); return; } result = form.fieldlist(itemName); } // The item does not exist or is empty. Treat as empty list. if (result == null) { result = new ArrayList(); } // Eventually execute xpath String xpath = getXpath(); if (xpath != null && result.size() > 0) { Object firstResult = result.get(0); if (firstResult instanceof Node) { Node resultNode = (Node) firstResult; result = resultNode.selectNodes(xpath); } else if (firstResult instanceof String) { try { Document doc = DocumentHelper.parseText((String) firstResult); result = doc.selectNodes(xpath); } catch (DocumentException e) { addWarning("Unable to parse item content '" + itemName + "' as XML: " + firstResult); } } else if (ExpressionEngineFactory.getTMLScriptEngine() .determineTMLScriptType(firstResult) == RhinoExpressionEngine.TYPE_XMLOBJECT) { result = ExpressionEngineFactory.getTMLScriptEngine().xpathTMLScriptBean(firstResult, xpath); } else { JXPathContext jxcontext = JXPathContext.newContext(firstResult); Iterator jxresults = jxcontext.iterate(xpath); result = new ArrayList(); while (jxresults.hasNext()) { result.add(jxresults.next()); } } } // Eventually resolve scriptlets if (result.size() > 0 && this.stringToBoolean(this.getScriptlets()) == true) { RhinoExpressionEngine engine = ExpressionEngineFactory.getTMLScriptEngine(); String resolvedResultStr = null; try { Map params = new HashMap(); params.put(RhinoExpressionEngine.SCRIPTLETOPTION_LEVEL, RhinoExpressionEngine.LEVEL_SCRIPTLETS); resolvedResultStr = engine.resolveScriptlets(result.get(0), getTMLContext(), params); result = new ArrayList(); result.add(resolvedResultStr); } catch (Exception e) { throw new TMLException("Exception parsing scriptlets", e, false); } } // BI-Editor (See Root-Class for attrib WGACore.ATTRIB_EDITDOCUMENT) Object attribEdit = this.getPageContext().getRequest().getAttribute(WGACore.ATTRIB_EDITDOCUMENT); if (attribEdit != null && getEditor() != null && attribEdit.equals(this.getTMLContext().getcontent().getContentKey().toString())) { buildEditor(itemName, result); setResult(result); } else { // if aliases are defined, replace values with aliases List aliases = this.retrieveAliases(); if (aliases.isEmpty()) this.setResult(result); else { WGA wga = WGA.get(); this.setResult(wga.aliases(WGUtils.toString(result), aliases)); } } }
From source file:de.innovationgate.wgpublisher.WGACore.java
License:Open Source License
private void initDefaultSerializer() { Dom4JDriver driver = new Dom4JDriver(); OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); driver.setOutputFormat(format);/*from ww w.j a v a 2s . c o m*/ _defaultSerializer = new XStream(driver); _defaultSerializer.setClassLoader(getLibraryLoader()); _defaultSerializer.alias("tmloption", TMLOption.class); _defaultSerializer.alias("version", Version.class); _defaultSerializer.alias("portletState", TMLPortletState.class); _defaultSerializer.registerConverter(ExpressionEngineFactory.getTMLScriptEngine()); // DOM4J Objects _defaultSerializer.registerConverter(new SingleValueConverter() { public boolean canConvert(Class arg0) { return org.dom4j.Element.class.isAssignableFrom(arg0); } public Object fromString(String arg0) { try { org.dom4j.Document doc = DocumentHelper.parseText(arg0); return doc.getRootElement(); } catch (DocumentException e) { Logger.getLogger("wga.ajax") .error("Exception deserializing DOM4J Element from TMLPortlet.SessionContext", e); return ""; } } public String toString(Object arg0) { Element elem = (Element) arg0; return elem.asXML(); } }); // Serialize TMLContext to their context path. All other info is dropped. Deserialize to a TMLContext.Serialized. _defaultSerializer.registerConverter(new SingleValueConverter() { @SuppressWarnings("rawtypes") @Override public boolean canConvert(Class arg0) { return TMLContext.class.isAssignableFrom(arg0); } @Override public String toString(Object arg0) { try { TMLContext cx = (TMLContext) arg0; return cx.getpath(); } catch (WGAPIException e) { throw new RuntimeException("Exception serializing TMLContext", e); } } @Override public Object fromString(String arg0) { return new TMLContext.Serialized(arg0); } }); // Version object _defaultSerializer.registerConverter(new SingleValueConverter() { public boolean canConvert(Class arg0) { return Version.class.isAssignableFrom(arg0); } public Object fromString(String arg0) { return new Version(arg0); } public String toString(Object arg0) { return ((Version) arg0).toString(); } }); // GSON data structures _defaultSerializer.registerConverter(new SingleValueConverter() { private Gson _gson = new GsonBuilder().create(); @Override public boolean canConvert(Class arg0) { return JsonElement.class.isAssignableFrom(arg0); } @Override public Object fromString(String arg0) { return new JsonParser().parse(arg0); } @Override public String toString(Object arg0) { return _gson.toJson((JsonElement) arg0); } }); // Serialize types not meant to be serialized to empty string, deserialize to null _defaultSerializer.registerConverter(new SingleValueConverter() { public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) { return DEFAULT_SERIALIZER_NONSERIALIZABLE_TYPES.contains(clazz); } public Object fromString(String arg0) { return null; } public String toString(Object arg0) { return ""; } }); }
From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java
License:LGPL
/** * Replace the img-tag and a-tag with the equivalent velocity macro. Mainly used before saving a field value to the database. * /*from w w w. java 2 s . c o m*/ * @throws RenderingException * If any exception was thrown while replacing the tags. */ @SuppressWarnings("unchecked") public static String replaceTags(final Site site, final String oldValue) throws RenderingException { if (StringUtils.isBlank(oldValue)) return null; // 1. add a root element (to have a proper xml) and replace the ampersand String newValue = String.format("<dummytag>\n%s\n</dummytag>", StringUtils.replace(oldValue, "&", ampReplacer)); Map<String, String> replacements = new HashMap<String, String>(); try { Document dom = DocumentHelper.parseText(newValue); dom.setXMLEncoding(Constants.STANDARD_ENCODING); // 2. Collect the keys, identify the img-tags. List<Node> imgs = dom.selectNodes("//img", "."); for (Node node : imgs) { Element element = (Element) node; if (element.attributeValue("src").startsWith("/")) // only internal links have to replaced with a velocity macro replacements.put(node.asXML(), generateVelocityImageToolCall(site, element.attributeIterator())); } // 3. Collect the keys, identify the a-tags List<Node> links = dom.selectNodes("//a", "."); for (Node node : links) { Element element = (Element) node; if (element.attributeValue("href").startsWith("/")) // only internal links have to replaced with a velocity macro replacements.put(element.asXML(), generateVelocityLinkToolCall(site, element)); } // 4. Replace the tags with the velomacro. StringWriter stringWriter = new StringWriter(); XMLWriter writer = new XMLWriter(stringWriter, sourceFormat); writer.write(dom.selectSingleNode("dummytag")); writer.close(); newValue = stringWriter.toString(); for (String stringToReplace : replacements.keySet()) newValue = StringUtils.replace(newValue, stringToReplace, replacements.get(stringToReplace)); newValue = StringUtils.replace(newValue, "<dummytag>", ""); newValue = StringUtils.replace(newValue, "</dummytag>", ""); } catch (Exception e) { throw new RenderingException("While preprocessing the field value: " + e.getMessage(), e); } return StringUtils.replace(newValue, ampReplacer, "&"); }
From source file:de.tu_berlin.cit.intercloud.xmpp.component.ResourceContainerComponent.java
License:Apache License
/** * Override this method to handle the IQ stanzas of type <tt>get</tt> that * could not be processed by the {@link AbstractComponent} implementation. * /* w w w .ja v a 2 s. co m*/ * Note that, as any IQ stanza of type <tt>get</tt> must be replied to, * returning <tt>null</tt> from this method equals returning an IQ error * stanza of type 'feature-not-implemented' (this behavior can be disabled * by setting the <tt>enforceIQResult</tt> argument in the constructor to * <tt>false</tt>). * * Note that if this method throws an Exception, an IQ stanza of type * <tt>error</tt>, condition 'internal-server-error' will be returned to the * sender of the original request. * * The default implementation of this method returns <tt>null</tt>. It is * expected that most child classes will override this method. * * @param iq * The IQ request stanza of type <tt>get</tt> that was received * by this component. * @return the response the to request stanza, or <tt>null</tt> to indicate * 'feature-not-available'. */ @Override protected IQ handleIQGet(IQ iq) throws Exception { logger.info("the following iq get stanza has been received:" + iq.toString()); Element child = iq.getChildElement(); String path = child.attribute("path").getValue(); ResourceTypeDocument xwadl = this.container.getXWADL(path); Document doc = DocumentHelper.parseText(xwadl.toString()); IQ response = IQ.createResultIQ(iq); response.setChildElement(doc.getRootElement()); logger.info("the following iq result stanza will be send:" + response.toString()); return response; }
From source file:de.tu_berlin.cit.intercloud.xmpp.component.ResourceContainerComponent.java
License:Apache License
/** * Override this method to handle the IQ stanzas of type <tt>set</tt> that * could not be processed by the {@link AbstractComponent} implementation. * /*from w w w.ja v a 2 s. com*/ * Note that, as any IQ stanza of type <tt>set</tt> must be replied to, * returning <tt>null</tt> from this method equals returning an IQ error * stanza of type 'feature-not-implemented' {this behavior can be disabled * by setting the <tt>enforceIQResult</tt> argument in the constructor to * <tt>false</tt>). * * Note that if this method throws an Exception, an IQ stanza of type * <tt>error</tt>, condition 'internal-server-error' will be returned to the * sender of the original request. * * The default implementation of this method returns <tt>null</tt>. It is * expected that most child classes will override this method. * * @param iq * The IQ request stanza of type <tt>set</tt> that was received * by this component. * @return the response the to request stanza, or <tt>null</tt> to indicate * 'feature-not-available'. */ @Override protected IQ handleIQSet(IQ iq) throws Exception { logger.info("the following iq set stanza has been received:" + iq.toString()); Element child = iq.getChildElement(); ResourceDocument xmlRequest = ResourceDocument.Factory.parse(child.asXML()); ResourceDocument xmlResponse = this.container.execute(xmlRequest); Document doc = DocumentHelper.parseText(xmlResponse.toString()); IQ response = IQ.createResultIQ(iq); response.setChildElement(doc.getRootElement()); logger.info("the following iq result stanza will be send:" + response.toString()); return response; }
From source file:de.tu_berlin.cit.intercloud.xmpp.component.ResourceContainerSocket.java
License:Apache License
public ResourceTypeDocument requestXWADL(String path) throws InterruptedException { IQ iq = new IQ(Type.get); iq.setTo(jid);/*w ww. j a v a 2s.c om*/ // create request ResourceTypeDocument request = ResourceTypeDocument.Factory.newInstance(); request.addNewResourceType().setPath(path); try { Document doc; doc = DocumentHelper.parseText(request.toString()); // set request iq.setChildElement(doc.getRootElement()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } this.socketManager.sendIQ(iq, this); // wait for response ResourceTypeDocument response; response = this.xwadlExchanger.exchange(request); return response; }
From source file:de.tu_berlin.cit.intercloud.xmpp.component.ResourceContainerSocket.java
License:Apache License
public ResourceDocument invokeRestXML(ResourceDocument request) throws InterruptedException { IQ iq = new IQ(Type.set); iq.setTo(jid);/* w w w . j a v a 2 s .c o m*/ // create request try { Document doc; doc = DocumentHelper.parseText(request.toString()); // set request iq.setChildElement(doc.getRootElement()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } this.socketManager.sendIQ(iq, this); // wait for response ResourceDocument response; response = this.restXmlExchanger.exchange(request); return response; }
From source file:de.tu_berlin.cit.intercloud.xmpp.component.ResourceContainerSocket.java
License:Apache License
public void invokeAsyncRestXML(ResourceDocument request, AsynchronousResultListener listener) { IQ iq = new IQ(Type.set); iq.setTo(jid);//ww w. jav a 2 s . c o m // create request try { Document doc; doc = DocumentHelper.parseText(request.toString()); // set request iq.setChildElement(doc.getRootElement()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.socketManager.sendIQ(iq, this); // process the result in a separate thread new Thread(new Runnable() { @Override public void run() { // wait for response ResourceDocument response; try { response = restXmlExchanger.exchange(request); listener.processResult(response); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); }