javax.jcr.query.Query类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(13.2k)|赞(0)|评价(0)|浏览(187)

本文整理了Java中javax.jcr.query.Query类的一些代码示例,展示了Query类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Query类的具体详情如下:
包路径:javax.jcr.query.Query
类名称:Query

Query介绍

[英]A Query object.
[中]Query对象。

代码示例

代码示例来源:origin: stackoverflow.com

Blob imageFor(String name, HttpServletResponse res) {
  // find desired image
  PersistenceManager pm = PMF.get().getPersistenceManager();
  Query query = pm.newQuery("select from MyImage " +
    "where name = nameParam " +
    "parameters String nameParam");
  List<MyImage> results = (List<MyImage>)query.execute(name);
  Blob image = results.iterator().next().getImage();

  // serve the first image
  res.setContentType("image/jpeg");
  res.getOutputStream().write(image.getBytes());
}

代码示例来源:origin: stackoverflow.com

public StockClient[] getStocks() throws NotLoggedInException {
 checkLoggedIn();
 PersistenceManager pm = getPersistenceManager();
 List<StockClient> stockclients = new ArrayList<StockClient>();
 try {
  Query q = pm.newQuery(Stock.class, "user == u");
  q.declareParameters("com.google.appengine.api.users.User u");
  q.setOrdering("createDate");
  List<Stock> stocks = (List<Stock>) q.execute(getUser());
  for (Stock stock : stocks)
  {
    stockclients.add(new StockClient(stock.getId(), stock.getSymbol(), stock.getCreateDate()));
  }
 } finally {
  pm.close();
 }
 return (StockClient[]) stockclients.toArray(new StockClient[0]);
}

代码示例来源:origin: org.onehippo.cms7/hippo-addon-channel-manager-content-service

static NodeIterator executeQuery(final Session session, final Node templateQueryNode) throws RepositoryException {
  final String statement = templateQueryNode.getProperty("jcr:statement").getString();
  final String language =  templateQueryNode.getProperty("jcr:language").getString();
  final QueryManager queryManager = session.getWorkspace().getQueryManager();
  final Query query = queryManager.createQuery(statement, language);
  final QueryResult queryResult = query.execute();
  return queryResult.getNodes();
}

代码示例来源:origin: apache/jackrabbit

public void testSimpleQuerySQL4() throws Exception {
  Node foo = testRootNode.addNode("foo");
  foo.setProperty("bla", new String[]{"bla"});
  Node bla = testRootNode.addNode("bla");
  bla.setProperty("bla", new String[]{"bla"});
  testRootNode.save();
  String sql = "SELECT * FROM nt:unstructured WHERE jcr:path LIKE '" + testRoot + "/%'";
  Query q = superuser.getWorkspace().getQueryManager().createQuery(sql, Query.SQL);
  QueryResult result = q.execute();
  checkResult(result, 2);
}

代码示例来源:origin: apache/jackrabbit-oak

private void run0() throws RepositoryException {
    session.refresh(false);
    QueryManager qm = session.getWorkspace().getQueryManager();
    Query q = qm.createQuery("select * from [nt:base] where [" + indexedPropName + "] = $status " +
        "option(index tag fooIndex)", Query.JCR_SQL2);
    q.bindValue("status", session.getValueFactory().createValue(randomStatus()));
    QueryResult result = q.execute();
    //With property index at time traversing index wins (somehow reporting lower cost)
    //and that leads to warning. So limit the iterator size
    resultSize += Iterators.size(Iterators.limit(result.getNodes(), 500));
  }
}

代码示例来源:origin: apache/jackrabbit

public void testGetSize() throws RepositoryException {
  QueryManager qm = superuser.getWorkspace().getQueryManager();
  for (int i = 0; i < 10; i++) {
    String stmt = testPath + "/*[@" + propertyName1 + " < 1000]";
    QueryResult result = qm.createQuery(stmt, Query.XPATH).execute();
    assertEquals("Wrong size of NodeIterator in result",
        INITIAL_NODE_NUM - i, result.getNodes().getSize());
    // remove node for the next iteration
    testRootNode.getNode("node" + i).remove();
    testRootNode.save();
  }
}

代码示例来源:origin: com.geeoz.atom/atom-kie

final Session session = activity.getNewJcrSession();
  final QueryManager queryManager =
      session.getWorkspace().getQueryManager();
  final Query query =
      queryManager.createQuery(request, Query.JCR_SQL2);
  final Map<String, Object> map = item.getParameters();
    final String entryValue = (String) entry.getValue();
    final Value value =
        session.getValueFactory().createValue(entryValue);
    query.bindValue(entryKey, value);
  final QueryResult result = query.execute();
  final NodeIterator iterator = result.getNodes();
  while (iterator.hasNext()) {
    final Node node = iterator.nextNode();
    item.getResults().put("id", node.getIdentifier());
  session.logout();
} catch (RepositoryException e) {
  e.printStackTrace();

代码示例来源:origin: info.magnolia.ui/magnolia-ui-framework

protected QueryResult executeQuery(String statement, String language, int limit, int offset) throws RepositoryException {
  final Session jcrSession = MgnlContext.getJCRSession(WORKSPACE_NAME);
  final QueryManager jcrQueryManager = jcrSession.getWorkspace().getQueryManager();
  final Query query = jcrQueryManager.createQuery(statement, language);
  if (limit > 0) {
    query.setLimit(limit);
  }
  if (offset >= 0) {
    query.setOffset(offset);
  }
  logger.debug("Executing query against workspace [{}] with statement [{}] and limit {} and offset {}...", new Object[]{WORKSPACE_NAME, statement, limit, offset});
  long start = System.currentTimeMillis();
  final QueryResult result = query.execute();
  logger.debug("Query execution took {} ms", System.currentTimeMillis() - start);
  return result;
}

代码示例来源:origin: apache/jackrabbit-oak

public void testScoreWithOr() throws Exception {
  Session session = superuser;
  QueryManager qm = session.getWorkspace().getQueryManager();
  Node n1 = testRootNode.addNode("node1");
  n1.setProperty("text", "hello");
  n1.setProperty("id", "1");
  session.save();
  String xpath = "/jcr:root//*[jcr:contains(@text, 'hello') or @id = '1']";
  Query q = qm.createQuery(xpath, "xpath");
  String result = getResult(q.execute(), "jcr:path");
  assertEquals("/testroot/node1", result);
}

代码示例来源:origin: apache/jackrabbit

public void testFulltextBindVariableSQL() throws Exception {
  Node foo = testRootNode.addNode("foo");
  foo.setProperty("mytext", new String[]{"the quick brown fox jumps over the lazy dog."});
  
  testRootNode.save();
  
  String sql = "SELECT * FROM [nt:unstructured]"
    + " WHERE ISCHILDNODE([" + testRoot + "])"
    + " AND CONTAINS(mytext, $searchExpression)";
  Query q = superuser.getWorkspace().getQueryManager().createQuery(sql, Query.JCR_SQL2);
  assertEquals("Expected exactly 1 bind variable", 1, q.getBindVariableNames().length);
  assertEquals("searchExpression", q.getBindVariableNames()[0]);
  q.bindValue("searchExpression", superuser.getValueFactory().createValue("fox"));
  QueryResult result = q.execute();
  checkResult(result, 1);
}

代码示例来源:origin: info.magnolia.templating/magnolia-templating-essentials-models

final QueryManager jcrQueryManager = jcrSession.getWorkspace().getQueryManager();
final Query query = jcrQueryManager.createQuery(String.format(SEARCH_QUERY_PATTERN, StringUtils.defaultIfBlank(returnItemType, JcrConstants.NT_BASE), startPath, queryString), Query.SQL);
query.setLimit(limit);
query.setOffset(offset);
log.debug("Executing query against workspace [{}] with statement [{}] and limit {} and offset {}...", workspace, query.getStatement(), limit, offset);
long start = System.currentTimeMillis();
QueryResult qr = query.execute();
log.debug("Query execution took {} ms", System.currentTimeMillis() - start);
RowIterator it = qr.getRows();
  if (PermissionUtil.isGranted(jcrSession, node.getPath(), Session.ACTION_READ)) {
    String excerpt = hasExcerptValue(row) ? row.getValue("rep:excerpt()").getString() : "";
    node.setProperty("excerpt", excerpt);
    result.add(new ContentMap(new I18nNodeWrapper(node)));

代码示例来源:origin: org.apache.sling/org.apache.sling.launchpad.test-services

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
    throws ServletException, IOException {
  response.setContentType("text/plain");
  
  String queryText = request.getParameter("q");
  if ( queryText == null || queryText.isEmpty() ) {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.getWriter().write("Missing mandatory 'q' parameter");
    return;
  }
  Session session = request.getResourceResolver().adaptTo(Session.class);
  
  try {
    Query query = session.getWorkspace().getQueryManager().createQuery("SELECT * FROM [nt:base] AS s WHERE CONTAINS(s.*, $queryText)", Query.JCR_SQL2);
    query.bindValue("queryText", session.getValueFactory().createValue(queryText));
    QueryResult result  = query.execute();
    NodeIterator iterator = result.getNodes();
    while( iterator.hasNext() ) {
      response.getWriter().println(iterator.nextNode().getPath());
    }
  } catch (RepositoryException e) {
    throw new ServletException(e);
  }
  
}

代码示例来源:origin: apache/jackrabbit

/**
 * Stores a {@link javax.jcr.query.Query#XPATH} query at:
 * <code>testRoot + "/" + nodeName1</code>.
 * @throws NotExecutableException if nt:query is not supported.
 */
public void testSave() throws RepositoryException, NotExecutableException {
  checkNtQuery();
  Query query = superuser.getWorkspace().getQueryManager().createQuery(statement, Query.XPATH);
  query.storeAsNode(testRoot + "/" + nodeName1);
  assertTrue("Node has not been stored", testRootNode.hasNode(nodeName1));
  Node queryNode = testRootNode.getNode(nodeName1);
  assertTrue("Query node is not of type nt:query", queryNode.isNodeType(ntQuery));
  Query query2 = superuser.getWorkspace().getQueryManager().getQuery(queryNode);
  assertEquals("Persisted query does not match initial query.", query.getStatement(), query2.getStatement());
}

代码示例来源:origin: Adobe-Consulting-Services/acs-aem-commons

private ResultsPage fetchResults(int limit, int offset) throws ReportException {
 prepareStatement();
 ResourceResolver resolver = request.getResourceResolver();
 Session session = resolver.adaptTo(Session.class);
 List<Object> results = new ArrayList<>();
 try {
  QueryManager queryMgr = session.getWorkspace().getQueryManager();
  Query query = queryMgr.createQuery(statement, config.getQueryLanguage());
  if (page != -1) {
   log.debug("Fetching results with limit {} and offset {}", limit, offset);
   query.setLimit(limit);
   query.setOffset(offset);
  } else {
   log.debug("Fetching all results");
  }
  QueryResult result = query.execute();
  NodeIterator nodes = result.getNodes();
  while (nodes.hasNext()) {
   results.add(resolver.getResource(nodes.nextNode().getPath()));
  }
 } catch (RepositoryException re) {
  log.error("Exception executing search results", re);
  throw new ReportException("Exception executing search results", re);
 }
 return new ResultsPage(results, config.getPageSize(), page);
}

代码示例来源:origin: apache/jackrabbit

/**
   * Verify that the jcr:path is present in the query result.
   */
  public void testJcrPath() throws RepositoryException, NotExecutableException {
    String nodeTypeName = session.getRootNode().getPrimaryNodeType().getName();
    String queryStatement = "//element(*, " + nodeTypeName + ")";

    // execute the search query
    Query query = session.getWorkspace().getQueryManager().createQuery(queryStatement, qsXPATH);
    QueryResult result = query.execute();

    assertTrue("jcr:path must be present in query result row",
        Arrays.asList(result.getColumnNames()).contains(jcrPath));
  }
}

代码示例来源:origin: apache/jackrabbit

/**
   * Tests it the statement returned by {@link Query#getStatement()} is equal
   * to the one passed in createQuery().
   */
  public void testGetStatement() throws RepositoryException {
    String statement = "/" + jcrRoot + "/foo";
    Query q = session.getWorkspace().getQueryManager().createQuery(statement, qsXPATH);
    assertEquals("Statement returned by Query.getStatement() is not equal to the initial statement.",
        statement,
        q.getStatement());
  }
}

代码示例来源:origin: apache/jackrabbit-oak

private boolean performQuery(@NotNull final TestContext ec) throws RepositoryException {
  QueryManager qm = ec.session.getWorkspace().getQueryManager();
  ValueFactory vf = ec.session.getValueFactory();
  Query q = qm.createQuery("SELECT * FROM [nt:base] WHERE [title] = $title", Query.JCR_SQL2);
  q.bindValue("title", vf.createValue(ec.title));
  LOG.trace("statement: {} - title: {}", q.getStatement(), ec.title);        
  RowIterator rows = q.execute().getRows();
  if (rows.hasNext()) {
    rows.nextRow().getPath();
    return true;
  } else {
    return false;
  }
}

代码示例来源:origin: apache/jackrabbit

public void testSetOffset() throws RepositoryException {
    testRootNode.addNode(nodeName1, testNodeType);
    testRootNode.addNode(nodeName2, testNodeType);
    testRootNode.addNode(nodeName3, testNodeType);
    superuser.save();
    for (int i = 0; i < 5; i++) {
      Query query = qf.createQuery(
          qf.selector(testNodeType, "s"),
          qf.descendantNode("s", testRoot),
          null,
          null
      );
      query.setOffset(i);
      long expected = Math.max(3 - i, 0);
      assertEquals("Wrong numer of results", expected,
          getSize(query.execute().getNodes()));
    }
  }
}

代码示例来源:origin: apache/jackrabbit-oak

protected void searchCommon(QueryManager qm, ExecutionContext context)
  throws RepositoryException {
  /** Execute standard query */
  Query stdQuery = getStandardQuery(qm, context);
  stdQuery.setLimit(LIMIT);
  QueryResult stdResult = stdQuery.execute();
  RowIterator stdIt = stdResult.getRows();
  // Iterate the standard shown first
  for (int rows = 0; stdIt.hasNext() && rows < LIMIT; rows++) {
    Node node = stdIt.nextRow().getNode();
    LOG.debug(node.getPath());
  }
}

代码示例来源:origin: ModeShape/modeshape

@Test
public void shouldLoadStoredQuery() throws Exception {
  String statement = "SELECT * FROM [nt:unstructured]";
  QueryManager queryManager = workspace.getQueryManager();
  Query query = queryManager.createQuery(statement, Query.JCR_SQL2);
  Node node = query.storeAsNode("/storedQuery");
  Query loaded = queryManager.getQuery(node);
  assertThat(loaded, is(notNullValue()));
  assertThat(loaded.getLanguage(), is(Query.JCR_SQL2));
  assertThat(loaded.getStatement(), is(statement));
  assertThat(loaded.getStoredQueryPath(), is(node.getPath()));
}

相关文章