Java Code Examples for javax.jdo.Query#execute()

The following examples show how to use javax.jdo.Query#execute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlpineQueryManager.java    From Alpine with Apache License 2.0 7 votes vote down vote up
/**
 * Determines if the specified UserPrincipal has been assigned the specified permission.
 * @param user the UserPrincipal to query
 * @param permissionName the name of the permission
 * @param includeTeams if true, will query all Team membership assigned to the user for the specified permission
 * @return true if the user has the permission assigned, false if not
 * @since 1.0.0
 */
public boolean hasPermission(final UserPrincipal user, String permissionName, boolean includeTeams) {
    Query query;
    if (user instanceof ManagedUser) {
        query = pm.newQuery(Permission.class, "name == :permissionName && managedUsers.contains(:user)");
    } else if (user instanceof LdapUser) {
        query = pm.newQuery(Permission.class, "name == :permissionName && ldapUsers.contains(:user)");
    } else {
        query = pm.newQuery(Permission.class, "name == :permissionName && oidcUsers.contains(:user)");
    }
    query.setResult("count(id)");
    final long count = (Long) query.execute(permissionName, user);
    if (count > 0) {
        return true;
    }
    if (includeTeams) {
        for (final Team team: user.getTeams()) {
            if (hasPermission(team, permissionName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 2
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private void dropSentryRoleCore(PersistenceManager pm, String roleName)
    throws SentryNoSuchObjectException {
  String lRoleName = roleName.trim().toLowerCase();
  Query query = pm.newQuery(MSentryRole.class);
  query.setFilter("this.roleName == t");
  query.declareParameters("java.lang.String t");
  query.setUnique(true);
  MSentryRole sentryRole = (MSentryRole) query.execute(lRoleName);
  if (sentryRole == null) {
    throw new SentryNoSuchObjectException("Role: " + lRoleName + " doesn't exist");
  } else {
    pm.retrieve(sentryRole);
    int numPrivs = sentryRole.getPrivileges().size();
    sentryRole.removePrivileges();
    // with SENTRY-398 generic model
    sentryRole.removeGMPrivileges();
    privCleaner.incPrivRemoval(numPrivs);
    pm.deletePersistent(sentryRole);
  }
}
 
Example 3
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public List<Long> getRecentItemIdsWithTags(int tagAttrId,Set<String> tags, int limit) {
	Query query;
	query = pm.newQuery("javax.jdo.query.SQL","select item_id,value from item_map_varchar where attr_id=? order by item_id desc limit "+limit);			

	Collection<Object[]> results = (Collection<Object[]>) query.execute(tagAttrId);
	List<Long> resf = new ArrayList<>();
	for(Object[] r : results)
	{
		Long itemId = (Long) r[0];
		String itemTags = (String) r[1];
		String[] parts = itemTags.split(",");
		for(int i=0;i<parts.length;i++)
			if (tags.contains(parts[i].toLowerCase().trim()))
			{
				resf.add(itemId);
				break;
			}
	}
	query.closeAll();
	return resf;
}
 
Example 4
Source File: JdoClusterCountStore.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Long, Double> getTopCountsByTwoDimensions(int clusterId,
		Set<Integer> dimensions, int dimension2, long timestamp, int limit,
		double decay) throws ClusterCountNoImplementationException {
	final PersistenceManager pm = getPM();
	Map<Long,Double> map = new HashMap<>();
	String dimensionsStr = StringUtils.join(dimensions, ",");
	Query query = pm.newQuery( "javax.jdo.query.SQL", "select c.item_id,exp(-(greatest(unix_timestamp()-t,0)/?))*count as decayedCount from cluster_counts c natural join item_map_enum natural join dimension d1 join item_map_enum ime2 on (c.item_id=ime2.item_id) join dimension d2 on (d2.attr_id=ime2.attr_id and ime2.value_id=d2.value_id) where id = ? and d1.dim_id in ("+dimensionsStr+") and d2.dim_id=? order by decayedCount desc limit "+limit);
	Collection<Object[]> res = (Collection<Object[]>)  query.execute(decay,clusterId,dimension2);
	for(Object[] r : res)
	{
		Long itemId = (Long) r[0];
		Double count = (Double) r[1];
		map.put(itemId, count);
	}
	return map;
}
 
Example 5
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of Vulnerability for the specified Dependency.
 * This method if designed NOT to provide paginated results.
 * @param dependency the Dependency to retrieve vulnerabilities of
 * @return a List of Vulnerability objects
 */
@SuppressWarnings("unchecked")
private List<Vulnerability> getAllVulnerabilities(Dependency dependency, boolean includeSuppressed) {
    final String filter;
    if (includeSuppressed) {
        filter = "components.contains(:component)";
    } else {
        filter = "components.contains(:component)" + generateExcludeSuppressed(
                dependency.getProject(), dependency.getComponent()
        );
    }
    final Query query = pm.newQuery(Vulnerability.class, filter);
    return (List<Vulnerability>)query.execute(dependency.getComponent());
}
 
Example 6
Source File: SqlUserAttributePeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public Map<String,String> getUserAttributesName(long userid) {
	Map<String,String> attributes = new HashMap<>();
	String sql = "SELECT a.name attr_name, CASE WHEN imi.value IS NOT NULL THEN cast(imi.value as char) WHEN imd.value IS NOT NULL THEN cast(imd.value as char) WHEN imb.value IS NOT NULL THEN cast(imb.value as char) WHEN imboo.value IS NOT NULL and imboo.value=0 THEN 'false' WHEN imboo.value IS NOT NULL and imboo.value>0 THEN 'true' WHEN imt.value IS NOT NULL THEN imt.value WHEN imdt.value IS NOT NULL THEN cast(imdt.value as char) WHEN imv.value IS NOT NULL THEN imv.value WHEN e.value_name IS NOT NULL THEN e.value_name END value_id FROM  users u INNER JOIN user_attr a ON u.user_id=? LEFT JOIN user_map_int imi ON u.user_id=imi.user_id AND a.attr_id=imi.attr_id LEFT JOIN user_map_double imd ON u.user_id=imd.user_id AND a.attr_id=imd.attr_id LEFT JOIN user_map_enum ime ON u.user_id=ime.user_id AND a.attr_id=ime.attr_id LEFT JOIN user_map_bigint imb ON u.user_id=imb.user_id AND a.attr_id=imb.attr_id LEFT JOIN user_map_boolean imboo ON u.user_id=imboo.user_id AND a.attr_id=imboo.attr_id LEFT JOIN user_map_text imt ON u.user_id=imt.user_id AND a.attr_id=imt.attr_id LEFT JOIN user_map_datetime imdt ON u.user_id=imdt.user_id AND a.attr_id=imdt.attr_id LEFT JOIN user_map_varchar imv ON u.user_id=imv.user_id AND a.attr_id=imv.attr_id LEFT JOIN user_attr_enum e ON ime.attr_id=e.attr_id AND ime.value_id=e.value_id";
	Query query = persistenceManager.newQuery( "javax.jdo.query.SQL", sql );
	Collection<Object[]> c = (Collection<Object[]>) query.execute(userid);
	for(Object[] array : c) {
		if(array!=null && array[1]!=null) {
			attributes.put((String)array[0],(String)array[1]);
		}
	}
	return attributes;
}
 
Example 7
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getItemSemanticAttributes(long itemId) {
	Query query = pm.newQuery("javax.jdo.query.SQL","SELECT CASE WHEN imi.value IS NOT NULL THEN cast(imi.value as char) WHEN imd.value IS NOT NULL THEN cast(imd.value as char) WHEN imb.value IS NOT NULL THEN cast(imb.value as char) WHEN imboo.value IS NOT NULL THEN cast(imboo.value as char) WHEN imt.value IS NOT NULL THEN imt.value WHEN imdt.value IS NOT NULL THEN cast(imdt.value as char) WHEN imv.value IS NOT NULL THEN imv.value WHEN e.value_name IS NOT NULL THEN e.value_name END value_id FROM  items i INNER JOIN item_attr a ON i.item_id=? and a.semantic = true and i.type=a.item_type LEFT JOIN item_map_int imi ON i.item_id=imi.item_id AND a.attr_id=imi.attr_id LEFT JOIN item_map_double imd ON i.item_id=imd.item_id AND a.attr_id=imd.attr_id LEFT JOIN item_map_enum ime ON i.item_id=ime.item_id AND a.attr_id=ime.attr_id LEFT JOIN item_map_bigint imb ON i.item_id=imb.item_id AND a.attr_id=imb.attr_id LEFT JOIN item_map_boolean imboo ON i.item_id=imboo.item_id AND a.attr_id=imboo.attr_id LEFT JOIN item_map_text imt ON i.item_id=imt.item_id AND a.attr_id=imt.attr_id LEFT JOIN item_map_datetime imdt ON i.item_id=imdt.item_id AND a.attr_id=imdt.attr_id LEFT JOIN item_map_varchar imv ON i.item_id=imv.item_id AND a.attr_id=imv.attr_id LEFT JOIN item_attr_enum e ON ime.attr_id =e.attr_id AND ime.value_id=e.value_id order by imv.pos");
	List<String> res = new ArrayList<>();
	Collection<String> col = (Collection<String>) query.execute(itemId);
	if(col!=null && col.size()>0) { res = new ArrayList<>(col); }
	return res;

}
 
Example 8
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Long, List<String>> getRecentItemTags(Set<Long> ids, int attrId,String table) {
	Map<Long,List<String>> res = new HashMap<>();
	if (ids != null && ids.size() > 0)
	{
		String idStr = CollectionTools.join(ids, ",");
		Query query = pm.newQuery("javax.jdo.query.SQL","select item_id,value from item_map_"+table+" where attr_id="+attrId+" and item_id in ("+idStr+")");				
		Collection<Object[]> results = (Collection<Object[]>) query.execute();

		for(Object[] r : results)
		{
			Long itemId = (Long) r[0];
			String tags = (String) r[1];
			String[] parts = tags.split(",");
			List<String> tagList = new ArrayList<>();
			for(int i=0;i<parts.length;i++)
			{
				String tag = StringUtils.trimToEmpty(parts[i]);
				if (!StringUtils.isEmpty(tag))
					tagList.add(tag);
			}
			if (tagList.size() > 0)
				res.put(itemId, tagList);
		}
		query.closeAll();
	}
	return res;
}
 
Example 9
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves ProjectMetrics in ascending order starting with the oldest since the date specified.
 * @return a List of metrics
 */
@SuppressWarnings("unchecked")
public List<ProjectMetrics> getProjectMetricsSince(Project project, Date since) {
    final Query query = pm.newQuery(ProjectMetrics.class, "project == :project && lastOccurrence >= :since");
    query.setOrdering("lastOccurrence asc");
    return (List<ProjectMetrics>)query.execute(project, since);
}
 
Example 10
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
private boolean hasAnyServerPrivileges(Set<String> roleNames, String serverName) {
  if (roleNames == null || roleNames.isEmpty()) {
    return false;
  }
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();
    Query query = pm.newQuery(MSentryPrivilege.class);
    query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role");
    List<String> rolesFiler = new LinkedList<String>();
    for (String rName : roleNames) {
      rolesFiler.add("role.roleName == \"" + rName.trim().toLowerCase() + "\"");
    }
    StringBuilder filters = new StringBuilder("roles.contains(role) "
        + "&& (" + Joiner.on(" || ").join(rolesFiler) + ") ");
    filters.append("&& serverName == \"" + serverName.trim().toLowerCase() + "\"");
    query.setFilter(filters.toString());
    query.setResult("count(this)");

    Long numPrivs = (Long) query.execute();
    rollbackTransaction = false;
    commitTransaction(pm);
    return numPrivs > 0;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example 11
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves all NotificationPublishers.
 * This method if designed NOT to provide paginated results.
 * @return list of all NotificationPublisher objects
 */
@SuppressWarnings("unchecked")
public List<NotificationPublisher> getAllNotificationPublishers() {
    final Query query = pm.newQuery(NotificationPublisher.class);
    query.getFetchPlan().addGroup(NotificationPublisher.FetchGroup.ALL.name());
    query.setOrdering("name asc");
    return (List<NotificationPublisher>)query.execute();
}
 
Example 12
Source File: SqlActionPeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Action> getRecentUserActions(long userId, int actionType,
		int limit) {
	Query query = pm.newQuery( Action.class, "userId == i && type == t" );
	query.setOrdering("actionId desc");
	query.declareParameters( "java.lang.Long i,java.lang.Integer t");
	query.setRange(0, limit);
	Collection<Action> c = (Collection<Action>) query.execute(userId,actionType);
	return c;
}
 
Example 13
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 4 votes vote down vote up
public Collection<String> getItemAttributesNameByAttrName(long itemId,String attrName) {
	String sql = "SELECT CASE WHEN imi.value IS NOT NULL THEN cast(imi.value as char) WHEN imd.value IS NOT NULL THEN cast(imd.value as char) WHEN imb.value IS NOT NULL THEN cast(imb.value as char) WHEN imboo.value IS NOT NULL THEN cast(imboo.value as char) WHEN imt.value IS NOT NULL THEN imt.value WHEN imdt.value IS NOT NULL THEN cast(imdt.value as char) WHEN imv.value IS NOT NULL THEN imv.value WHEN e.value_name IS NOT NULL THEN e.value_name END value_id FROM  items i INNER JOIN item_attr a ON i.item_id=? and a.name=? LEFT JOIN item_map_int imi ON i.item_id=imi.item_id AND a.attr_id=imi.attr_id LEFT JOIN item_map_double imd ON i.item_id=imd.item_id AND a.attr_id=imd.attr_id LEFT JOIN item_map_enum ime ON i.item_id=ime.item_id AND a.attr_id=ime.attr_id LEFT JOIN item_map_bigint imb ON i.item_id=imb.item_id AND a.attr_id=imb.attr_id LEFT JOIN item_map_boolean imboo ON i.item_id=imboo.item_id AND a.attr_id=imboo.attr_id LEFT JOIN item_map_text imt ON i.item_id=imt.item_id AND a.attr_id=imt.attr_id LEFT JOIN item_map_datetime imdt ON i.item_id=imdt.item_id AND a.attr_id=imdt.attr_id LEFT JOIN item_map_varchar imv ON i.item_id=imv.item_id AND a.attr_id=imv.attr_id LEFT JOIN item_attr_enum e ON ime.attr_id =e.attr_id AND ime.value_id=e.value_id order by imv.pos";
	Query query = pm.newQuery( "javax.jdo.query.SQL", sql );
	return (Collection<String>) query.execute(itemId,attrName);
}
 
Example 14
Source File: GuideToJDOIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenProduct_WhenQueryThenExist() {
    PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
    pumd.addClassName("com.baeldung.libraries.jdo.Product");
    pumd.setExcludeUnlistedClasses();
    pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
    pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
    pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
    pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
    pumd.addProperty("datanucleus.autoCreateSchema", "true");
    pumd.addProperty("datanucleus.schema.autoCreateTables", "true");

    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Product product = new Product("Tablet", 80.0);
        pm.makePersistent(product);
        Product product2 = new Product("Phone", 20.0);
        pm.makePersistent(product2);
        Product product3 = new Product("Laptop", 200.0);
        pm.makePersistent(product3);
        tx.commit();
    } catch (Throwable thr) {
        fail("Failed test : " + thr.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }

    pmf.close();

    PersistenceManagerFactory pmf2 = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm2 = pmf2.getPersistenceManager();
    Transaction tx2 = pm2.currentTransaction();
    try {
        tx2.begin();

        @SuppressWarnings("rawtypes")
        Query q = pm2.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price == 200");
        @SuppressWarnings("unchecked")
        List<Product> products = (List<Product>) q.execute();
        for (Product p : products) {
            assertEquals("Laptop", p.name);
        }

        tx2.commit();
    } finally {
        if (tx2.isActive()) {
            tx2.rollback();
        }

        pm2.close();
    }
}
 
Example 15
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
/**
 * This returns a Mapping of AuthZObj(db/table) -> (Role -> permission)
 */
public Map<String, HashMap<String, String>> retrieveFullPrivilegeImage() {
  Map<String, HashMap<String, String>> retVal = new HashMap<String, HashMap<String,String>>();
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();
    Query query = pm.newQuery(MSentryPrivilege.class);
    String filters = "(serverName != \"__NULL__\") "
        + "&& (dbName != \"__NULL__\") " + "&& (URI == \"__NULL__\")";
    query.setFilter(filters.toString());
    query
        .setOrdering("serverName ascending, dbName ascending, tableName ascending");
    List<MSentryPrivilege> privileges = (List<MSentryPrivilege>) query
        .execute();
    rollbackTransaction = false;
    for (MSentryPrivilege mPriv : privileges) {
      String authzObj = mPriv.getDbName();
      if (!isNULL(mPriv.getTableName())) {
        authzObj = authzObj + "." + mPriv.getTableName();
      }
      HashMap<String, String> pUpdate = retVal.get(authzObj);
      if (pUpdate == null) {
        pUpdate = new HashMap<String, String>();
        retVal.put(authzObj, pUpdate);
      }
      for (MSentryRole mRole : mPriv.getRoles()) {
        String existingPriv = pUpdate.get(mRole.getRoleName());
        if (existingPriv == null) {
          pUpdate.put(mRole.getRoleName(), mPriv.getAction().toUpperCase());
        } else {
          pUpdate.put(mRole.getRoleName(), existingPriv + ","
              + mPriv.getAction().toUpperCase());
        }
      }
    }
    commitTransaction(pm);
    return retVal;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example 16
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
List<MSentryPrivilege> getMSentryPrivileges(Set<String> roleNames, TSentryAuthorizable authHierarchy) {
  if (roleNames == null || roleNames.isEmpty()) {
    return new ArrayList<MSentryPrivilege>();
  }
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();
    Query query = pm.newQuery(MSentryPrivilege.class);
    query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role");
    List<String> rolesFiler = new LinkedList<String>();
    for (String rName : roleNames) {
      rolesFiler.add("role.roleName == \"" + rName.trim().toLowerCase() + "\"");
    }
    StringBuilder filters = new StringBuilder("roles.contains(role) "
        + "&& (" + Joiner.on(" || ").join(rolesFiler) + ") ");
    if (authHierarchy != null && authHierarchy.getServer() != null) {
      filters.append("&& serverName == \"" + authHierarchy.getServer().toLowerCase() + "\"");
      if (authHierarchy.getDb() != null) {
        filters.append(" && ((dbName == \"" + authHierarchy.getDb().toLowerCase() + "\") || (dbName == \"__NULL__\")) && (URI == \"__NULL__\")");
        if (authHierarchy.getTable() != null
            && !AccessConstants.ALL.equalsIgnoreCase(authHierarchy.getTable())) {
          if (!AccessConstants.SOME.equalsIgnoreCase(authHierarchy.getTable())) {
            filters.append(" && ((tableName == \"" + authHierarchy.getTable().toLowerCase() + "\") || (tableName == \"__NULL__\")) && (URI == \"__NULL__\")");
          }
          if (authHierarchy.getColumn() != null
              && !AccessConstants.ALL.equalsIgnoreCase(authHierarchy.getColumn())
              && !AccessConstants.SOME.equalsIgnoreCase(authHierarchy.getColumn())) {
            filters.append(" && ((columnName == \"" + authHierarchy.getColumn().toLowerCase() + "\") || (columnName == \"__NULL__\")) && (URI == \"__NULL__\")");
          }
        }
      }
      if (authHierarchy.getUri() != null) {
        filters.append(" && ((URI != \"__NULL__\") && (\"" + authHierarchy.getUri() + "\".startsWith(URI)) || (URI == \"__NULL__\")) && (dbName == \"__NULL__\")");
      }
    }
    query.setFilter(filters.toString());
    List<MSentryPrivilege> privileges = (List<MSentryPrivilege>) query.execute();
    rollbackTransaction = false;
    commitTransaction(pm);
    return privileges;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example 17
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<ItemType> getItemTypes() {
	Query query = pm.newQuery( ItemType.class, "" );
	query.setOrdering("typeId asc");
	return (Collection<ItemType>) query.execute();
}
 
Example 18
Source File: QueryManager.java    From dependency-track with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a List of Dependencies for the specified Project and Component.
 *
 * There should NEVER be duplicate dependencies. But this method is intended
 * to check for them and return the list. This is a private method and should
 * never be accessed outside the QueryManager.
 *
 * @param project the Project the component is part of
 * @param component the Component
 * @return a List of Dependency objects, or null if not found
 */
@SuppressWarnings("unchecked")
private List<Dependency> getDependencies(Project project, Component component) {
    final Query query = pm.newQuery(Dependency.class, "project == :project && component == :component");
    query.getFetchPlan().addGroup(Dependency.FetchGroup.ALL.name());
    return (List<Dependency>) query.execute(project, component);
}
 
Example 19
Source File: AbstractAlpineQueryManager.java    From Alpine with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the number of items that would have resulted from returning all object.
 * This method is performant in that the objects are not actually retrieved, only
 * the count.
 * @param cls the persistence-capable class to query
 * @return the number of items
 * @param <T> candidate type for the query
 * @since 1.0.0
 */
public <T> long getCount(final Class<T> cls) {
    final Query query = pm.newQuery(cls);
    //query.addExtension("datanucleus.query.resultSizeMethod", "count");
    query.setResult("count(id)");
    return (Long) query.execute();
}
 
Example 20
Source File: AbstractAlpineQueryManager.java    From Alpine with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the number of items that would have resulted from returning all object.
 * This method is performant in that the objects are not actually retrieved, only
 * the count.
 * @param query the query to return a count from
 * @param p1 the value of the first parameter declared.
 * @param p2 the value of the second parameter declared.
 * @return the number of items
 * @since 1.0.0
 */
public long getCount(final Query query, final Object p1, final Object p2) {
    final String ordering = ((JDOQuery) query).getInternalQuery().getOrdering();
    query.setResult("count(id)");
    query.setOrdering(null);
    final long count = (Long) query.execute(p1, p2);
    query.setOrdering(ordering);
    return count;
}