List of usage examples for javax.xml.transform.dom DOMResult getNode
public Node getNode()
From source file:org.fireflow.service.callback.ProcessServiceProvider.java
public Source invoke(Source request) { Expression correlation = callbackService.getCorrelation(); final QName responseRootElementQName = new QName(callbackService.getTargetNamespaceUri(), this.serviceBinding.getOperationName() + "Response"); //??/* w w w . j a va 2 s.co m*/ /* try{ Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // transformer.transform() XML Source? Result transformer.transform(request, new StreamResult( outputStream)); System.out.println( outputStream.toString()); }catch(Exception e){ e.printStackTrace(); } */ final Document requestDOM; try { Transformer transformer = transformerFactory.newTransformer(); DOMResult domResult = new DOMResult(); transformer.transform(request, domResult); requestDOM = (Document) domResult.getNode();//reuqestDOM } catch (TransformerException e) { throw new WebServiceException("Can NOT transform request to DOM.", e); } final WorkflowSession session = WorkflowSessionFactory.createWorkflowSession(workflowRuntimeContext, FireWorkflowSystem.getInstance()); if (!startNewProcess) {//? if (correlation == null || StringUtils.isEmpty(correlation.getBody())) { throw new WebServiceException( "The correlation can NOT be empty; the callbackservice is " + callbackService.getName()); } //1?serviceIdservice versioncandidate activityInstance WorkflowQuery<ActivityInstance> query = session.createWorkflowQuery(ActivityInstance.class); List<ActivityInstance> candidates = query .add(Restrictions.eq(ActivityInstanceProperty.SERVICE_ID, callbackService.getId())) .add(Restrictions.eq(ActivityInstanceProperty.SERVICE_VERSION, callbackService.getVersion())) .add(Restrictions.eq(ActivityInstanceProperty.STATE, ActivityInstanceState.RUNNING)).list(); //2??correlation //correlationbool?processVars.var1==xpath(requestDom,'method1Request/id') ProcessInstance theProcessInstance = null; ActivityInstance theActivityInstance = null; if (candidates != null && candidates.size() > 0) { for (ActivityInstance activityInstance : candidates) { ProcessInstance processInstance = activityInstance.getProcessInstance(session); ((WorkflowSessionLocalImpl) session).setCurrentProcessInstance(processInstance); ((WorkflowSessionLocalImpl) session).setCurrentActivityInstance(activityInstance); Map<String, Object> varContext = ScriptEngineHelper.fulfillScriptContext(session, workflowRuntimeContext, processInstance, activityInstance); varContext.put(ScriptContextVariableNames.INPUTS, requestDOM); Object result = ScriptEngineHelper.evaluateExpression(workflowRuntimeContext, correlation, varContext); if (result != null && (result instanceof Boolean)) { if ((Boolean) result) { theActivityInstance = activityInstance; theProcessInstance = processInstance; break; } } } } final ActivityInstance theMatchedActivityInstance = theActivityInstance;//?activityInstance final ProcessInstance theMatchedProcessInstance = theProcessInstance; if (theMatchedActivityInstance != null) { //1?currentProcessInstanceCurrentActivityInstance ((WorkflowSessionLocalImpl) session).setCurrentActivityInstance(theMatchedActivityInstance); ((WorkflowSessionLocalImpl) session).setCurrentProcessInstance(theMatchedProcessInstance); try { this.transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { //2???? List<Assignment> inputAssignments_ = serviceBinding.getInputAssignments(); Map<String, Object> scriptContext = new HashMap<String, Object>(); scriptContext.put(ScriptContextVariableNames.INPUTS, requestDOM); try { ScriptEngineHelper.assignOutputToVariable(session, workflowRuntimeContext, theMatchedProcessInstance, theMatchedActivityInstance, inputAssignments_, scriptContext); } catch (ScriptException e) { throw new RuntimeException( "Can NOT assign inputs to process instance varialbes,the callback service is " + callbackService.getName(), e); } //3?closeActivity? ActivityInstanceManager actInstMgr = workflowRuntimeContext.getEngineModule( ActivityInstanceManager.class, theMatchedProcessInstance.getProcessType()); actInstMgr.onServiceCompleted(session, theMatchedActivityInstance); return null; } }); } catch (TransactionException e) { throw new WebServiceException(e); } //4? try { Map<String, Object> allTheVars = ScriptEngineHelper.fulfillScriptContext(session, workflowRuntimeContext, theMatchedProcessInstance, theMatchedActivityInstance); List<Assignment> outputAssignments = serviceBinding.getOutputAssignments(); Document doc = DOMInitializer.generateDocument(callbackService.getXmlSchemaCollection(), responseRootElementQName); allTheVars.put(ScriptContextVariableNames.OUTPUTS, doc); Map<String, Object> tmp = ScriptEngineHelper.resolveAssignments(workflowRuntimeContext, outputAssignments, allTheVars); Document resultDOM = (Document) tmp.get(ScriptContextVariableNames.OUTPUTS); return new DOMSource(resultDOM); } catch (ScriptException e) { throw new WebServiceException( "Can NOT assign process instance varialbes to output,the callback service is " + callbackService.getName(), e); } catch (ParserConfigurationException e) { throw new WebServiceException( "Can NOT init output DOM,the callback service is " + callbackService.getName(), e); } } else { throw new WebServiceException( "Process instance NOT found for the conditions as follows,service id='" + callbackService.getId() + "' and service version='" + callbackService.getVersion() + "' and correlation='" + correlation.getBody() + "'"); } } else {//?? //1????bizId final Map<String, Object> processVars; final String bizId; try { List<Assignment> inputAssignments_ = serviceBinding.getInputAssignments(); Map<String, Object> scriptContext = new HashMap<String, Object>(); scriptContext.put(ScriptContextVariableNames.INPUTS, requestDOM); Map<String, Object> temp = ScriptEngineHelper.resolveAssignments(workflowRuntimeContext, inputAssignments_, scriptContext); processVars = (Map<String, Object>) temp.get(ScriptContextVariableNames.PROCESS_VARIABLES); Map<String, Object> varContext = new HashMap<String, Object>(); varContext.put(ScriptContextVariableNames.INPUTS, requestDOM); Object result = ScriptEngineHelper.evaluateExpression(workflowRuntimeContext, correlation, varContext); bizId = result == null ? null : result.toString(); } catch (ScriptException e) { throw new WebServiceException( "Can NOT assign inputs to process instance varialbes,the callback service is " + callbackService.getName(), e); } //2??? ProcessInstance processInstance = null; try { processInstance = (ProcessInstance) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { WorkflowStatement stmt = session.createWorkflowStatement(processType); ProcessInstance procInst = null; try { procInst = stmt.startProcess(processId, bizId, processVars); } catch (InvalidModelException e1) { throw new RuntimeException("Start process instance error! The callback service is " + callbackService.getName() + "; the process is " + processId, e1); } catch (WorkflowProcessNotFoundException e1) { throw new RuntimeException("Start process instance error! The callback service is " + callbackService.getName() + "; the process is " + processId, e1); } catch (InvalidOperationException e1) { throw new RuntimeException("Start process instance error! The callback service is " + callbackService.getName() + "; the process is " + processId, e1); } return procInst; } }); } catch (TransactionException e) { throw new WebServiceException(e); } //3? try { Map<String, Object> allTheVars = ScriptEngineHelper.fulfillScriptContext(session, workflowRuntimeContext, processInstance, null); List<Assignment> outputAssignments = serviceBinding.getOutputAssignments(); // ?DOM Document doc = DOMInitializer.generateDocument(callbackService.getXmlSchemaCollection(), responseRootElementQName); allTheVars.put(ScriptContextVariableNames.OUTPUTS, doc); Map<String, Object> tmp = ScriptEngineHelper.resolveAssignments(workflowRuntimeContext, outputAssignments, allTheVars); Document resultDOM = (Document) tmp.get(ScriptContextVariableNames.OUTPUTS); return new DOMSource(resultDOM); } catch (ScriptException e) { throw new WebServiceException( "Can NOT assign process instance varialbes to output,the callback service is " + callbackService.getName(), e); } catch (ParserConfigurationException e) { throw new WebServiceException( "Can NOT init output DOM,the callback service is " + callbackService.getName(), e); } } }
From source file:org.geoserver.wfs.xslt.config.TransformRepositoryTest.java
@Test public void testTransform() throws Exception { TransformInfo info = new TransformInfo(); info.setName("test"); info.setSourceFormat("application/xml"); info.setOutputFormat("text/plain"); info.setFileExtension("txt"); info.setXslt("test-tx.xslt"); repo.putTransformInfo(info);/*from w w w .ja v a 2 s . c om*/ repo.putTransformSheet(info, getClass().getResourceAsStream("test.xslt")); Transformer transformer = repo.getTransformer(info); InputStream is = getClass().getResourceAsStream("sample.xml"); StreamSource source = new StreamSource(is); DOMResult result = new DOMResult(); transformer.transform(source, result); Document dom = (Document) result.getNode(); XMLAssert.assertXpathEvaluatesTo("12", "count(/html/body/table/tr/td)", dom); XMLAssert.assertXpathEvaluatesTo("1", "count(/html/body/table/tr[td='museum'])", dom); XMLAssert.assertXpathEvaluatesTo("1", "count(/html/body/table/tr[td='-74.0104611,40.70758763'])", dom); }
From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java
/** * Performs the transformation to the output result as Document. * * @param in - the XML document as <code>Source</code>. * @return String// w w w .j a v a 2 s.c o m * @throws TransformerException * @throws IOException */ public Document transformToDocument(Source in) throws TransformerException, IOException { // Create a Writer instance to hold transformation result DOMResult out = new DOMResult(); // Transformation this.transform(in, out); // Here is the newly transformed document return (Document) out.getNode(); }
From source file:org.infoscoop.dao.model.TabLayout.java
private Collection getPanelXmlWidgets(String uid, String tabId, String panelXml, boolean isStatic) throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer;/* w w w . j a v a 2 s. c o m*/ Collection widgetList = new ArrayList(); if (log.isDebugEnabled()) log.debug("--" + Thread.currentThread().getContextClassLoader()); InputStream xsl = Thread.currentThread().getContextClassLoader() .getResourceAsStream("widget_xml2object.xsl"); transformer = factory.newTransformer(new StreamSource(xsl)); DOMResult result = new DOMResult(); transformer.transform(new StreamSource(new StringReader("<widgets>" + panelXml + "</widgets>")), result); //Store widgets at the end of each line Map siblingMap = new HashMap(); Document widgets = (Document) result.getNode(); NodeList widgetNodeList = widgets.getElementsByTagName("widget"); for (int i = 0; i < widgetNodeList.getLength(); i++) { Element widgetEl = (Element) widgetNodeList.item(i); Widget widget = new Widget(); widget.setTabid(tabId); widget.setDeletedate(new Long(0)); widget.setWidgetid(widgetEl.getAttribute("widgetId")); widget.setUid(uid); //widget.setWidgetId(widgetEl.getAttribute("widgetId")); widget.setType(widgetEl.getAttribute("type")); String column = widgetEl.getAttribute("colnum"); if (column != null || !"".equals(column)) { try { widget.setColumn(Integer.valueOf(widgetEl.getAttribute("colnum"))); } catch (NumberFormatException e) { widget.setColumn(new Integer(0)); } } if (isStatic) { widget.setSiblingid(widgetEl.getAttribute("siblingId")); } else { String siblingId = (String) siblingMap.get(widget.getColumn()); if (siblingId != null) { widget.setSiblingid(siblingId); } siblingMap.put(widget.getColumn(), widget.getWidgetid()); } widget.setMenuid(isStatic ? "" : widget.getWidgetid().substring(2)); widget.setParentid(widgetEl.getAttribute("parentId")); widget.setTitle(widgetEl.getAttribute("title")); widget.setHref(widgetEl.getAttribute("href")); widget.setIgnoreHeader(new Boolean(widgetEl.getAttribute("ignoreHeader")).booleanValue()); widget.setNoBorder(new Boolean(widgetEl.getAttribute("noBorder")).booleanValue()); Element data = (Element) widgetEl.getElementsByTagName("data").item(0); NodeList propertyNodes = data.getElementsByTagName("property"); for (int k = 0; k < propertyNodes.getLength(); k++) { Element propEl = (Element) propertyNodes.item(k); widget.setUserPref(propEl.getAttribute("name"), getText(propEl)); } if (isStatic) { widget.setIsstatic(new Integer(1)); } else { widget.setIsstatic(new Integer(0)); } widgetList.add(widget); } return widgetList; }
From source file:org.lilyproject.runtime.tools.plugin.genclassloader.ClassloaderMojo.java
private void parseClassloaderTemplate(File file) { DOMResult domResult = null; Transformer transformer = null; try {/*from w w w . j av a2 s. c om*/ Source xmlSource = new StreamSource(file); TransformerFactory tfFactory = TransformerFactory.newInstance(); if (tfFactory.getFeature(DOMResult.FEATURE)) { transformer = tfFactory.newTransformer(); domResult = new DOMResult(); transformer.transform(xmlSource, domResult); } } catch (TransformerException ex) { throw new RuntimeException("Error parsing file '" + file + "'."); } if (domResult != null && transformer != null) { Document docu = (Document) domResult.getNode(); Element classpath; NodeList list; String shareSelf = docu.getDocumentElement().getAttribute("share-self").trim(); if (shareSelf.length() > 0) { this.shareSelf = shareSelf; } try { classpath = (Element) docu.getElementsByTagName("classpath").item(0); list = classpath.getElementsByTagName("artifact"); } catch (NullPointerException npex) { throw new RuntimeException("Classloader template is invalid."); } NamedNodeMap map; Entry entry; String groupId; String classifier; String artifactId; Element domArtifact; for (int i = 0; i < list.getLength(); i++) { domArtifact = (Element) list.item(i); map = domArtifact.getAttributes(); groupId = extractAttVal(map, "groupId"); artifactId = extractAttVal(map, "artifactId"); classifier = extractAttVal(map, "classifier"); entry = new Entry(groupId, artifactId, classifier); entryMap.put(entry, domArtifact); } } }
From source file:org.mule.module.xml.filters.AbstractJaxpFilter.java
public Node toDOMNode(Object src) throws Exception { if (src instanceof Node) { return (Document) src; } else if (src instanceof org.dom4j.Document) { org.dom4j.Document dom4j = (org.dom4j.Document) src; DOMDocument dom = new DOMDocument(); dom.setDocument(dom4j);//from w w w . ja v a 2 s . c om return dom; } else if (src instanceof OutputHandler) { OutputHandler handler = ((OutputHandler) src); ByteArrayOutputStream output = new ByteArrayOutputStream(); handler.write(RequestContext.getEvent(), output); InputStream stream = new ByteArrayInputStream(output.toByteArray()); return getDocumentBuilderFactory().newDocumentBuilder().parse(stream); } else if (src instanceof byte[]) { ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) src); return getDocumentBuilderFactory().newDocumentBuilder().parse(stream); } else if (src instanceof InputStream) { return getDocumentBuilderFactory().newDocumentBuilder().parse((InputStream) src); } else if (src instanceof String) { return getDocumentBuilderFactory().newDocumentBuilder() .parse(new InputSource(new StringReader((String) src))); } else if (src instanceof XMLStreamReader) { XMLStreamReader xsr = (XMLStreamReader) src; // StaxSource requires that we advance to a start element/document event if (!xsr.isStartElement() && xsr.getEventType() != XMLStreamConstants.START_DOCUMENT) { xsr.nextTag(); } return getDocumentBuilderFactory().newDocumentBuilder().parse(new InputSource()); } else if (src instanceof DelayedResult) { DelayedResult result = ((DelayedResult) src); DOMResult domResult = new DOMResult(); result.write(domResult); return domResult.getNode(); } else { return (Node) xmlToDom.transform(src); } }
From source file:org.mule.module.xml.filters.SchemaValidationFilter.java
/** * Accepts the message if schema validation passes. * //ww w . j a va2s.c o m * @param message The message. * @return Whether the message passes schema validation. */ public boolean accept(MuleMessage message) { Source source; try { source = loadSource(message); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (logger.isInfoEnabled()) { logger.info( "SchemaValidationFilter rejected a message because there was a problem interpreting the payload as XML.", e); } return false; } if (source == null) { if (logger.isInfoEnabled()) { logger.info("SchemaValidationFilter rejected a message because the XML source was null."); } return false; } DOMResult result = null; try { if (returnResult) { result = new DOMResult(); createValidator().validate(source, result); } else { createValidator().validate(source); } } catch (SAXException e) { if (logger.isDebugEnabled()) { logger.debug( "SchemaValidationFilter rejected a message because it apparently failed to validate against the schema.", e); } return false; } catch (IOException e) { if (logger.isInfoEnabled()) { logger.info( "SchemaValidationFilter rejected a message because there was a problem reading the XML.", e); } return false; } finally { if (result != null && result.getNode() != null) { message.setPayload(result.getNode()); } } if (logger.isDebugEnabled()) { logger.debug("SchemaValidationFilter accepted the message."); } return true; }
From source file:org.mule.module.xml.util.XMLUtils.java
/** * Converts a payload to a {@link org.w3c.dom.Document} representation. * <p> Reproduces the behavior from {@link org.mule.module.xml.util.XMLUtils#toDocument(Object, MuleContext)} * which works converting to {@link org.dom4j.Document}. * * @param payload the payload to convert. * @return a document from the payload or null if the payload is not a valid XML document. *//*www.j a v a2s . c o m*/ public static org.w3c.dom.Document toW3cDocument(Object payload) throws Exception { if (payload instanceof org.dom4j.Document) { DOMWriter writer = new DOMWriter(); org.w3c.dom.Document w3cDocument = writer.write((org.dom4j.Document) payload); return w3cDocument; } else if (payload instanceof org.w3c.dom.Document) { return (org.w3c.dom.Document) payload; } else if (payload instanceof org.xml.sax.InputSource) { return parseXML((InputSource) payload); } else if (payload instanceof javax.xml.transform.Source || payload instanceof javax.xml.stream.XMLStreamReader) { DOMResult result = new DOMResult(); Transformer idTransformer = getTransformer(); Source source = (payload instanceof Source) ? (Source) payload : toXmlSource(null, true, payload); idTransformer.transform(source, result); return (Document) result.getNode(); } else if (payload instanceof java.io.InputStream) { InputStreamReader input = new InputStreamReader((InputStream) payload); return parseXML(input); } else if (payload instanceof String) { Reader input = new StringReader((String) payload); return parseXML(input); } else if (payload instanceof byte[]) { // TODO Handle encoding/charset somehow Reader input = new StringReader(new String((byte[]) payload)); return parseXML(input); } else if (payload instanceof File) { Reader input = new FileReader((File) payload); return parseXML(input); } else { return null; } }
From source file:org.mule.module.xml.util.XMLUtils.java
/** * Convert our object to a Source type efficiently. *//*from w w w . j a v a2 s .c o m*/ public static javax.xml.transform.Source toXmlSource(javax.xml.stream.XMLInputFactory xmlInputFactory, boolean useStaxSource, Object src) throws Exception { if (src instanceof javax.xml.transform.Source) { return (Source) src; } else if (src instanceof byte[]) { ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) src); return toStreamSource(xmlInputFactory, useStaxSource, stream); } else if (src instanceof InputStream) { return toStreamSource(xmlInputFactory, useStaxSource, (InputStream) src); } else if (src instanceof String) { if (useStaxSource) { return new StaxSource(xmlInputFactory.createXMLStreamReader(new StringReader((String) src))); } else { return new StreamSource(new StringReader((String) src)); } } else if (src instanceof org.dom4j.Document) { return new DocumentSource((org.dom4j.Document) src); } else if (src instanceof org.xml.sax.InputSource) { return new SAXSource((InputSource) src); } // TODO MULE-3555 else if (src instanceof XMLStreamReader) { XMLStreamReader xsr = (XMLStreamReader) src; // StaxSource requires that we advance to a start element/document event if (!xsr.isStartElement() && xsr.getEventType() != XMLStreamConstants.START_DOCUMENT) { xsr.nextTag(); } return new StaxSource((XMLStreamReader) src); } else if (src instanceof org.w3c.dom.Document || src instanceof org.w3c.dom.Element) { return new DOMSource((org.w3c.dom.Node) src); } else if (src instanceof DelayedResult) { DelayedResult result = ((DelayedResult) src); DOMResult domResult = new DOMResult(); result.write(domResult); return new DOMSource(domResult.getNode()); } else if (src instanceof OutputHandler) { OutputHandler handler = ((OutputHandler) src); ByteArrayOutputStream output = new ByteArrayOutputStream(); handler.write(RequestContext.getEvent(), output); return toStreamSource(xmlInputFactory, useStaxSource, new ByteArrayInputStream(output.toByteArray())); } else { return null; } }
From source file:org.nuxeo.ecm.core.io.impl.TestTypedExportedDocument.java
/** * Transforms a dom4j document to a w3c Document. * * @param dom4jdoc the org.dom4j.Document document * @return the org.w3c.dom.Document document * @throws TransformerException the transformer exception */// w ww .ja v a 2s . c om protected final Document dom4jToW3c(org.dom4j.Document dom4jdoc) throws TransformerException { SAXSource source = new DocumentSource(dom4jdoc); DOMResult result = new DOMResult(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, result); return (Document) result.getNode(); }