javax.jdo.Query Java Examples

The following examples show how to use javax.jdo.Query. 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: ServerUtils.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Counts the entities returned by the specified query.
 * @param query  query whose results to count
 * @param params optional parameters of the query
 * @return the number of entities returned by the query
 * 
 * @deprecated Use of this method does not count toward <b>"Datastore Small Ops"</b> but toward <b>"Datastore Read Ops"</b>. Use {@link #countEntities(DatastoreService, com.google.appengine.api.datastore.Query)} instead.
 */
public static int countEntitiesJdo( final Query query, final Object... params ) {
	int count = 0;
	
	query.setRange( 0, 1000 );
	
	while ( true ) {
		final List< ? > resultList = (List< ? >) query.executeWithArray( params );
		count += resultList.size();
		
		if ( resultList.size() < 1000 )
			return count;
		
		setQueryCursor( query, resultList );
	}
}
 
Example #3
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public long getMinItemId(Date after, Integer dimension,ConsumerBean cb) {
	String typeFilter = "";
	if(dimension != null && dimension != Constants.DEFAULT_DIMENSION) {
		DimensionBean d = ItemService.getDimension(cb, dimension);
		Integer type = d.getItemType();
		if(type!=null) { typeFilter = " and type ="+ type; }
	}
	Query query = pm.newQuery( Item.class, "lastOp >= d" + typeFilter );
	query.declareParameters("java.util.Date d");
	query.setRange(0, 1);
	query.setOrdering("lastOp ASC,itemId ASC");
	Collection<Item> c = (Collection<Item>) query.execute(after);
	if (c.size() >= 1)
		return c.iterator().next().getItemId();
	else
		return 0L;
}
 
Example #4
Source File: AbstractAlpineQueryManager.java    From Alpine with Apache License 2.0 6 votes vote down vote up
/**
 * Given a query, this method will decorate that query with pagination, ordering,
 * and sorting direction. Specific checks are performed to ensure the execution
 * of the query is capable of being paged and that ordering can be securely performed.
 * @param query the JDO Query object to execute
 * @return a Collection of objects
 * @since 1.0.0
 */
public Query decorate(final Query query) {
    // Clear the result to fetch if previously specified (i.e. by getting count)
    query.setResult(null);
    if (pagination != null && pagination.isPaginated()) {
        final long begin = pagination.getOffset();
        final long end = begin + pagination.getLimit();
        query.setRange(begin, end);
    }
    if (orderBy != null && RegexSequence.Pattern.STRING_IDENTIFIER.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) {
        // Check to see if the specified orderBy field is defined in the class being queried.
        boolean found = false;
        final org.datanucleus.store.query.Query iq = ((JDOQuery) query).getInternalQuery();
        final String candidateField = orderBy.contains(".") ? orderBy.substring(0, orderBy.indexOf('.')) : orderBy;
        for (final Field field: iq.getCandidateClass().getDeclaredFields()) {
            if (candidateField.equals(field.getName())) {
                found = true;
                break;
            }
        }
        if (found) {
            query.setOrdering(orderBy + " " + orderDirection.name().toLowerCase());
        }
    }
    return query;
}
 
Example #5
Source File: ServerUtils.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Counts the entities returned by the specified query.
 * @param ds    reference to the datastore service
 * @param query query whose results to count
 * @return the number of entities returned by the query
 */
public static int countEntities( final DatastoreService ds, final com.google.appengine.api.datastore.Query q ) {
	q.setKeysOnly();
	
	final int          batchSize    = 1000;
	final FetchOptions fetchOptions = FetchOptions.Builder.withLimit( batchSize );
	
	Cursor cursor = null;
	int    count  = 0;
	while ( true ) {
		if ( cursor != null )
			fetchOptions.startCursor( cursor );
		
		final QueryResultList< Entity > resultList = ds.prepare( q ).asQueryResultList( fetchOptions );
		
		count += resultList.size();
		
		if ( resultList.size() < batchSize )
			return count;
		
		cursor = resultList.getCursor();
	}
}
 
Example #6
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void DeleteProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Query query = pm.newQuery(Product.class, "name == \"Android Phone\"");
        Collection result = (Collection) query.execute();
        Product product = (Product) result.iterator().next();
        pm.deletePersistent(product);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #7
Source File: SqlBaselineRecommenderUtils.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Long, Double> reorderByMostPopular(Set<Long> itemIds) {
	String idStr = StringUtils.join(itemIds, ",");
	String sql = "select ip.item_id,opsum from items_popular where item_id in ("+idStr+") order by opsum desc";
	Query query = getPM().newQuery( "javax.jdo.query.SQL", sql);
	Collection<Object[]> results = (Collection<Object[]>) query.execute();
	Map<Long,Double> map = new HashMap<>();
	Double topScore = null;
	for(Object[] res : results)
	{
		if (topScore == null)
			topScore = (Double) res[1];
		Long item = (Long) res[0];
		Double score = (Double) res[1];
		map.put(item, score/topScore);
	}
	query.closeAll();
	return map;
}
 
Example #8
Source File: JdoClusterCountStore.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Long, Double> getTopCountsByTagAndDimension(String tag,
		int tagAttrId, Set<Integer> dimensions, 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 cluster_counts.item_id,sum(exp(-(greatest(unix_timestamp()-t,0)/?))*count) as decayedSumCount from cluster_counts natural join item_map_enum natural join dimension join item_map_varchar on (cluster_counts.item_id=item_map_varchar.item_id and item_map_varchar.attr_id=?) where dim_id in ("+dimensionsStr+") and value regexp \"(^|,)[ ]*"+tag+"[ ]*(,|$)\" group by item_id order by decayedSumCount desc limit "+limit );
	Collection<Object[]> res = (Collection<Object[]>)  query.execute(decay,tagAttrId);
	for(Object[] r : res)
	{
		Long itemId = (Long) r[0];
		Double count = (Double) r[1];
		map.put(itemId, count);
	}
	logger.info("getTopCountsByTagAndTwoDimension "+tag+" tagATtrId "+tagAttrId+" dimension "+dimensionsStr+" decay "+decay+ " limit "+limit+ " results "+map.size());
	return map;
}
 
Example #9
Source File: JdoClusterCountStore.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Long, Double> getTopCountsByTagAndTwoDimensions(String tag,
		int tagAttrId, Set<Integer> dimensions, int dimension2, 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,sum(exp(-(greatest(unix_timestamp()-t,0)/?))*count) as decayedCount from cluster_counts c natural join item_map_enum ime1 join dimension d1 on (d1.attr_id=ime1.attr_id and ime1.value_id=d1.value_id) 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) join item_map_varchar on (c.item_id=item_map_varchar.item_id and item_map_varchar.attr_id=?) where d1.dim_id in ("+dimensionsStr+") and d2.dim_id = ? and value regexp \"(^|,)[ ]*"+tag+"[ ]*(,|$)\" group by item_id order by decayedcount desc limit "+limit );
	ArrayList<Object> args = new ArrayList<>();
	args.add(decay);
	args.add(tagAttrId);
	args.add(dimension2);
	Collection<Object[]> res = (Collection<Object[]>)  query.executeWithArray(args.toArray());
	for(Object[] r : res)
	{
		Long itemId = (Long) r[0];
		Double count = (Double) r[1];
		map.put(itemId, count);
	}
	logger.info("getTopCountsByTagAndTwoDimensions "+tag+" tagATtrId "+tagAttrId+" dimension "+dimensionsStr+" dimension2 "+dimension2+" decay "+decay+ " limit "+limit+ " results "+map.size());
	return map;
}
 
Example #10
Source File: SqlUserPeer.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
private boolean validateDemographic(final String name,final String value,ConsumerBean c) {
	if(UserService.getDemographic(c,name, value) == null) {
		//create the demographic
		final String addAttrEnum = "insert into user_attr_enum (attr_id,value_id,value_name,amount) select a.attr_id,max(e.value_id)+1,?,0 from user_attr a inner join user_attr_enum e on a.name = ? and a.attr_id=e.attr_id";
		final String addDemo = "insert into demographic (attr_id,value_id) select a.attr_id,e.value_id from user_attr a inner join user_attr_enum e on a.name = ? and e.value_name=? and a.attr_id=e.attr_id";
		try {
               TransactionPeer.runTransaction(new Transaction(pm) {
                   public void process() {
                       Query query = pm.newQuery("javax.jdo.query.SQL", addAttrEnum);
                       query.execute(value,name);
                       query.closeAll();
                       query = pm.newQuery("javax.jdo.query.SQL", addDemo);
                       query.execute(name,value);
                       query.closeAll();
                   }
               });
           } catch (DatabaseException e) {
               logger.error("Not able to create demographic for value: " + value + " for attribute " + name, e);
               return false;
           }
	}
	return true;
}
 
Example #11
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private List<MSentryPrivilege> getMSentryPrivileges(TSentryPrivilege tPriv, PersistenceManager pm) {
  Query query = pm.newQuery(MSentryPrivilege.class);
  StringBuilder filters = new StringBuilder("this.serverName == \""
        + toNULLCol(safeTrimLower(tPriv.getServerName())) + "\" ");
  if (!isNULL(tPriv.getDbName())) {
    filters.append("&& this.dbName == \"" + toNULLCol(safeTrimLower(tPriv.getDbName())) + "\" ");
    if (!isNULL(tPriv.getTableName())) {
      filters.append("&& this.tableName == \"" + toNULLCol(safeTrimLower(tPriv.getTableName())) + "\" ");
      if (!isNULL(tPriv.getColumnName())) {
        filters.append("&& this.columnName == \"" + toNULLCol(safeTrimLower(tPriv.getColumnName())) + "\" ");
      }
    }
  }
  // if db is null, uri is not null
  else if (!isNULL(tPriv.getURI())){
    filters.append("&& this.URI == \"" + toNULLCol(safeTrim(tPriv.getURI())) + "\" ");
  }
  filters.append("&& this.action == \"" + toNULLCol(safeTrimLower(tPriv.getAction())) + "\"");

  query.setFilter(filters.toString());
  List<MSentryPrivilege> privileges = (List<MSentryPrivilege>) query.execute();
  return privileges;
}
 
Example #12
Source File: SqlBaselineRecommenderUtils.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Long, Double> getPopularItems(int dimension, int numRecommendations) {
	
	String sql = "select ip.item_id,opsum from items_popular ip join item_map_enum ime on (ip.item_id=ime.item_id) join dimension d on (ime.attr_id=d.attr_id and ime.value_id=d.value_id) where dim_id=? order by opsum desc limit "+numRecommendations;
	Query query = getPM().newQuery( "javax.jdo.query.SQL", sql);
	ArrayList<Object> args = new ArrayList<>();
	args.add(dimension);
	Collection<Object[]> results = (Collection<Object[]>) query.executeWithArray(args.toArray());
	Map<Long,Double> map = new HashMap<>();
	Double topScore = null;
	for(Object[] res : results)
	{
		if (topScore == null)
			topScore = (Double) res[1];
		Long item = (Long) res[0];
		Double score = (Double) res[1];
		map.put(item, score/topScore);
	}
	query.closeAll();
	return map;
}
 
Example #13
Source File: JdoClusterCountStore.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Long, Double> getTopCountsByDimension(Set<Integer> dimensions, 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 item_id,sum(exp(-(greatest(unix_timestamp()-t,0)/?))*count) as decayedSumCount from cluster_counts natural join item_map_enum natural join dimension where dim_id in ("+dimensionsStr+") group by item_id order by decayedSumCount desc limit "+limit );
	Collection<Object[]> res = (Collection<Object[]>)  query.execute(decay);
	for(Object[] r : res)
	{
		Long itemId = (Long) r[0];
		Double count = (Double) r[1];
		map.put(itemId, count);
	}
	return map;
}
 
Example #14
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of all VulnerableSoftware objects that match the specified vendor/product/version.
 * @return a List of matching VulnerableSoftware objects
 */
@SuppressWarnings("unchecked")
public List<VulnerableSoftware> getAllVulnerableSoftware(final String part, final String vendor, final String product, final String version) {
    final Query query = pm.newQuery(VulnerableSoftware.class);
    query.setFilter("part == :part && vendor == :vendor && product == :product && version == :version");
    return (List<VulnerableSoftware>)query.executeWithArray(part, vendor, product, version);
}
 
Example #15
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of repositories by it's type in the order in which the repository should be used in resolution.
 * This method if designed NOT to provide paginated results.
 * @param type the type of repository (required)
 * @return a List of Repository objects
 */
@SuppressWarnings("unchecked")
public List<Repository> getAllRepositoriesOrdered(RepositoryType type) {
    final Query query = pm.newQuery(Repository.class, "type == :type");
    query.setOrdering("resolutionOrder asc");
    return (List<Repository>)query.execute(type);
}
 
Example #16
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of all Dependency for the specified Project.
 * This method if designed NOT to provide paginated results.
 * @param project the Project to retrieve dependencies of
 * @return a List of Dependency objects
 */
@SuppressWarnings("unchecked")
public List<Dependency> getAllDependencies(Project project) {
    final Query query = pm.newQuery(Dependency.class, "project == :project");
    query.getFetchPlan().setMaxFetchDepth(2);
    query.getFetchPlan().addGroup(Dependency.FetchGroup.COMPONENT_ONLY.name());
    query.setOrdering("component.name asc");
    return (List<Dependency>)query.execute(project);
}
 
Example #17
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Item> getItems(int skip,int limit) {
	Query query = pm.newQuery( Item.class, "" );
	query.setRange(skip, limit);
	Collection<Item> c = (Collection<Item>) query.execute();
	return c;
}
 
Example #18
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves ComponentMetrics in ascending order starting with the oldest since the date specified.
 * @return a List of metrics
 */
@SuppressWarnings("unchecked")
public List<ComponentMetrics> getComponentMetricsSince(Component component, Date since) {
    final Query query = pm.newQuery(ComponentMetrics.class, "component == :component && lastOccurrence >= :since");
    query.setOrdering("lastOccurrence asc");
    return (List<ComponentMetrics>)query.execute(component, since);
}
 
Example #19
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public Integer getDimensionForAttrName(long itemId, String name) {
	Query query = pm.newQuery( "javax.jdo.query.SQL", "select dim_id from dimension natural join item_map_enum join item_attr on (item_attr.attr_id=item_map_enum.attr_id) where item_attr.name=? and item_map_enum.item_id=?");
	query.setResultClass(Integer.class);
	query.setUnique(true);
	return (Integer) query.execute(name,itemId);
}
 
Example #20
Source File: DelegateSentryStore.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
/**
 * The role is global in the generic model, such as the role may be has more than one component
 * privileges, so delete role will remove all privileges related to it.
 */
@Override
public CommitContext dropRole(String component, String role, String requestor)
    throws SentryNoSuchObjectException {
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  role = toTrimmedLower(role);
  try {
    pm = openTransaction();
    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(role);
    if (sentryRole == null) {
      throw new SentryNoSuchObjectException("Role: " + role + " doesn't exist");
    } else {
      pm.retrieve(sentryRole);
      sentryRole.removeGMPrivileges();
      sentryRole.removePrivileges();
      pm.deletePersistent(sentryRole);
    }
    CommitContext commit = commitUpdateTransaction(pm);
    rollbackTransaction = false;
    return commit;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example #21
Source File: GuideToJDO.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void QueryJDOQL() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        // Declarative JDOQL :
        LOGGER.log(Level.INFO, "Declarative JDOQL --------------------------------------------------------------");
        Query qDJDOQL = pm.newQuery(Product.class);
        qDJDOQL.setFilter("name == 'Tablet' && price == price_value");
        qDJDOQL.declareParameters("double price_value");
        List<Product> resultsqDJDOQL = qDJDOQL.setParameters(80.0).executeList();

        Iterator<Product> iterDJDOQL = resultsqDJDOQL.iterator();
        while (iterDJDOQL.hasNext()) {
            Product p = iterDJDOQL.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");

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

        pm.close();
    }
}
 
Example #22
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 #23
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a concise List of all Licenses.
 * This method if designed NOT to provide paginated results.
 * @return a List of License objects
 */
@SuppressWarnings("unchecked")
public List<License> getAllLicensesConcise() {
    final Query query = pm.newQuery(License.class);
    query.getFetchPlan().addGroup(License.FetchGroup.CONCISE.name());
    if (orderBy == null) {
        query.setOrdering("name asc");
    }
    return (List<License>)query.execute();
}
 
Example #24
Source File: PersistenceManagerFactoryUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Apply the current transaction timeout, if any, to the given JDO Query object.
 * @param query the JDO Query object
 * @param pmf JDO PersistenceManagerFactory that the Query was created for
 * @throws JDOException if thrown by JDO methods
 */
public static void applyTransactionTimeout(Query query, PersistenceManagerFactory pmf) throws JDOException {
	Assert.notNull(query, "No Query object specified");
	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null && pmHolder.hasTimeout() &&
			pmf.supportedOptions().contains("javax.jdo.option.DatastoreTimeout")) {
		int timeout = (int) pmHolder.getTimeToLiveInMillis();
		query.setDatastoreReadTimeoutMillis(timeout);
		query.setDatastoreWriteTimeoutMillis(timeout);
	}
}
 
Example #25
Source File: JdoUserClusterStore.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public long getCurrentTimestamp() {
	final PersistenceManager pm = getPM();
	Query query = pm.newQuery( "javax.jdo.query.SQL","select lastupdate from cluster_update");
	query.setResultClass(Long.class);
	query.setUnique(true);
	return (Long) query.execute();
}
 
Example #26
Source File: QueryManager.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of all CPE objects that match the specified vendor/product/version.
 * @return a List of matching CPE objects
 */
@SuppressWarnings("unchecked")
public List<Cpe> getCpes(final String part, final String vendor, final String product, final String version) {
    final Query query = pm.newQuery(Cpe.class);
    query.setFilter("part == :part && vendor == :vendor && product == :product && version == :version");
    return (List<Cpe>)query.executeWithArray(part, vendor, product, version);
}
 
Example #27
Source File: StatusMessageSummaryCache.java    From estatio with Apache License 2.0 5 votes vote down vote up
private List<InvoiceIdAndStatusMessageSummary> find(final Long invoiceId) {
    final PersistenceManager jdoPersistenceManager = isisJdoSupport.getJdoPersistenceManager();

    final String sql = readSql();
    final Query query = jdoPersistenceManager.newQuery("javax.jdo.query.SQL", sql);
    query.setResultClass(InvoiceIdAndStatusMessageSummary.class);

    return (List<InvoiceIdAndStatusMessageSummary>) query.executeWithMap(ImmutableMap.of("invoiceId", invoiceId));
}
 
Example #28
Source File: SqlItemPeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public int getDimensionItemType(int dimension) {
	int res = Constants.DEFAULT_ITEM_TYPE;
	Query query = pm.newQuery( "javax.jdo.query.SQL", "select item_type from dimension where dim_id=?");
	Collection<Integer> c = (Collection<Integer>) query.execute(dimension);
	if(!c.isEmpty()) {
		res = (Integer)c.iterator().next();
	}
	return res;
}
 
Example #29
Source File: AlpineQueryManager.java    From Alpine with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the most recent log entry for the specified Subscriber.
 * If no log entries are found, this method will return null.
 * @param clazz The LoggableSubscriber class to query on
 * @return a EventServiceLog
 * @since 1.0.0
 */
@SuppressWarnings("unchecked")
public EventServiceLog getLatestEventServiceLog(final Class<LoggableSubscriber> clazz) {
    final Query query = pm.newQuery(EventServiceLog.class, "eventClass == :clazz");
    query.setOrdering("completed desc");
    final List<EventServiceLog> result = (List<EventServiceLog>) query.execute(clazz);
    return Collections.isEmpty(result) ? null : result.get(0);
}
 
Example #30
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
public Set<String> getRoleNamesForGroups(Set<String> groups) {
  Set<String> result = new HashSet<String>();
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();
    Query query = pm.newQuery(MSentryGroup.class);
    query.setFilter("this.groupName == t");
    query.declareParameters("java.lang.String t");
    query.setUnique(true);
    for (String group : groups) {
      MSentryGroup sentryGroup = (MSentryGroup) query.execute(group.trim());
      if (sentryGroup != null) {
        for (MSentryRole role : sentryGroup.getRoles()) {
          result.add(role.getRoleName());
        }
      }
    }
    rollbackTransaction = false;
    commitTransaction(pm);
    return result;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}