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:nl.nn.adapterframework.util.XmlUtils.java
License:Apache License
public static String canonicalize(String input) throws DocumentException, IOException { if (StringUtils.isEmpty(input)) { return null; }/*w w w . j ava 2 s. c o m*/ org.dom4j.Document doc = DocumentHelper.parseText(input); StringWriter sw = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setExpandEmptyElements(true); XMLWriter xw = new XMLWriter(sw, format); xw.write(doc); return sw.toString(); }
From source file:nl.nn.ibistesttool.PipeDescriptionProvider.java
License:Apache License
/** * Get a PipeDescription object for the specified pipe. The returned object * is cached./*from w w w .j a v a2s. com*/ */ public PipeDescription getPipeDescription(PipeLine pipeLine, IPipe pipe) { PipeDescription pipeDescription; String adapterName = pipeLine.getOwner().getName(); String pipeName = pipe.getName(); String checkpointName = null; String xpathExpression = null; if (pipeLine.getPipe(pipeName) == null) { if (PipeLine.INPUT_VALIDATOR_NAME.equals(pipeName)) { checkpointName = INPUT_VALIDATOR_CHECKPOINT_NAME; xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/inputValidator"; } else if (PipeLine.OUTPUT_VALIDATOR_NAME.equals(pipeName)) { checkpointName = OUTPUT_VALIDATOR_CHECKPOINT_NAME; xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/outputValidator"; } else if (PipeLine.INPUT_WRAPPER_NAME.equals(pipeName)) { checkpointName = INPUT_WRAPPER_CHECKPOINT_NAME; xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/inputWrapper"; } else if (PipeLine.OUTPUT_WRAPPER_NAME.equals(pipeName)) { checkpointName = OUTPUT_WRAPPER_CHECKPOINT_NAME; xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/outputWrapper"; } else if (pipeName.startsWith(MessageSendingPipe.INPUT_VALIDATOR_NAME_PREFIX) && pipeName.endsWith(MessageSendingPipe.INPUT_VALIDATOR_NAME_SUFFIX)) { checkpointName = INPUT_VALIDATOR_CHECKPOINT_NAME; String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.INPUT_VALIDATOR_NAME_PREFIX, MessageSendingPipe.INPUT_VALIDATOR_NAME_SUFFIX); xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\"" + parentPipeName + "\"]/inputValidator"; } else if (pipeName.startsWith(MessageSendingPipe.OUTPUT_VALIDATOR_NAME_PREFIX) && pipeName.endsWith(MessageSendingPipe.OUTPUT_VALIDATOR_NAME_SUFFIX)) { checkpointName = OUTPUT_VALIDATOR_CHECKPOINT_NAME; String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.OUTPUT_VALIDATOR_NAME_PREFIX, MessageSendingPipe.OUTPUT_VALIDATOR_NAME_SUFFIX); xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\"" + parentPipeName + "\"]/outputValidator"; } else if (pipeName.startsWith(MessageSendingPipe.INPUT_WRAPPER_NAME_PREFIX) && pipeName.endsWith(MessageSendingPipe.INPUT_WRAPPER_NAME_SUFFIX)) { checkpointName = INPUT_WRAPPER_CHECKPOINT_NAME; String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.INPUT_WRAPPER_NAME_PREFIX, MessageSendingPipe.INPUT_WRAPPER_NAME_SUFFIX); xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\"" + parentPipeName + "\"]/inputWrapper"; } else if (pipeName.startsWith(MessageSendingPipe.OUTPUT_WRAPPER_NAME_PREFIX) && pipeName.endsWith(MessageSendingPipe.OUTPUT_WRAPPER_NAME_SUFFIX)) { checkpointName = OUTPUT_WRAPPER_CHECKPOINT_NAME; String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.OUTPUT_WRAPPER_NAME_PREFIX, MessageSendingPipe.OUTPUT_WRAPPER_NAME_SUFFIX); xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\"" + parentPipeName + "\"]/outputWrapper"; } } else { xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\"" + pipeName + "\"]"; } synchronized (pipeDescriptionCaches) { // When a configuration is changed (reloaded) a new configuration // object will be created. The old configuration object will be // removed from pipeDescriptionCaches by the garbage collection as // this is a WeakHashMap. Configuration configuration = pipeLine.getAdapter().getConfiguration(); Map<String, PipeDescription> pipeDescriptionCache = pipeDescriptionCaches.get(configuration); if (pipeDescriptionCache == null) { pipeDescriptionCache = new HashMap<String, PipeDescription>(); pipeDescriptionCaches.put(configuration, pipeDescriptionCache); } pipeDescription = pipeDescriptionCache.get(xpathExpression); if (pipeDescription == null) { pipeDescription = new PipeDescription(); pipeDescription.setCheckpointName(getCheckpointName(pipe, checkpointName)); if (xpathExpression == null) { pipeDescription.setDescription("Could not create xpath to extract pipe from configuration"); pipeDescriptionCache.put(xpathExpression, pipeDescription); } else { Document document = documents.get(configuration); if (document == null) { try { document = DocumentHelper.parseText(configuration.getLoadedConfiguration()); documents.put(configuration, document); } catch (DocumentException e) { pipeDescription = new PipeDescription(); pipeDescription.setCheckpointName(getCheckpointName(pipe, checkpointName)); pipeDescription.setDescription("Could not parse configuration: " + e.getMessage()); pipeDescriptionCache.put(xpathExpression, pipeDescription); } } if (document != null) { Node node = document.selectSingleNode(xpathExpression); if (node != null) { StringWriter stringWriter = new StringWriter(); OutputFormat outputFormat = OutputFormat.createPrettyPrint(); XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat); try { xmlWriter.write(node); xmlWriter.flush(); pipeDescription.setDescription(stringWriter.toString()); } catch (IOException e) { pipeDescription.setDescription("IOException: " + e.getMessage()); } addResourceNamesToPipeDescription((Element) node, pipeDescription); } else { pipeDescription.setDescription("Pipe not found in configuration."); } } } pipeDescriptionCache.put(xpathExpression, pipeDescription); } } return pipeDescription; }
From source file:noThreads.Playlist.java
License:Open Source License
public void createPlaylist(String filePath) throws IOException, DocumentException, SAXException, ParserConfigurationException { String xmlObject, title = null; boolean flag = true; XspfPlaylist playlist = new XspfPlaylist(); playlist.setTitle("My Playlist"); playlist.setVersion("1"); // create track list first XspfPlaylistTrackList tracks = new XspfPlaylistTrackList(); for (int i = 0; i < eradioLinks.size(); i++) { if (flag == true) { flag = false;//www . j a v a 2 s .co m title = org.apache.commons.lang3.StringEscapeUtils.escapeXml(eradioLinks.get(i)); } else { flag = true; //escape the xml characters of the url xmlObject = org.apache.commons.lang3.StringEscapeUtils.escapeXml(eradioLinks.get(i)); // now create track, set title and add to list XspfTrack track = new XspfTrack(); track.setTitle(title); track.setLocation(xmlObject); tracks.addTrack(track); } } // add tracks to playlist playlist.setPlaylistTrackList(tracks); //or use Dom4j to output the playlist File file = new File(filePath); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(file), format); Document doc = DocumentHelper.parseText(playlist.makeTextDocument()); writer.write(doc); writer.close(); }
From source file:org.alfresco.module.vti.web.ws.UpdateDwsDataEndpoint.java
License:Open Source License
/** * Update dws data for site// w ww.ja va 2s.c o m * * @param soapRequest Vti soap request ({@link VtiSoapRequest}) * @param soapResponse Vti soap response ({@link VtiSoapResponse}) */ @SuppressWarnings("unchecked") public void execute(VtiSoapRequest soapRequest, VtiSoapResponse soapResponse) throws Exception { if (logger.isDebugEnabled()) { logger.debug("SOAP method with name " + getName() + " is started."); } // mapping xml namespace to prefix SimpleNamespaceContext nc = new SimpleNamespaceContext(); nc.addNamespace(prefix, namespace); nc.addNamespace(soapUriPrefix, soapUri); XPath updatesPath = new Dom4jXPath(buildXPath(prefix, "/UpdateDwsData/updates")); updatesPath.setNamespaceContext(nc); Element updates = (Element) updatesPath.selectSingleNode(soapRequest.getDocument().getRootElement()); Document updatesDocument = DocumentHelper.parseText(updates.getText()); XPath setVarPath = new Dom4jXPath("/Batch/Method/SetVar"); List<Element> list = setVarPath.selectNodes(updatesDocument); LinkBean link = createLink(list); XPath methodPath = new Dom4jXPath("/Batch/Method"); CAMLMethod method = CAMLMethod .value(((Element) methodPath.selectSingleNode(updatesDocument)).attributeValue("ID")); Element root = soapResponse.getDocument().addElement("UpdateDwsDataResponse", namespace); Element updateDwsDataResult = root.addElement("UpdateDwsDataResult"); Element results = updateDwsDataResult.addElement("Results"); Element result = results.addElement("Result"); result.addAttribute("ID", method.toString()); result.addAttribute("Code", "0"); try { link = handler.updateDwsData(link, method, VtiPathHelper.removeSlashes(getDwsFromUri(soapRequest))); } catch (VtiHandlerException e) { if (e.getMessage().equals(VtiHandlerException.ITEM_NOT_FOUND)) { result.addElement("Error").addAttribute("ID", "5"); return; } else if (e.getMessage().equals(VtiHandlerException.LIST_NOT_FOUND)) { result.addElement("Error").addAttribute("ID", "7"); return; } else { throw e; } } if (method.toString().equals("New")) { result.addText(generateXml(link)); } else { result.addAttribute("List", ""); result.addAttribute("Version", "0"); } if (logger.isDebugEnabled()) { logger.debug("SOAP method with name " + getName() + " is finished."); } }
From source file:org.alfresco.web.ui.repo.tag.JBPMProcessImageTag.java
License:Open Source License
private void writeTable() throws IOException, DocumentException { int borderWidth = 4; Element rootDiagramElement = DocumentHelper.parseText(new String(gpdBytes)).getRootElement(); int[] boxConstraint; int[] imageDimension = extractImageDimension(rootDiagramElement); String imageLink = "/alfresco/processimage?definitionId=" + processDefinition.getId(); JspWriter jspOut = pageContext.getOut(); if (tokenInstanceId > 0) { List allTokens = new ArrayList(); walkTokens(currentToken, allTokens); jspOut.println("<div style='position:relative; background-image:url(" + imageLink + "); width: " + imageDimension[0] + "px; height: " + imageDimension[1] + "px;'>"); for (int i = 0; i < allTokens.size(); i++) { Token token = (Token) allTokens.get(i); //check how many tokens are on teh same level (= having the same parent) int offset = i; if (i > 0) { while (offset > 0 && ((Token) allTokens.get(offset - 1)).getParent().equals(token.getParent())) { offset--;/*from w ww. java2 s .c om*/ } } boxConstraint = extractBoxConstraint(rootDiagramElement, token); //Adjust for borders //boxConstraint[2]-=borderWidth*2; //boxConstraint[3]-=borderWidth*2; jspOut.println("<div style='position:absolute; left: " + boxConstraint[0] + "px; top: " + boxConstraint[1] + "px; "); if (i == (allTokens.size() - 1)) { jspOut.println("border: " + currentTokenColor); } else { jspOut.println("border: " + childTokenColor); } jspOut.println(" " + borderWidth + "px groove; " + "width: " + boxConstraint[2] + "px; height: " + boxConstraint[3] + "px;'>"); if (token.getName() != null) { jspOut.println("<span style='color:" + tokenNameColor + ";font-style:italic;position:absolute;left:" + (boxConstraint[2] + 10) + "px;top:" + ((i - offset) * 20) + ";'> " + token.getName() + "</span>"); } jspOut.println("</div>"); } jspOut.println("</div>"); } else { boxConstraint = extractBoxConstraint(rootDiagramElement); jspOut.println("<table border=0 cellspacing=0 cellpadding=0 width=" + imageDimension[0] + " height=" + imageDimension[1] + ">"); jspOut.println(" <tr>"); jspOut.println(" <td width=" + imageDimension[0] + " height=" + imageDimension[1] + " style=\"background-image:url(" + imageLink + ")\" valign=top>"); jspOut.println(" <table border=0 cellspacing=0 cellpadding=0>"); jspOut.println(" <tr>"); jspOut.println(" <td width=" + (boxConstraint[0] - borderWidth) + " height=" + (boxConstraint[1] - borderWidth) + " style=\"background-color:transparent;\"></td>"); jspOut.println(" </tr>"); jspOut.println(" <tr>"); jspOut.println(" <td style=\"background-color:transparent;\"></td>"); jspOut.println(" <td style=\"border-color:" + currentTokenColor + "; border-width:" + borderWidth + "px; border-style:groove; background-color:transparent;\" width=" + boxConstraint[2] + " height=" + (boxConstraint[3] + (2 * borderWidth)) + "> </td>"); jspOut.println(" </tr>"); jspOut.println(" </table>"); jspOut.println(" </td>"); jspOut.println(" </tr>"); jspOut.println("</table>"); } }
From source file:org.apache.directory.scim.ldap.LdapSchemaMapper.java
License:Apache License
public void loadMappings(InputStream in) { if (in == null) { throw new IllegalArgumentException("Mapping file inputstream cannot be null"); }/*from ww w. j a v a 2 s .c o m*/ BufferedReader r = new BufferedReader(new InputStreamReader(in)); try { StringBuilder sb = new StringBuilder(); String s = null; while ((s = r.readLine()) != null) { sb.append(s).append("\n"); } Document doc = DocumentHelper.parseText(sb.toString()); // the entities element Element root = doc.getRootElement(); if (root.elements().isEmpty()) { throw new IllegalStateException("Invalid schema mapping file"); } } catch (Exception e) { LOG.warn("Failed to load the schema mappings", e); throw new RuntimeException(e); } finally { if (r != null) { try { r.close(); } catch (IOException e) { LOG.warn("Failed to close the inputstream of the schema mapping file", e); } } } }
From source file:org.apache.taglibs.xtags.xpath.ReplaceTag.java
License:Apache License
public int doEndTag() throws JspException { Object context = TagHelper.getInputNodes(pageContext, this, false); if (context == null) { logInfo("No current node to replace"); return EVAL_PAGE; }//from w w w .ja v a2 s . com try { String xmlFragment = null; if (bodyContent != null) { xmlFragment = bodyContent.getString(); } if (context instanceof List) { List els = (List) context; if (els.size() > 1) { throw new JspException("Current context contains more than one node"); } if (els.size() == 1) { context = els.get(0); } } if (context instanceof Document) { if (xmlFragment == null) { throw new JspException("Cannot replace document with empty body"); } Document sourceDoc = (Document) context; Document newDoc = DocumentHelper.parseText(xmlFragment); // clear source doc contents sourceDoc.clearContent(); for (int i = 0, size = newDoc.nodeCount(); i < size; i++) { Node node = newDoc.node(i); // detach from new doc node.detach(); // add to source sourceDoc.add(node); } } else { if (!(context instanceof Element)) { throw new JspException("Current node is not an Element: " + context.getClass().getName()); } Element element = (Element) context; SAXReader reader = new SAXReader(); if (element.isRootElement()) { if (xmlFragment == null) { throw new JspException("Cannot replace root element with empty body"); } Document newDoc = DocumentHelper.parseText(xmlFragment); Document sourceDoc = element.getDocument(); Element newRoot = newDoc.getRootElement(); newRoot.detach(); sourceDoc.setRootElement(newRoot); } else { Element parent = element.getParent(); List parentContent = parent.content(); int index = parentContent.indexOf(element); parentContent.remove(index); if (xmlFragment != null) { Document newDoc = DocumentHelper.parseText("<dummy>" + xmlFragment + "</dummy>"); parentContent.addAll(index, newDoc.getRootElement().content()); } } } } catch (DocumentException e) { handleException(e); } return EVAL_PAGE; }
From source file:org.apache.taverna.activities.xpath.XPathActivity.java
License:Apache License
/** * This method executes pre-configured instance of XPath activity. *///w w w . j a v a 2 s. c om @Override public void executeAsynch(final Map<String, T2Reference> inputs, final AsynchronousActivityCallback callback) { // Don't execute service directly now, request to be run asynchronously callback.requestRun(new Runnable() { @Override @SuppressWarnings("unchecked") public void run() { InvocationContext context = callback.getContext(); ReferenceService referenceService = context.getReferenceService(); // ---- RESOLVE INPUT ---- String xmlInput = (String) referenceService.renderIdentifier(inputs.get(IN_XML), String.class, context); // ---- DO THE ACTUAL SERVICE INVOCATION ---- List<Node> matchingNodes = new ArrayList<Node>(); // only attempt to execute XPath expression if there is some input data if (xmlInput != null && xmlInput.length() > 0) { // XPath configuration is taken from the config bean try { XPath expr = DocumentHelper.createXPath(json.get("xpathExpression").textValue()); Map<String, String> xpathNamespaceMap = new HashMap<>(); for (JsonNode namespaceMapping : json.get("xpathNamespaceMap")) { xpathNamespaceMap.put(namespaceMapping.get("prefix").textValue(), namespaceMapping.get("uri").textValue()); } expr.setNamespaceURIs(xpathNamespaceMap); Document doc = DocumentHelper.parseText(xmlInput); matchingNodes = expr.selectNodes(doc); } catch (InvalidXPathException e) { callback.fail("Incorrect XPath Expression -- XPath processing library " + "reported the following error: " + e.getMessage(), e); // make sure we don't call callback.receiveResult later return; } catch (DocumentException e) { callback.fail("XML document was not valid -- XPath processing library " + "reported the following error: " + e.getMessage(), e); // make sure we don't call callback.receiveResult later return; } catch (XPathException e) { callback.fail("Unexpected error has occurred while executing the XPath expression. " + "-- XPath processing library reported the following error:\n" + e.getMessage(), e); // make sure we don't call callback.receiveResult later return; } } // --- PREPARE OUTPUTS --- List<String> outNodesText = new ArrayList<String>(); List<String> outNodesXML = new ArrayList<String>(); Object textValue = null; Object xmlValue = null; for (Object o : matchingNodes) { if (o instanceof Node) { Node n = (Node) o; if (n.getStringValue() != null && n.getStringValue().length() > 0) { outNodesText.add(n.getStringValue()); if (textValue == null) textValue = n.getStringValue(); } outNodesXML.add(n.asXML()); if (xmlValue == null) xmlValue = n.asXML(); } else { outNodesText.add(o.toString()); if (textValue == null) textValue = o.toString(); } } // ---- REGISTER OUTPUTS ---- Map<String, T2Reference> outputs = new HashMap<String, T2Reference>(); if (textValue == null) { ErrorDocumentService errorDocService = referenceService.getErrorDocumentService(); textValue = errorDocService.registerError("No value produced", 0, callback.getContext()); } if (xmlValue == null) { ErrorDocumentService errorDocService = referenceService.getErrorDocumentService(); xmlValue = errorDocService.registerError("No value produced", 0, callback.getContext()); } T2Reference firstNodeAsText = referenceService.register(textValue, 0, true, context); outputs.put(SINGLE_VALUE_TEXT, firstNodeAsText); T2Reference firstNodeAsXml = referenceService.register(xmlValue, 0, true, context); outputs.put(SINGLE_VALUE_XML, firstNodeAsXml); T2Reference outNodesAsText = referenceService.register(outNodesText, 1, true, context); outputs.put(OUT_TEXT, outNodesAsText); T2Reference outNodesAsXML = referenceService.register(outNodesXML, 1, true, context); outputs.put(OUT_XML, outNodesAsXML); // return map of output data, with empty index array as this is // the only and final result (this index parameter is used if // pipelining output) callback.receiveResult(outputs, new int[0]); } }); }
From source file:org.b5chat.crossfire.xmpp.presence.PresenceManagerImpl.java
License:Open Source License
public String getLastPresenceStatus(User user) { String username = user.getUsername(); String presenceStatus = null; String presenceXML = offlinePresenceCache.get(username); if (presenceXML == null) { loadOfflinePresence(username);/* w ww . ja v a2s. co m*/ } presenceXML = offlinePresenceCache.get(username); if (presenceXML != null) { // If the cached answer is no data, return null. if (presenceXML.equals(NULL_STRING)) { return null; } // Otherwise, parse out the status from the XML. try { // Parse the element Document element = DocumentHelper.parseText(presenceXML); presenceStatus = element.getRootElement().elementTextTrim("status"); } catch (DocumentException e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } return presenceStatus; }
From source file:org.b5chat.crossfire.xmpp.presence.PresenceManagerImpl.java
License:Open Source License
public void probePresence(JID prober, JID probee) { try {/*from www.ja va 2s . c o m*/ if (server.isLocal(probee)) { // Local probers should receive presences of probee in all connected resources Collection<JID> proberFullJIDs = new ArrayList<JID>(); if (prober.getResource() == null && server.isLocal(prober)) { for (IClientSession session : sessionManager.getSessions(prober.getNode())) { proberFullJIDs.add(session.getAddress()); } } else { proberFullJIDs.add(prober); } // If the probee is a local user then don't send a probe to the contact's server. // But instead just send the contact's presence to the prober Collection<IClientSession> sessions = sessionManager.getSessions(probee.getNode()); if (sessions.isEmpty()) { // If the probee is not online then try to retrieve his last unavailable // presence which may contain particular information and send it to the // prober String presenceXML = offlinePresenceCache.get(probee.getNode()); if (presenceXML == null) { loadOfflinePresence(probee.getNode()); } presenceXML = offlinePresenceCache.get(probee.getNode()); if (presenceXML != null && !NULL_STRING.equals(presenceXML)) { try { // Parse the element Document element = DocumentHelper.parseText(presenceXML); // Create the presence from the parsed element Presence presencePacket = new Presence(element.getRootElement()); presencePacket.setFrom(probee.toBareJID()); // Check if default privacy list of the probee blocks the // outgoing presence PrivacyList list = PrivacyListManager.getInstance() .getDefaultPrivacyList(probee.getNode()); // Send presence to all prober's resources for (JID receipient : proberFullJIDs) { presencePacket.setTo(receipient); if (list == null || !list.shouldBlockPacket(presencePacket)) { // Send the presence to the prober deliverer.deliver(presencePacket); } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } else { // The contact is online so send to the prober all the resources where the // probee is connected for (IClientSession session : sessions) { // Create presence to send from probee to prober Presence presencePacket = session.getPresence().createCopy(); presencePacket.setFrom(session.getAddress()); // Check if a privacy list of the probee blocks the outgoing presence PrivacyList list = session.getActiveList(); list = list == null ? session.getDefaultList() : list; // Send presence to all prober's resources for (JID receipient : proberFullJIDs) { presencePacket.setTo(receipient); if (list != null) { if (list.shouldBlockPacket(presencePacket)) { // Default list blocked outgoing presence so skip this session continue; } } try { deliverer.deliver(presencePacket); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } }