public void testLeadingWildcardType() throws Exception { QueryParser qp = getParser(null); qp.setAllowLeadingWildcard(true); assertEquals(WildcardQuery.class, qp.parse("t*erm*").getClass()); assertEquals(WildcardQuery.class, qp.parse("?term*").getClass()); assertEquals(WildcardQuery.class, qp.parse("*term*").getClass()); }
// generate the set of test request messages. public Vector<String> genTestParasSet(String sig, String entry, RequestMessage seed) { HashMap<String, String> parameters = _parser.parseInputParameters(seed.getInputParas()); HashMap<String, String> sessionVars = _parser.parseSession(seed.getSessionVars()); Vector<String> testParas = testProfiles.get(sig).getEntries().get(entry).genViolatedParas(parameters, sessionVars); return testParas; }
public void assertWildcardQueryEquals(String query, String result) throws Exception { QueryParser qp = getParser(null); Query q = qp.parse(query); String s = q.toString("field"); if (!s.equals(result)) { fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /" + result + "/"); } }
public boolean checkEqualityConstViolated( String sig, String entry, String inputParas, String session) { HashMap<String, String> parameters = _parser.parseInputParameters(inputParas); HashMap<String, String> sessionVars = _parser.parseSession(session); return (!testProfiles .get(sig) .getEntries() .get(entry) .checkEqualityConst(parameters, sessionVars)); }
/** This test differs from TestPrecedenceQueryParser */ public void testPrecedence() throws Exception { QueryParser qp = new QueryParser( TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false)); Query query1 = qp.parse("A AND B OR C AND D"); Query query2 = qp.parse("+A +B +C +D"); assertEquals(query1, query2); }
public void testAutoGeneratePhraseQueriesOn() throws Exception { // individual CJK chars as terms StandardAnalyzer analyzer = new StandardAnalyzer(TEST_VERSION_CURRENT); PhraseQuery expected = new PhraseQuery(); expected.add(new Term("field", "中")); expected.add(new Term("field", "国")); QueryParser parser = new QueryParser(TEST_VERSION_CURRENT, "field", analyzer); parser.setAutoGeneratePhraseQueries(true); assertEquals(expected, parser.parse("中国")); }
/** * Parses a module. * * @param io input reference * @return query parser * @throws QueryException query exception */ final QueryParser parseQuery(final IO io) throws QueryException { try (final QueryContext qctx = new QueryContext(qc)) { final String input = string(io.read()); // parse query final QueryParser qp = new QueryParser(input, io.path(), qctx, null); module = QueryProcessor.isLibrary(input) ? qp.parseLibrary(true) : qp.parseMain(); return qp; } catch (final IOException | QueryException ex) { throw IOERR_X.get(info, ex); } }
public void assertWildcardQueryEquals( String query, boolean lowercase, String result, boolean allowLeadingWildcard) throws Exception { QueryParser qp = getParser(null); qp.setLowercaseExpandedTerms(lowercase); qp.setAllowLeadingWildcard(allowLeadingWildcard); Query q = qp.parse(query); String s = q.toString("field"); if (!s.equals(result)) { fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /" + result + "/"); } }
public StrategyQueryBuilder(String topicsFile, boolean timesKey) throws MalformedURLException, DocumentException { queryProcessors = new ArrayList<QueryProcessor>(); topics = Dom4jUtil.parse(new File(topicsFile)); XPath xPath = topics.createXPath("//topic"); List<Element> topicsElems = xPath.selectNodes(topics); for (Element topic : topicsElems) { QueryParser queryParser = new QueryParser(topic); QueryProcessor queryProcessor = new QueryProcessor(queryParser.getQuery(), timesKey); queryProcessors.add(queryProcessor); } }
public void testMatchAllDocs() throws Exception { QueryParser qp = new QueryParser( TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false)); assertEquals(new MatchAllDocsQuery(), qp.parse("*:*")); assertEquals(new MatchAllDocsQuery(), qp.parse("(*:*)")); BooleanQuery bq = (BooleanQuery) qp.parse("+*:* -*:*"); assertTrue(bq.getClauses()[0].getQuery() instanceof MatchAllDocsQuery); assertTrue(bq.getClauses()[1].getQuery() instanceof MatchAllDocsQuery); }
/** * This will create a new instance of Project. It will find what to project and from where from * the statement passed. * * @param statement The literal of the project statement. */ public Project(final String statement) { setType(QueryParser.PROJECT); ArrayList<String> parts = QueryParser.parseStatementParts(statement); // Find the list of attributes to project attributes = QueryParser.parseQueryAttributes(parts.get(QueryParser.PROJECT_ATTRIBUTES_INDEX)); // Find the table its coming from tableOne = Operation.makeOperation(parts.get(QueryParser.PROJECT_FROM_INDEX)); tableOne.setParent(this); }
private void assertHits(int expected, String query, IndexSearcher is) throws ParseException, IOException { QueryParser qp = new QueryParser( TEST_VERSION_CURRENT, "date", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false)); qp.setLocale(Locale.ENGLISH); Query q = qp.parse(query); ScoreDoc[] hits = is.search(q, null, 1000).scoreDocs; assertEquals(expected, hits.length); }
public String selectList( String screenName, String panelname, String querynode, JSONObject jsonObject, InputDTO jsonInput, ResultDTO prevResultDTO) { String parsedquery = ""; try { String xmlconfigfile = ScreenMapRepo.findMapXMLPath(screenName); org.dom4j.Document document1 = new SAXReader().read(xmlconfigfile); org.dom4j.Element root = document1.getRootElement(); Node crudnode = root.selectSingleNode("//crud"); Node node = crudnode.selectSingleNode(querynode); if (node == null) throw new Exception("<" + querynode + "> node not defined"); String outstack = ((Element) node).attributeValue("outstack"); panelname = outstack; String updatequery = ""; updatequery += node.getText(); List<Element> nodeList = crudnode.selectNodes("../fields/field/*"); logger.debug("fields size:" + nodeList.size()); HashMap<String, DataType> hmfielddbtype = new HashMap<String, PrepstmtDTO.DataType>(); QueryParser.populateFieldDBType(nodeList, hmfielddbtype); /*Pattern pattern = Pattern.compile(":(\\w*)",Pattern.DOTALL|Pattern.MULTILINE); Matcher m = pattern.matcher(updatequery); while(m.find()){ String val = ""; logger.debug(m.group(0)+ " "+ m.group(1)); if(jsonObject.has(m.group(1))){ val = jsonObject.getString(m.group(1)); updatequery = updatequery.replaceAll(":"+m.group(1), val); } }*/ // SET List<Element> primarykeys = crudnode.selectNodes("../fields/field/*[@primarykey]"); PrepstmtDTOArray arparam = new PrepstmtDTOArray(); parsedquery = QueryParser.parseQuery( updatequery, panelname, jsonObject, arparam, hmfielddbtype, jsonInput, prevResultDTO); logger.debug( "UPDATE query:" + parsedquery + "\n Expanded prep:" + arparam.toString(parsedquery)); } catch (Exception e) { logger.debug("Exception caught in InsertData", e); } return parsedquery; }
public Query createQuery(String ejbql) { if (ejbql.indexOf('#') > 0) { QueryParser qp = new QueryParser(ejbql); Query query = delegate.createQuery(qp.getEjbql()); for (int i = 0; i < qp.getParameterValueBindings().size(); i++) { query.setParameter( QueryParser.getParameterName(i), qp.getParameterValueBindings().get(i).getValue()); } return query; } else { return delegate.createQuery(ejbql); } }
public void testBooleanQuery() throws Exception { BooleanQuery.setMaxClauseCount(2); try { QueryParser qp = new QueryParser( TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false)); qp.parse("one two three"); fail("ParseException expected due to too many boolean clauses"); } catch (ParseException expected) { // too many boolean clauses, so ParseException is expected } }
public void testDateRange() throws Exception { String startDate = getLocalizedDate(2002, 1, 1); String endDate = getLocalizedDate(2002, 1, 4); Calendar endDateExpected = new GregorianCalendar(); endDateExpected.clear(); endDateExpected.set(2002, 1, 4, 23, 59, 59); endDateExpected.set(Calendar.MILLISECOND, 999); final String defaultField = "default"; final String monthField = "month"; final String hourField = "hour"; QueryParser qp = new QueryParser( TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.SIMPLE, true)); // Don't set any date resolution and verify if DateField is used assertDateRangeQueryEquals( qp, defaultField, startDate, endDate, endDateExpected.getTime(), null); // set a field specific date resolution qp.setDateResolution(monthField, DateTools.Resolution.MONTH); // DateField should still be used for defaultField assertDateRangeQueryEquals( qp, defaultField, startDate, endDate, endDateExpected.getTime(), null); // set default date resolution to MILLISECOND qp.setDateResolution(DateTools.Resolution.MILLISECOND); // set second field specific date resolution qp.setDateResolution(hourField, DateTools.Resolution.HOUR); // for this field no field specific date resolution has been set, // so verify if the default resolution is used assertDateRangeQueryEquals( qp, defaultField, startDate, endDate, endDateExpected.getTime(), DateTools.Resolution.MILLISECOND); // verify if field specific date resolutions are used for these two fields assertDateRangeQueryEquals( qp, monthField, startDate, endDate, endDateExpected.getTime(), DateTools.Resolution.MONTH); assertDateRangeQueryEquals( qp, hourField, startDate, endDate, endDateExpected.getTime(), DateTools.Resolution.HOUR); }
@PooledConnection public JSONArray getRowsWithQuery( String keyspace, String columnFamily, String queryStr, ConsistencyLevel consistencyLevel) throws InvalidRequestException, UnavailableException, TimedOutException, TException, CharacterCodingException { Query query = QueryParser.parse(queryStr); SlicePredicate predicate = new SlicePredicate(); SliceRange range = new SliceRange(ByteBufferUtil.bytes(""), ByteBufferUtil.bytes(""), false, MAX_COLUMNS); predicate.setSlice_range(range); ColumnParent parent = new ColumnParent(columnFamily); IndexClause indexClause = new IndexClause(); indexClause.setCount(MAX_ROWS); indexClause.setStart_key(new byte[0]); for (String keyName : query.getEqStmt().keySet()) { indexClause.addToExpressions( new IndexExpression( ByteBufferUtil.bytes(keyName), IndexOperator.EQ, ByteBufferUtil.bytes(query.getEqStmt().get(keyName)))); } List<KeySlice> rows = getConnection(keyspace) .get_indexed_slices(parent, indexClause, predicate, ConsistencyLevel.QUORUM); return JsonMarshaller.marshallRows(rows, true); }
@Test public void testCreateTempTable3() throws QueryParserException { String sql = "Create TEMPORARY table tempTable (c1 boolean, c2 byte)"; assertEquals( "CREATE LOCAL TEMPORARY TABLE tempTable (c1 boolean, c2 byte)", QueryParser.getQueryParser().parseCommand(sql).toString()); // $NON-NLS-1$ }
// LUCENE-2002: make sure defaults for StandardAnalyzer's // enableStopPositionIncr & QueryParser's enablePosIncr // "match" public void testPositionIncrements() throws Exception { Directory dir = newDirectory(); Analyzer a = new StandardAnalyzer(TEST_VERSION_CURRENT); IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, a)); Document doc = new Document(); doc.add(newField("f", "the wizard of ozzy", Field.Store.NO, Field.Index.ANALYZED)); w.addDocument(doc); IndexReader r = IndexReader.open(w, true); w.close(); IndexSearcher s = newSearcher(r); QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "f", a); Query q = qp.parse("\"wizard of ozzy\""); assertEquals(1, s.search(q, 1).totalHits); s.close(); r.close(); dir.close(); }
public void assertQueryEquals(QueryParser qp, String field, String query, String result) throws Exception { Query q = qp.parse(query); String s = q.toString(field); if (!s.equals(result)) { fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result + "/"); } }
@Test public void testViewWithoutColumns() throws Exception { MetadataStore mds = new MetadataStore(); MetadataFactory mf = new MetadataFactory(null, 1, "VM1", getDataTypes(), new Properties(), null); parser.parseDDL(mf, "CREATE VIEW V1 AS SELECT * FROM PM1.G1"); mf.mergeInto(mds); }
private void searchFor(int n, Searcher searcher) throws Exception { System.out.println("Searching for " + n); Hits hits = searcher.search(QueryParser.parse(intToEnglish(n), "contents", ANALYZER)); System.out.println("Search for " + n + ": total=" + hits.length()); for (int j = 0; j < Math.min(3, hits.length()); j++) { System.out.println("Hit for " + n + ": " + hits.doc(j).get("id")); } }
/** * Parses and returns an xquery expression. * * @param cmd referring command; if specified, the result must not be empty * @return path * @throws QueryException query exception */ private String xquery(final Cmd cmd) throws QueryException { consumeWS(); final StringBuilder sb = new StringBuilder(); if (!eoc()) { final QueryContext qc = new QueryContext(ctx); try { final QueryParser p = new QueryParser(parser.input, null, qc, null); p.pos = parser.pos; p.parseMain(); sb.append(parser.input.substring(parser.pos, p.pos)); parser.pos = p.pos; } finally { qc.close(); } } return finish(sb, cmd); }
@Test(expected = MetadataException.class) public void testTableWithPlan() throws Exception { String ddl = "CREATE foreign table G1 as select 1"; MetadataStore mds = new MetadataStore(); MetadataFactory mf = new MetadataFactory(null, 1, "model", getDataTypes(), new Properties(), null); parser.parseDDL(mf, ddl); mf.mergeInto(mds); }
@Test(expected = MetadataException.class) public void testDuplicatePrimarykey() throws Exception { String ddl = "CREATE FOREIGN TABLE G1( e1 integer primary key, e2 varchar primary key)"; MetadataStore mds = new MetadataStore(); MetadataFactory mf = new MetadataFactory(null, 1, "model", getDataTypes(), new Properties(), null); parser.parseDDL(mf, ddl); mf.mergeInto(mds); }
@Test public void testAutoIncrementPrimarykey() throws Exception { String ddl = "CREATE FOREIGN TABLE G1( e1 integer auto_increment primary key, e2 varchar)"; MetadataStore mds = new MetadataStore(); MetadataFactory mf = new MetadataFactory(null, 1, "model", getDataTypes(), new Properties(), null); parser.parseDDL(mf, ddl); mf.mergeInto(mds); }
protected Object handleCreateQueryWithString(Method method, Object[] args) throws Throwable { if (args[0] == null) { return method.invoke(delegate, args); } String ejbql = (String) args[0]; if (ejbql.indexOf('#') > 0) { QueryParser qp = new QueryParser(ejbql); Object[] newArgs = args.clone(); newArgs[0] = qp.getEjbql(); Query query = (Query) method.invoke(delegate, newArgs); for (int i = 0; i < qp.getParameterValueBindings().size(); i++) { query.setParameter( QueryParser.getParameterName(i), qp.getParameterValueBindings().get(i).getValue()); } return query; } else { return method.invoke(delegate, args); } }
@Test public void testReservedURIDifferentNS() throws Exception { String ddl = "set namespace 'http://www.teiid.org/translator/salesforce/2012' AS ns"; MetadataStore mds = new MetadataStore(); MetadataFactory mf = new MetadataFactory(null, 1, "model", getDataTypes(), new Properties(), null); parser.parseDDL(mf, ddl); mf.mergeInto(mds); assertTrue(mf.getNamespaces().keySet().contains("ns")); assertEquals("http://www.teiid.org/translator/salesforce/2012", mf.getNamespaces().get("ns")); }
@Test public void testNamespace() throws Exception { String ddl = "set namespace 'http://teiid.org' AS teiid"; MetadataStore mds = new MetadataStore(); MetadataFactory mf = new MetadataFactory(null, 1, "model", getDataTypes(), new Properties(), null); parser.parseDDL(mf, ddl); mf.mergeInto(mds); assertTrue(mf.getNamespaces().keySet().contains("teiid")); assertEquals("http://teiid.org", mf.getNamespaces().get("teiid")); }
@Test(expected = MetadataException.class) public void testReservedNamespacePrefixMismatch() throws Exception { String ddl = "set namespace 'http://www.teiid.org/translator/salesforce/2012' AS teiid_foo"; MetadataStore mds = new MetadataStore(); MetadataFactory mf = new MetadataFactory(null, 1, "model", getDataTypes(), new Properties(), null); parser.parseDDL(mf, ddl); mf.mergeInto(mds); assertTrue(mf.getNamespaces().keySet().contains("teiid_foo")); assertEquals( "http://www.teiid.org/translator/salesforce/2012", mf.getNamespaces().get("teiid_foo")); }