public boolean searchSecQuery() throws XQException { String query = "declare default element namespace \"http://tpox-benchmark.com/security\";\n" + "for $sec in fn:collection(\"CLN_Security\")/s:Security\n" + "where $sec[SecurityInformation/*/Sector = 'Technology' and PE[. >= xs:decimal('25') and . < xs:decimal('28.0')] and Yield > xs:decimal('0')]\n" + "return <Security>\n" + "\t{$sec/Symbol}\n" + "\t{$sec/Name}\n" + "\t{$sec/SecurityType}\n" + "\t{$sec/SecurityInformation//Sector}\n" + "\t{$sec/PE}\n" + "\t{$sec/Yield}\n" + "</Security>"; XQExpression xqe = xqc.createExpression(); XQResultSequence xqs = xqe.executeQuery(query); int cnt = 0; while (xqs.next()) { cnt++; } System.out.println("Got " + cnt + " results"); return cnt > 0; }
public void storeSecCommand() throws XQException { String dName = "..\\..\\etc\\samples\\tpox\\"; String xml; try { xml = readTextFile(dName + "security5621.xml"); } catch (IOException ex) { throw new XQException(ex.getMessage()); } XQExpression xqe = xqc.createExpression(); xqe.bindString(new QName("doc"), xml, xqc.createAtomicType(XQItemType.XQBASETYPE_STRING)); xqe.executeCommand("storeDocument($doc)"); // todo: get XDMDocument back somehow.. // XDMDocument doc = (XDMDocument) ... xqe.close(); }
public boolean searchSecQuery() throws XQException { String query = "declare default element namespace \"http://tpox-benchmark.com/security\";\n" + "for $sec in fn:collection(\"/{http://tpox-benchmark.com/security}Security\")/Security\n" + "where $sec[SecurityInformation/*/Sector = 'Technology' and PE[. >= xs:decimal('25') and . < xs:decimal('28.0')] and Yield > xs:decimal('0')]\n" + "return <Security>\n" + "\t{$sec/Symbol}\n" + "\t{$sec/Name}\n" + "\t{$sec/SecurityType}\n" + "\t{$sec/SecurityInformation//Sector}\n" + "\t{$sec/PE}\n" + "\t{$sec/Yield}\n" + "</Security>"; XQExpression xqe = xqc.createExpression(); XQResultSequence xqs = xqe.executeQuery(query); int cnt = 0; while (xqs.next()) { cnt++; } System.out.println("Got " + cnt + " results"); return cnt > 0; }
@Test public void testGetBoolean() throws XQException { SaxonXQDataSource xqds = new SaxonXQDataSource(); XQConnection xqc = xqds.getConnection(); XQExpression xqe = xqc.createExpression(); xqe.bindObject(new QName("v"), Boolean.valueOf(true), null); XQSequence xqs = xqe.executeQuery("declare variable $v external; $v instance of xs:boolean"); xqs.next(); assertTrue("expected true but got false", xqs.getBoolean()); xqe.bindObject(new QName("v"), new Byte((byte) 1), null); xqs = xqe.executeQuery("declare variable $v external; $v instance of xs:byte"); xqs.next(); assertTrue("expected true (byte) but got false", xqs.getBoolean()); xqs.close(); }
public void queryChildTest() throws XQException { String query = //"declare namespace s=\"http://tpox-benchmark.com/security\";\n" + //"for $sec in fn:collection(\"/{http://tpox-benchmark.com/security}Security\")/s:Security\n" + "for $e in fn:collection(\"/document\")/document\n" + //"where $sec/s:Symbol=$sym\n" + //'IBM'\n" + "return $e//child\n"; XQExpression xqe = xqc.createExpression(); //xqe.bindString(new QName("doc"), xml, xqc.createAtomicType(XQItemType.XQBASETYPE_STRING)); XQResultSequence xqrs = xqe.executeQuery(query); assertNotNull(xqrs); assertFalse(xqrs.isClosed()); boolean found = false; while (xqrs.next()) { System.out.println(xqrs.getItemAsString(null)); found = true; } }
@Test public void queryParentTest() throws XQException { String query = //"declare namespace s=\"http://tpox-benchmark.com/security\";\n" + //"for $sec in fn:collection(\"/{http://tpox-benchmark.com/security}Security\")/s:Security\n" + "for $e in fn:collection(\"/document\")\n" + // /document\n" + //"where $e//child/parent::*[fn:count(*)=3]\n" + //"where fn:count($e//child/parent::*)=3\n" + "where $e/document/root//*[.='IBM']\n" + "return $e\n"; // starts with /document/root; // descendants of document/root; kind = text; XQExpression xqe = xqc.createExpression(); XQResultSequence xqrs = xqe.executeQuery(query); assertNotNull(xqrs); assertFalse(xqrs.isClosed()); boolean found = false; while (xqrs.next()) { System.out.println(xqrs.getItemAsString(null)); found = true; } }
@Test public void testWriteSequence() throws XQException { XQExpression xqe = xqc.createExpression(); XQSequence xqs = xqe.executeQuery("<e>Hello world!</e>"); StringWriter result = new StringWriter(); Properties prop = new Properties(); prop.setProperty("encoding", "UTF-8"); try { xqs.writeSequence(result, prop); } catch (XQException e) { fail("A-XQS-24.1: writeSequence failed with message: " + e.getMessage()); } assertTrue("A-XQS-24.1: Expects serialized result contains '<e>Hello world!</e>', but it is '" + result.toString() + "'", result.toString().indexOf("<e>Hello world!</e>") != -1); xqe.close(); }
@Test public void testGetBoolean() throws XQException { XQExpression xqe = xqc.createExpression(); xqe.bindObject(new QName("v"), Boolean.valueOf(true), null); xqe.bindBoolean(new QName("v"), true, xqc.createAtomicType(XQItemType.XQBASETYPE_BOOLEAN)); XQSequence xqs = xqe.executeQuery("declare variable $v external; $v instance of xs:boolean"); xqs.next(); assertTrue("expected true but got false", xqs.getBoolean()); //xqe.close(); //xqe = xqc.createExpression(); xqe.bindObject(new QName("v"), new Byte((byte)1), null); xqs = xqe.executeQuery("declare variable $v external; $v instance of xs:byte"); xqs.next(); assertTrue("expected true (byte) but got false", xqs.getBoolean()); }
/** * Bind parameter values to an XQuery expression. * * @param expression * XQuery expression * @param parameterMap * parameter key-value pairs */ public static void bindParameters(final XQExpression expression, final Map<String, String> parameterMap) { for (final String parameterName : parameterMap.keySet()) { final String parameterValue = parameterMap.get(parameterName); try { expression.bindString(new QName(parameterName), parameterValue, null); } catch (final XQException ex) { throw new ApplicationException("Failed to bind XQuery parameters", ex); } } }
@ManagedOperation(description="Run XQuery. Returns string output specified by XQuery") @ManagedOperationParameters({ @ManagedOperationParameter(name = "query", description = "A query request provided in XQuery syntax"), @ManagedOperationParameter(name = "useXDM", description = "use XDM (true) or XQJ query interface"), @ManagedOperationParameter(name = "props", description = "Query processing properties")}) public String runQuery(String query, boolean useXDM, Properties props) { logger.debug("runQuery.enter; got query: {}, properties: {}", query, props); String result = null; try { if (useXDM) { ResultCursor<XQItemAccessor> cursor = queryMgr.executeQuery(query, null, props); result = extractResult(cursor, props); cursor.close(); } else { XQStaticContext ctx = xqConn.getStaticContext(); props2Context(schemaManager.getEntity().getProperties(), ctx); props2Context(props, ctx); XQExpression xqExp = xqConn.createExpression(ctx); XQResultSequence xqSec = xqExp.executeQuery(query); result = xqSec.getSequenceAsString(props); xqExp.close(); } } catch (Exception ex) { logger.error("runQuery.error", ex); throw new RuntimeException(ex.getMessage()); } logger.debug("runQuery.exit; returning: {}", result); return result; }
public void removeSecCommand(long docId) throws XQException { XQExpression xqe = xqc.createExpression(); xqe.bindLong(new QName("docId"), docId, xqc.createAtomicType(XQItemType.XQBASETYPE_LONG)); xqe.executeCommand("removeDocument($docId)"); xqe.close(); }
@Override public String queryDocumentByUri(String uri) throws XQException { String query = "for $doc in fn:doc(\"" + uri + "\")\n" + "return $doc\n"; XQExpression xqe = xqConn.createExpression(); XQResultSequence xqs = xqe.executeQuery(query); String result = null; if (xqs.next()) { result = xqs.getItemAsString(null); } return result; }
@Override public String queryDocumentFromCollection() throws XQException { String query = "for $doc in fn:collection()\n" + "return $doc\n"; XQExpression xqe = xqConn.createExpression(); XQResultSequence xqs = xqe.executeQuery(query); String result = null; if (xqs.next()) { result = xqs.getItemAsString(null); } return result; }
@Override protected int execCommand(String query, Map<String, Parameter> params) throws XQException { XQExpression xqe = getConnection().createExpression(); bindParams(params, xqe); xqe.executeCommand(query); // do next somehow! xqe.close(); return 1; }
@Test public void testSaxon() throws XQException { SaxonXQDataSource xqds = new SaxonXQDataSource(); XQConnection xqc = xqds.getConnection(); XQExpression xqe = xqc.createExpression(); XQSequence xqs = xqe.executeQuery("<e>Hello world!</e>"); //XQSequence xqs = xqe.executeQuery("<a b='c'>{5+2}</a>"); while (xqs.next()) { System.out.println(xqs.getItemAsString(null)); } //System.out.println(xqds.getSchemaValidationMode()); }
@Test public void testGetByte() throws XQException { SaxonXQDataSource xqds = new SaxonXQDataSource(); XQConnection xqc = xqds.getConnection(); XQExpression xqe = xqc.createExpression(); XQSequence xqs = xqe.executeQuery("xs:byte('1')"); xqs.next(); Object o = xqs.getObject(); assertTrue(o instanceof Byte); xqe.close(); }
@Override public XQExpression createExpression(XQStaticContext context) throws XQException { checkState(ex_connection_closed); if (context == null) { throw new XQException(ex_null_context); } return new BagriXQExpression(this, context); }
@AfterClass public static void tearDownAfterClass() throws Exception { XQConnection xqc = xqds.getConnection(); try { XQExpression xqe = xqc.createExpression(); xqe.bindLong(new QName("docId"), axisId, xqc.createAtomicType(XQItemType.XQBASETYPE_LONG)); xqe.executeCommand("removeDocument($docId)"); xqe.close(); } finally { xqc.close(); } }
@Test public void testGetItem() throws XQException { XQExpression xqe = xqc.createExpression(); XQSequence xqs = xqe.executeQuery("1,2,3,4"); xqs.next(); xqs.close(); try { xqs.getItem(); fail("A-XQS-1.2: closed sequence supports getItem()"); } catch (XQException e) { // Expect an XQException } xqe.close(); }
@Test public void testGetBoolean() throws XQException { XQExpression xqe = xqc.createExpression(); XQSequence xqs = xqe.executeQuery("xs:boolean('true')"); xqs.next(); xqs.getItem(); try { xqs.getBoolean(); fail("A-XQIA-1.4: SCROLLTYPE_FORWARD_ONLY sequence supports getting item twice()"); } catch (XQException e) { // Expect an XQException } xqe.close(); }
@Test public void testSequence() throws XQException { String query = "<e>Hello world!</e>"; XQExpression xqe = xqc.createExpression(); XQSequence xqs = xqe.executeQuery(query); assertTrue(xqs.next()); String value = xqs.getItemAsString(null); xqe.close(); assertEquals(query, value); }
@Test public void testNamespace() throws XQException { XQStaticContext xqsc = xqc.getStaticContext(); xqsc.declareNamespace("foo", "http://www.foo.com"); XQExpression xqe = xqc.createExpression(xqsc); XQSequence xqs = xqe.executeQuery("<foo:e/>"); xqe.close(); }
@Test public void testBasicType() throws XQException { XQExpression xqe = xqc.createExpression(); XQSequence xqs = xqe.executeQuery("1,2"); boolean b = xqs.next(); assertEquals("A-XQS-18.1: next() failed", true, b); int type = xqs.getInt(); assertEquals("A-XQS-18.1: next() failed", 1, type); }
public static ArrayList<String> sort(String xmlns, String fileName, String elementName, boolean isAsc) throws XQException { URI uri = new File(fileName).toURI(); String uriPath = uri.getPath(); ArrayList<String> rowIds = new ArrayList<String>(); XQDataSource dataSource = new SaxonXQDataSource(); XQConnection conn = dataSource.getConnection(); String queryString = "for $file in doc(\'" + uriPath + "')/xliff/file," + " $tu in $file/body//trans-unit order by $tu/" + elementName + " " + (isAsc ? "" : "descending") + " return <file original='{$file/@original}' tuid='{$tu/@id}'></file>"; if (xmlns != null) { queryString = "declare default element namespace '" + xmlns + "';" + queryString; } XQExpression expression = conn.createExpression(); XQSequence results = expression.executeQuery(queryString); while (results.next()) { Node node = results.getNode(); String original = node.getAttributes().getNamedItem("original").getNodeValue(); String tuid = node.getAttributes().getNamedItem("tuid").getNodeValue(); String rowId = RowIdUtil.getRowId(fileName, original, tuid); rowIds.add(rowId); } // 释放资源 results.close(); expression.close(); conn.close(); return rowIds; }
/** * Helper method to retrieve {@link XQExpression} from {@link XQConnection} * * @param xqConnection * the {@link XQConnection} to retrieve the expression from * @return a XQExpression * @throws ApplicationException * if an exception occurs while trying to create the expression */ public static XQExpression createExpression(final XQConnection xqConnection) { try { return xqConnection.createExpression(); } catch (final XQException e) { throw new ApplicationException("Unable to get XQExpression", e); } }
@Override public XQExpression createExpression() throws XQException { checkState(ex_connection_closed); return new BagriXQExpression(this); }
/** * 查询 * @param queryString * XQuery查询语句 * @return RowId集合 * @throws XQException ; */ private static ArrayList<String> qurey(String queryString) throws XQException { XQDataSource dataSource = new SaxonXQDataSource(); XQConnection conn = null; XQExpression expression = null; XQSequence results = null; try { conn = dataSource.getConnection(); expression = conn.createExpression(); results = expression.executeQuery(queryString); LinkedHashSet<String> set = new LinkedHashSet<String>(); while (results.next()) { Node node = results.getNode(); String fileName = node.getAttributes().getNamedItem("fileName").getNodeValue(); String original = node.getAttributes().getNamedItem("original").getNodeValue(); String tuid = node.getAttributes().getNamedItem("tuid").getNodeValue(); // 解决 Windows 平台下,无法查询“重复文本段”的问题“: // 这里返回的是 URI,因此需要转成操作系统的标准文件路径。 // 注:在 Winodws 平台中文件路径分隔符使用“\”,而在 URI 标准中文件路径分隔符使用“/”,并且会以“/”为根, // 因此,Windows 的路径“c:\test.txt”,使用 URI 表示为“/c:/test.txt”。 fileName = new File(fileName).getAbsolutePath(); String rowId = RowIdUtil.getRowId(fileName, original, tuid); set.add(rowId); } return new ArrayList<String>(set); } finally { // 释放资源 if (results != null && !results.isClosed()) { results.close(); } if (expression != null && !expression.isClosed()) { expression.close(); } if (conn != null && !conn.isClosed()) { conn.close(); } } }
/** * 繁殖翻译文本段的查询 robert 2012-04-03 * @param queryString * XQuery查询语句 * @return RowId集合 * @throws XQException * ; */ public static Map<String, List<String>> PropagateQurey(String queryString) throws XQException { XQDataSource dataSource = new SaxonXQDataSource(); XQConnection conn = null; XQExpression expression = null; XQSequence results = null; try { conn = dataSource.getConnection(); expression = conn.createExpression(); results = expression.executeQuery(queryString); Map<String, List<String>> resultMap = new HashMap<String, List<String>>(); while (results.next()) { Node node = results.getNode(); // System.out.println("node.getChildNodes().getLength() = " + node.getChildNodes().getLength()); if (node.getChildNodes().getLength() >= 1) { String rootFileName = node.getAttributes().getNamedItem("fileName").getNodeValue(); rootFileName = new File(rootFileName).getAbsolutePath(); String rootOriginal = node.getAttributes().getNamedItem("original").getNodeValue(); String rootTuid = node.getAttributes().getNamedItem("tuid").getNodeValue(); String rootRowId = RowIdUtil.getRowId(rootFileName, rootOriginal, rootTuid); if (!resultMap.keySet().contains(rootRowId)) { resultMap.put(rootRowId, new ArrayList<String>()); } NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { if (nodeList.item(i).getAttributes() == null) { continue; } String fileName = nodeList.item(i).getAttributes().getNamedItem("fileName").getNodeValue(); fileName = new File(fileName).getAbsolutePath(); String original = nodeList.item(i).getAttributes().getNamedItem("original").getNodeValue(); String tuid = nodeList.item(i).getAttributes().getNamedItem("tuid").getNodeValue(); String rowId = RowIdUtil.getRowId(fileName, original, tuid); resultMap.get(rootRowId).add(rowId); } } } return resultMap; } finally { // 释放资源 if (results != null && !results.isClosed()) { results.close(); } if (expression != null && !expression.isClosed()) { expression.close(); } if (conn != null && !conn.isClosed()) { conn.close(); } } }
/** * 测试过滤重复文本段 robert 2012-06-11 * @throws XQException */ private static void testRpeateed() throws XQException{ String xqueryStr_1 = "declare namespace ns0='urn:oasis:names:tc:xliff:document:1.2'; " + "for $t in (let $allTU_1 := ( " + " for $file0 in doc('/home/robert/workspace/runtime-UltimateEdition.product/test/XLIFF/zh-CN/user_defineed_filter4.doc.xlf')/ns0:xliff/ns0:file[upper-case(@source-language)='EN-US' " + " and upper-case(@target-language)='ZH-CN'], " + " $tu0 in $file0/ns0:body//ns0:trans-unit " + " return <tu fileName='/home/robert/workspace/runtime-UltimateEdition.product/test/XLIFF/zh-CN/user_defineed_filter4.doc.xlf' original='{$file0/@original}' tuid='{$tu0/@id}' source='{$tu0/ns0:source/text()}' />), " + " $allTU := for $allTU1 in $allTU_1 return <tu fileName='{$allTU1/@fileName}' original='{$allTU1/@original}' tuid='{$allTU1/@tuid}' source='{normalize-space($allTU1/@source)}' /> ," + " $id := (for $src in distinct-values($allTU/@source) " + " return <root>{if (count($allTU[@source=$src])>1) then <src>{$src}</src> else ''}</root>)/src/text(), " + " $tu := $allTU[@source=$id] return $tu) order by $t/@source " + " return <tu fileName='{$t/@fileName}' original='{$t/@original}' tuid='{$t/@tuid}' /> "; String xqueryStr = "declare namespace ns0='urn:oasis:names:tc:xliff:document:1.2'; \n" + "declare function local:getPureText ($srcText1 as xs:anyType) as xs:anyType {\n" + "let $result := srcText1 \n" + "return $result }; \n" + "for $t in (let $allTU := ( \n" + " for $file0 in doc('/home/robert/workspace/runtime-UltimateEdition.product/test/XLIFF/zh-CN/user_defineed_filter4.doc.xlf')/ns0:xliff/ns0:file[upper-case(@source-language)='EN-US' \n" + " and upper-case(@target-language)='ZH-CN'], \n" + " $tu0 in $file0/ns0:body//ns0:trans-unit \n" + " return <tu fileName='/home/robert/workspace/runtime-UltimateEdition.product/test/XLIFF/zh-CN/user_defineed_filter4.doc.xlf' original='{$file0/@original}' tuid='{$tu0/@id}' source='{$tu0/ns0:source/text()}' />) \n" + " return $allTU )\n " + " return <tu fileName='{$t/@fileName}' original='{$t/@original}' tuid='{$t/@tuid}' source='{$t/@source}'/> \n"; XQDataSource dataSource = new SaxonXQDataSource(); XQConnection conn = null; XQExpression expression = null; XQSequence results = null; try { conn = dataSource.getConnection(); expression = conn.createExpression(); results = expression.executeQuery(xqueryStr); while (results.next()) { Node node = results.getNode(); String fileName = node.getAttributes().getNamedItem("fileName").getNodeValue(); String original = node.getAttributes().getNamedItem("original").getNodeValue(); String tuid = node.getAttributes().getNamedItem("tuid").getNodeValue(); String source = node.getAttributes().getNamedItem("source").getNodeValue(); System.out.println(source); // System.out.println(tuid); } return; } finally { // 释放资源 if (results != null && !results.isClosed()) { results.close(); } if (expression != null && !expression.isClosed()) { expression.close(); } if (conn != null && !conn.isClosed()) { conn.close(); } } }
public static void main(final String[] args) throws Exception { //get the command line arguments if(args.length < 5) { printUseage(); System.exit(1); return; } final String server = args[0]; final String port = args[1]; final String query = args[2]; final File queryFile; if(query.charAt(0) == '@') { queryFile = new File(query.substring(1)); if(!queryFile.exists()) { System.err.println("Query file '" + queryFile.getAbsolutePath() + "' does not exist!"); System.exit(2); } } else { queryFile = null; } final String path = args[3]; final String username = args[4]; final String password; if(args.length == 6) { password = args[5]; } else { password = ""; } //setup the Data Source final XQDataSource dataSource = new ExistXQDataSource(); dataSource.setProperty("serverName", server); dataSource.setProperty("port", port); //get connection with authenticated credentials XQConnection connection = null; try { connection = dataSource.getConnection(username, password); final String uri = "http://" + server + ":" + port + "/exist/rest" + path; logger.info("Starting Query of {}...", uri); //execute the query expression final XQExpression expression = connection.createExpression(); final XQResultSequence result; if(queryFile == null) { result = expression.executeQuery(query); } else { InputStream is = null; try { is = new FileInputStream(queryFile); result = expression.executeQuery(is); } finally { if(is != null) { is.close(); } } } //output the results boolean producedResults = false; while(result.next()) { result.writeItem(System.out, null); producedResults = true; } if(producedResults) { System.out.println(); } else { logger.warn("Your XQuery produced no results!"); } logger.info("Finished Query OK."); } finally { if(connection != null) { connection.close(); } } }
/** * Bind an XQuery program to an expression parameter. * * @param expression * XQuery expression * @param parameterName * name of parameter to bind program to * @param inputStream * XQuery program input stream * @throws XQException */ public static void bindDocument(final XQExpression expression, final String parameterName, final InputStream inputStream) throws XQException { final XMLStreamReader xmlStreamReader = getXmlStreamReader(inputStream); expression.bindDocument(new QName(XQueryUtil.DOCUMENT_NAME), xmlStreamReader, null); }
/** * Helper method to retrieve a {@link XQExpression} from a {@link XQDataSource} * * @param xqDataSource * the {@link XQDataSource} TO USE * @return a XQExpression * @throws ApplicationException * if an exception occurs while trying to create the expression */ public static XQExpression createExpression(final XQDataSource xqDataSource) { return createExpression(getConnection(xqDataSource)); }
/** * Bind an XQuery program to the standardly-named {@link XQueryUtil#DOCUMENT_NAME} * expression parameter. * * @param expression * XQuery expression * @param inputStream * XQuery program input stream * @throws XQException */ public static void bindDocument(final XQExpression expression, final InputStream inputStream) throws XQException { bindDocument(expression, XQueryUtil.DOCUMENT_NAME, inputStream); }