@Override public void execute(BuildResult result) { String name = (container != null) ? "container " + container : "gradle"; Report report = new Report.Builder() .name(name) .subname(name) .elapsedTimeNanos(System.nanoTime() - startTimeNanos) .addAllTestCases(failureListener.getTestCases()) .build(); Document xml = reportToXml(report); targetFile.getParentFile().mkdirs(); try (FileWriter writer = new FileWriter(targetFile)) { XmlUtils.write(writer, xml); } catch (IOException | TransformerException e) { throw new RuntimeException(e); } }
@Override public void execute() throws BuildException { if (StringUtils.isEmpty(dirName)) { throw new BuildException("dirname is mandatory"); } if (StringUtils.isEmpty(fileName)) { throw new BuildException("filename is mandatory"); } File file = new File(dirName + File.separator + fileName); if (!file.exists()) { throw new BuildException("wsdl file does not exist"); } try { Document doc = parse(file); Element element = doc.createElement("documentation"); element.setTextContent("v" + version); doc.getElementsByTagName("definitions").item(0) .appendChild(element); save(dirName + File.separator + fileName, doc); } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { throw new BuildException(e); } }
/** * Take a SystemID string and try to turn it into a good absolute URI. * * @param urlString SystemID string * @param base The URI string used as the base for resolving the systemID * * @return The resolved absolute URI * @throws TransformerException thrown if the string can't be turned into a URI. */ public static String getAbsoluteURI(String urlString, String base) throws TransformerException { if (base == null) return getAbsoluteURI(urlString); String absoluteBase = getAbsoluteURI(base); URI uri = null; try { URI baseURI = new URI(absoluteBase); uri = new URI(baseURI, urlString); } catch (MalformedURIException mue) { throw new TransformerException(mue); } return replaceChars(uri.toString()); }
/** * Hulpmethode om een xml fragment uit een node te halen middels xpath. * @param locatie de locatie van de node als xpath. * @param xPath een XPath instantie * @param node de basis node * @return de text */ protected static String getXmlFragment(final String locatie, final XPath xPath, final Node node) { try { final Node xPathNode = (Node) xPath.evaluate(locatie, node, XPathConstants.NODE); if (xPathNode != null) { final StringWriter buf = new StringWriter(); final Transformer xform = TransformerFactory.newInstance().newTransformer(); xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); xform.transform(new DOMSource(xPathNode), new StreamResult(buf)); return buf.toString(); } } catch (final XPathExpressionException | TransformerException e) { LOGGER.error("XPath voor text content kon niet worden geëvalueerd voor locatie {}.", locatie); throw new UnsupportedOperationException(e); } return null; }
public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException { isSupported(returnType); try { Document document = getDocument(source); XObject resultObject = eval(expression, document); return getResultAsType(resultObject, returnType); } catch (TransformerException te) { Throwable nestedException = te.getException(); if (nestedException instanceof javax.xml.xpath.XPathFunctionException) { throw (javax.xml.xpath.XPathFunctionException)nestedException; } else { throw new XPathExpressionException (te); } } }
/** * Converts the given document to an XML string. Uses UTF-8 as character * encoding. * * @return the XML as byte array */ byte[] docToXml() { try { DOMSource domSource = new DOMSource(xmldoc); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); StreamResult result = new StreamResult(buffer); Transformer transformer = Transformers.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(domSource, result); return buffer.toByteArray(); } catch (TransformerException e) { throw new SaaSSystemException(e); } }
/** * Warn the user of a problem. * * @param msg An error msgkey that corresponds to one of the constants found * in {@link com.sun.org.apache.xpath.internal.res.XPATHErrorResources}, which is * a key for a format string. * @param args An array of arguments represented in the format string, which * may be null. * * @throws TransformerException if the current ErrorListoner determines to * throw an exception. */ void warn(String msg, Object[] args) throws TransformerException { String fmsg = XSLMessages.createXPATHWarning(msg, args); ErrorListener ehandler = this.getErrorListener(); if (null != ehandler) { // TO DO: Need to get stylesheet Locator from here. ehandler.warning(new TransformerException(fmsg, m_sourceLocator)); } else { // Should never happen. System.err.println(fmsg); } }
/** * Write out the non-default properties in this configuration to the given * {@link Writer}. * * @param out the writer to write to. */ public void writeXml(Writer out) throws IOException { Document doc = asXmlDocument(); try { DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); // Important to not hold Configuration log while writing result, since // 'out' may be an HDFS stream which needs to lock this configuration // from another thread. transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } }
private void generateForecast(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException { city = c; // creating the URL String url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + city + ",us&mode=xml&cnt=6&appid=" + APIKey; // printing out XML URL urlString = new URL(url); URLConnection conn = urlString.openConnection(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(conn.getInputStream()); TransformerFactory transformer = TransformerFactory.newInstance(); Transformer xform = transformer.newTransformer(); xform.transform(new DOMSource(doc), new StreamResult(System.out)); }
/** * Converts a given document into its string representation. * * @param doc * The document to be converted. * @param xmlDecl * should the output contain a XML declaration? * @return The string representation of the document. * @throws TransformerException * Thrown in case the conversion fails. */ private String getDocAsString(final Node doc) throws TransformerException { final DOMSource docSource = new DOMSource(doc); final TransformerFactory transformerFactory = TransformerFactory .newInstance(); final Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); final StringWriter buffer = new StringWriter(); transformer.transform(docSource, new StreamResult(buffer)); lastRequest = buffer.toString(); return lastRequest; }
TransformerFactory getFactory() throws Exception { if (fac == null) { fac = TransformerFactory.newInstance(); fac.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { try { return new StreamSource(asl2xml.class.getResource("/xml/" + href).openStream()); } catch (Exception e) { System.err.println("Error - " + href + "-" + base); e.printStackTrace(); return null; } } }); } return fac; }
/** * This method implements XSLTC's SourceLoader interface. It is used to * glue a TrAX URIResolver to the XSLTC compiler's Input and Import classes. * * @param href The URI of the document to load * @param context The URI of the currently loaded document * @param xsltc The compiler that resuests the document * @return An InputSource with the loaded document */ @Override public InputSource loadSource(String href, String context, XSLTC xsltc) { try { if (_uriResolver != null) { final Source source = _uriResolver.resolve(href, context); if (source != null) { return Util.getInputSource(xsltc, source); } } } catch (TransformerException e) { // should catch it when the resolver explicitly throws the exception final ErrorMsg msg = new ErrorMsg(ErrorMsg.INVALID_URI_ERR, href + "\n" + e.getMessage(), this); xsltc.getParser().reportError(Constants.FATAL, msg); } return null; }
private static void writeOut(Document doc) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); DOMSource source = new DOMSource(doc); File f = new File("splFile.xml"); f.delete(); StreamResult result = new StreamResult(f); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); }
/** * Pass error messages from the compiler to the error listener */ private void passErrorsToListener(ArrayList<ErrorMsg> messages) { try { if (_errorListener == null || messages == null) { return; } // Pass messages to listener, one by one final int count = messages.size(); for (int pos = 0; pos < count; pos++) { String message = messages.get(pos).toString(); _errorListener.error(new TransformerException(message)); } } catch (TransformerException e) { // nada } }
private static void writeOut(Document doc) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); DOMSource source = new DOMSource(doc); File f = new File("file.xml"); f.delete(); StreamResult result = new StreamResult(f); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); }
/** * Receive notification of a non-recoverable error. * The application must assume that the transformation cannot continue * after the Transformer has invoked this method, and should continue * (if at all) only to collect addition error messages. In fact, * Transformers are free to stop reporting events once this method has * been invoked. * * @param e The warning information encapsulated in a transformer * exception. * @throws TransformerException if the application chooses to discontinue * the transformation (always does in our case). */ @Override public void fatalError(TransformerException e) throws TransformerException { Throwable wrapped = e.getException(); if (wrapped != null) { System.err.println(new ErrorMsg(ErrorMsg.FATAL_ERR_PLUS_WRAPPED_MSG, e.getMessageAndLocation(), wrapped.getMessage())); } else { System.err.println(new ErrorMsg(ErrorMsg.FATAL_ERR_MSG, e.getMessageAndLocation())); } throw e; }
/** * Converts the Node/Element instance to XML payload. * * @param node the node/element instance to convert * @return the XML payload representing the node/element * @throws AlipayApiException problem converting XML to string */ public static String childNodeToString(Node node) throws AlipayApiException { String payload = null; try { Transformer tf = TransformerFactory.newInstance().newTransformer(); Properties props = tf.getOutputProperties(); props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES); tf.setOutputProperties(props); StringWriter writer = new StringWriter(); tf.transform(new DOMSource(node), new StreamResult(writer)); payload = writer.toString(); payload = payload.replaceAll(REG_INVALID_CHARS, " "); } catch (TransformerException e) { throw new AlipayApiException("XML_TRANSFORM_ERROR", e); } return payload; }
/** * Tell the user of an error, and probably throw an * exception. * * @param xctxt The XPath runtime context. * @param sourceNode Not used. * @param msg An error msgkey that corresponds to one of the constants found * in {@link com.sun.org.apache.xpath.internal.res.XPATHErrorResources}, which is * a key for a format string. * @param args An array of arguments represented in the format string, which * may be null. * * @throws TransformerException if the current ErrorListoner determines to * throw an exception. */ public void error( XPathContext xctxt, int sourceNode, String msg, Object[] args) throws javax.xml.transform.TransformerException { String fmsg = XSLMessages.createXPATHMessage(msg, args); ErrorListener ehandler = xctxt.getErrorListener(); if (null != ehandler) { ehandler.fatalError(new TransformerException(fmsg, (SAXSourceLocator)xctxt.getSAXLocator())); } else { SourceLocator slocator = xctxt.getSAXLocator(); System.out.println(fmsg + "; file " + slocator.getSystemId() + "; line " + slocator.getLineNumber() + "; column " + slocator.getColumnNumber()); } }
/** * Pass warning messages from the compiler to the error listener */ private void passWarningsToListener(ArrayList<ErrorMsg> messages) throws TransformerException { if (_errorListener == null || messages == null) { return; } // Pass messages to listener, one by one final int count = messages.size(); for (int pos = 0; pos < count; pos++) { ErrorMsg msg = messages.get(pos); // Workaround for the TCK failure ErrorListener.errorTests.error001. if (msg.isWarningError()) _errorListener.error( new TransformerConfigurationException(msg.toString())); else _errorListener.warning( new TransformerConfigurationException(msg.toString())); } }
@Test public void shouldBuildDocumentFromSetOfXPathsAndSetValues() throws XPathExpressionException, TransformerException, IOException { Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties(); Document document = documentBuilder.newDocument(); document.setXmlStandalone(true); Document builtDocument = new XmlBuilder(namespaceContext) .putAll(xmlProperties) .build(document); for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) { XPath xpath = xpathFactory.newXPath(); if (null != namespaceContext) { xpath.setNamespaceContext(namespaceContext); } assertThat(xpath.evaluate(xpathToValuePair.getKey(), builtDocument, XPathConstants.STRING)) .isEqualTo(xpathToValuePair.getValue()); } assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml()); }
public Document cloneDoc ( final Document doc ) throws TransformerException { final Transformer tx = this.tf.newTransformer (); final DOMSource source = new DOMSource ( doc ); final DOMResult result = new DOMResult (); tx.transform ( source, result ); return (Document)result.getNode (); }
/** * Transform an unformatted style-sheet file. TransformerException is thrown. */ @Test public void tfexception() { try { // invalid.xsl has well-formedness error. Therefore transform throws // TransformerException StreamSource streamSource = new StreamSource(new File(XML_DIR + "invalid.xsl")); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(streamSource); transformer.transform( new StreamSource(new File(XML_DIR + "cities.xml")), new SAXResult()); fail("TransformerException is not thrown as expected"); } catch (TransformerException e) { assertNotNull(e.getCause()); assertNotNull(e.getException()); assertNull(e.getLocationAsString()); assertEquals(e.getMessageAndLocation(),e.getMessage()); } }
/** * Get the source tree from the a base URL and a URL string. * * @param base The base URI to use if the urlString is relative. * @param urlString An absolute or relative URL string. * @param locator The location of the caller, for diagnostic purposes. * * @return should be a non-null reference to the node identified by the * base and urlString. * * @throws TransformerException If the URL can not resolve to a node. */ public int getSourceTree( String base, String urlString, SourceLocator locator, XPathContext xctxt) throws TransformerException { // System.out.println("getSourceTree"); try { Source source = this.resolveURI(base, urlString, locator); // System.out.println("getSourceTree - base: "+base+", urlString: "+urlString+", source: "+source.getSystemId()); return getSourceTree(source, locator, xctxt); } catch (IOException ioe) { throw new TransformerException(ioe.getMessage(), locator, ioe); } /* catch (TransformerException te) { throw new TransformerException(te.getMessage(), locator, te); }*/ }
/** * <p>Unwrap links</p> * * @param rtf The result tree fragment of the verbatim environment. * * @return The modified result tree fragment. */ public static NodeSetValue unwrapLinks (Context context, NodeSetValue rtf_ns) { FragmentValue rtf = (FragmentValue) rtf_ns; boolean tryAgain = true; setupUnwrapLinks(context); try { Controller controller = context.getController(); NamePool namePool = controller.getNamePool(); while (tryAgain) { UnwrapLinksEmitter ulEmitter = new UnwrapLinksEmitter(controller, namePool, foStylesheet); rtf.replay(ulEmitter); tryAgain = ulEmitter.tryAgain(); rtf = (FragmentValue) ulEmitter.getResultTreeFragment(); } return rtf; } catch (TransformerException e) { // This "can't" happen. System.out.println("Transformer Exception in unwrapLinks"); return rtf; } }
public static void references(XSLProcessorContext ctx, ElemExtensionCall call) throws TransformerException { TransformerImpl transformer = ctx.getTransformer(); XMLReaderContext xrctx = (XMLReaderContext) transformer.getParameter(XML_READER_CONTEXT_PARAMETER); xrctx.startRefScope(); transformer.executeChildTemplates(call, false); xrctx.endRefScope(); }
/** * Parst een verzoek XML op een generieke manier. Hierbij wordt er een {@link Node} en een {@link XPath} gebruikt. * @param node de {@link Node} * @return het {@link Verzoek} * @throws VerzoekParseException fout bij het parsen. */ public final T parse(final Node node) throws VerzoekParseException { try { final T verzoek = maakVerzoek(); final VerzoekParser<T> dienstBerichtParser = geefDienstSpecifiekeParser(node); dienstBerichtParser.vulStuurgegevens(verzoek, node, xpath); dienstBerichtParser.vulParameters(verzoek, node, xpath); dienstBerichtParser.vulDienstSpecifiekeGegevens(verzoek, node, xpath); zetBerichtXml(verzoek, node); return verzoek; } catch (final TransformerException | ParseException e) { throw new VerzoekParseException(e); } }
public void setURIResolver(javax.xml.transform.URIResolver uRIResolver) { try { materialize(); m_realTransformer.setURIResolver(uRIResolver); } catch (TransformerException e) { // will be caught later } }
/** * Get the match score of the given node. * * @param xctxt XPath runtime context. * @param context The current source tree context node. * * @return score, one of {@link #MATCH_SCORE_NODETEST}, * {@link #MATCH_SCORE_NONE}, {@link #MATCH_SCORE_OTHER}, * or {@link #MATCH_SCORE_QNAME}. * * @throws javax.xml.transform.TransformerException */ public double getMatchScore(XPathContext xctxt, int context) throws javax.xml.transform.TransformerException { xctxt.pushCurrentNode(context); xctxt.pushCurrentExpressionNode(context); try { XObject score = m_mainExp.execute(xctxt); if (DEBUG_MATCHES) { DTM dtm = xctxt.getDTM(context); System.out.println("score: " + score.num() + " for " + dtm.getNodeName(context) + " for xpath " + this.getPatternString()); } return score.num(); } finally { xctxt.popCurrentNode(); xctxt.popCurrentExpressionNode(); } // return XPath.MATCH_SCORE_NONE; }
public InputStream upsetTheNorm(String xPath, boolean remove) { try { document = dbf.newDocumentBuilder().parse(new File(pathname)); XPath xpath = xpf.newXPath(); XPathExpression expression = xpath.compile(xPath); NodeList searchedNodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); if (searchedNodes == null) { System.out.println("bad path: " + xPath); } else { for (int i = 0; i < searchedNodes.getLength(); i++) { Node searched = searchedNodes.item(i); Node owningElement = (searched instanceof ElementImpl) ? searched : ((AttrImpl) searched).getOwnerElement(); Node containingParent = owningElement.getParentNode(); if (remove) { containingParent.removeChild(owningElement); } else { containingParent.appendChild(owningElement.cloneNode(true)); } } } Transformer t = tf.newTransformer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); t.transform(new DOMSource(document), result); return new ByteArrayInputStream(os.toByteArray()); } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException | TransformerException ex) { throw new RuntimeException(ex); } }
private static void apiHarverst() throws IOException, ParserConfigurationException, TransformerException, SAXException, URISyntaxException { LOGGER.info("Initialize Properties"); File propertiesFile = new File(propertiesPath); Properties properties = new Properties(); //Properties on the level of the jar or in the resources directory if (propertiesFile.exists()) { properties.load(new FileInputStream(propertiesPath)); } else { properties.load(Main.class.getResourceAsStream("/" + propertiesPath)); } String apiEndpoint = properties.getProperty("api.endpoint"); String directoryNamePrefix = properties.getProperty("directory.name.prefix"); boolean jsonConvertToXml = Boolean .parseBoolean(properties.getProperty("json.convert.to.xml")); String offsetParameterName = properties.getProperty("offset.parameter.name"); String limitParameterName = properties.getProperty("limit.parameter.name"); int offset = Integer.parseInt(properties.getProperty("offset")); int limit = Integer.parseInt(properties.getProperty("limit")); String recordListField = properties.getProperty("record.list.field"); String harvestOutputDirectory = properties.getProperty("harvest.output.directory"); String rootElementName = properties.getProperty("root.element.name"); String listElementNames = properties.getProperty("list.element.names"); ApiHarvester apiHarvester = new ApiHarvester(apiEndpoint, directoryNamePrefix, jsonConvertToXml, recordListField, offsetParameterName, offset, limitParameterName, limit, harvestOutputDirectory); if (jsonConvertToXml) { apiHarvester.setRootElementName(rootElementName); apiHarvester.setListElementNames(listElementNames); } LOGGER.info("Initiate Harvest"); apiHarvester.harvest(false, true); }
public static final void arg(XSLProcessorContext ctx, ElemExtensionCall call) throws TransformerException { TransformerImpl transformer = ctx.getTransformer(); XMLReaderContext xrctx = (XMLReaderContext) transformer.getParameter(XML_READER_CONTEXT_PARAMETER); String role = getAttributeStringValue(ctx, call, "xpath-role", "role"); String ref = getAttributeStringValue(ctx, call, "xpath-ref", "ref"); xrctx.setArgument(role, ref); }
private String nodeToText(Node node) throws TransformerException { Transformer trans = TransformerFactory.newInstance().newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); trans.transform(new DOMSource(node), result); String bodyContent = writer.toString(); System.out.println("SOAP body content read by SAAJ:"+bodyContent); return bodyContent; }
/** * * PredicateExpr ::= Expr * * * @throws javax.xml.transform.TransformerException */ protected void PredicateExpr() throws javax.xml.transform.TransformerException { int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH); appendOp(2, OpCodes.OP_PREDICATE); Expr(); // Terminate for safety. m_ops.setOp(m_ops.getOp(OpMap.MAPINDEX_LENGTH), OpCodes.ENDOP); m_ops.setOp(OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) + 1); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); }
/** * Dumps the EPR infoset in a human-readable string. */ @Override public String toString() { try { // debug convenience StringWriter sw = new StringWriter(); XmlUtil.newTransformer().transform(asSource("EndpointReference"),new StreamResult(sw)); return sw.toString(); } catch (TransformerException e) { return e.toString(); } }
/** * The context of the right hand side expressions is the context of the * left hand side expression. The results of the right hand side expressions * are node sets. The result of the left hand side UnionExpr is the union * of the results of the right hand side expressions. * * * UnionExpr ::= PathExpr * | UnionExpr '|' PathExpr * * * @throws javax.xml.transform.TransformerException */ protected void UnionExpr() throws javax.xml.transform.TransformerException { int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH); boolean continueOrLoop = true; boolean foundUnion = false; do { PathExpr(); if (tokenIs('|')) { if (false == foundUnion) { foundUnion = true; insertOp(opPos, 2, OpCodes.OP_UNION); } nextToken(); } else { break; } // this.m_testForDocOrder = true; } while (continueOrLoop); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); }
void generateClass(ModelContext ctx) throws IOException, TransformerException { Transformer transformer = ctx.getTransformerFactory().newTransformer(new StreamSource(ctx.getLibraryClassTemplate())); FileObject fo = ctx.getFiler().createSourceFile(fullName, (javax.lang.model.element.Element[])null); PrintWriter out = new PrintWriter(fo.openWriter()); transformer.transform(new DOMSource(getDOM(ctx, XMLUtils.docBuilder)), new StreamResult(out)); out.close(); }
/** * * Argument ::= Expr * * * @throws javax.xml.transform.TransformerException */ protected void Argument() throws javax.xml.transform.TransformerException { int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH); appendOp(2, OpCodes.OP_ARGUMENT); Expr(); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); }
@Test public void run() throws TransformerFactoryConfigurationError, TransformerException { Transformer t = getTransformer(); t.setParameter("config", getClass().getResource("config.xml").toString()); t.setParameter("mapsFile", getClass().getResource("maps.xml").toString()); StringWriter resultWriter = new StringWriter(); t.transform(getStreamSource(), new StreamResult(resultWriter)); String resultString = resultWriter.toString(); Assert.assertTrue(resultString.contains("map1key1value") && resultString.contains("map2key1value")); }
/** * Use an XPath string to select a single node. * XPath namespace prefixes are resolved from the namespaceNode. * * @param contextNode The node to start searching from. * @param str A valid XPath string. * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. * @return The first node found that matches the XPath, or null. * * @throws TransformerException */ public Node selectSingleNode( Node contextNode, String str, Node namespaceNode) throws TransformerException { // Have the XObject return its result as a NodeSetDTM. NodeIterator nl = selectNodeIterator(contextNode, str, namespaceNode); // Return the first node, or null return nl.nextNode(); }