Java Code Examples for javax.jdo.PersistenceManager#newQuery()

The following examples show how to use javax.jdo.PersistenceManager#newQuery() . 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: 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 2
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void ListProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price > 10");
        List<Product> products = (List<Product>) q.execute();
        Iterator<Product> iter = products.iterator();
        while (iter.hasNext()) {
            Product p = iter.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 3
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 4
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private <T> Long getCount(Class<T> tClass) {
  PersistenceManager pm = null;
  Long size = Long.valueOf(-1);
  try {
    pm = openTransaction();
    Query query = pm.newQuery();
    query.setClass(tClass);
    query.setResult("count(this)");
    size = (Long)query.execute();

  } finally {
    if (pm != null) {
      commitTransaction(pm);
    }
  }
  return size;
}
 
Example 5
Source File: ConsumerPeer.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
public Consumer findConsumer(String consumerKey) throws APIException {
	try {
		PersistenceManager pm =  jdoFactory.getPersistenceManager(Constants.API_DB);
		Query query = pm.newQuery(Consumer.class, "consumerKey == c");
		query.declareParameters("java.lang.String c");
		Collection<Consumer> c = (Collection<Consumer>) query.execute(consumerKey);
		if(c!=null && c.size()>0) {
			return c.iterator().next();
		}
		else return null;
	}
	catch(Exception e) {
		ApiLoggerServer.log(new ConsumerPeer(), e);
		throw new APIException(APIException.INTERNAL_DB_ERROR);
	}
}
 
Example 6
Source File: IncomingInvoiceRepository.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Programmatic
public boolean findCreditNotesInStateOf(
        final BankAccount creditorBankAccount,
        final List<IncomingInvoiceApprovalState> upstreamStates) {
    final PersistenceManager jdoPersistenceManager = isisJdoSupport.getJdoPersistenceManager();
    final String sql = constructSqlForCreditNotesInStateOf(upstreamStates);
    final Query query = jdoPersistenceManager.newQuery("javax.jdo.query.SQL", sql);
    try {
        query.setResultClass(Integer.class);
        final DatastoreIdImpl datastoreId = (DatastoreIdImpl) JDOHelper.getObjectId(creditorBankAccount);
        final long idKeyAsObject = (long) datastoreId.getKeyAsObject();
        final ForwardQueryResult result = (ForwardQueryResult) query.executeWithMap(ImmutableMap.of("bankAccountId", idKeyAsObject));
        return !result.isEmpty();
    } finally {
        if (query!=null) query.closeAll();
    }
}
 
Example 7
Source File: IncomingInvoiceItemRepository.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Programmatic
public List<LocalDate> findDistinctReportDates() {
    final PersistenceManager pm = isisJdoSupport.getJdoPersistenceManager();
    final Query query = pm.newQuery(IncomingInvoiceItem.class);
    query.setResultClass(LocalDate.class);
    query.setResult("distinct reportedDate");
    query.setOrdering("reportedDate descending");
    query.setFilter("reportedDate != null"); // EST-1838: Null value was set to LocalDate#now by DN
    return executeListAndClose(query);
}
 
Example 8
Source File: AndroidRpcImpl.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public AppInstall ensureInstall(AndroidDevice androidDevice) {
	PersistenceManager pm = PMF.get().getPersistenceManager();
	try {
		AppInstall appInstall;
		Query query = pm.newQuery(AppInstall.class);
		query.setFilter("deviceId == :param");
		List<AppInstall> result = (List<AppInstall>) query.execute(androidDevice.getId());
		if (result.isEmpty()) {
			logger.debug("New install : " + androidDevice);
			String email = androidDevice.getEmails().isEmpty() ? null : androidDevice.getEmails().iterator().next();
			sendEmail(STR.supportEmail, "[FlickrUploader] New install - " + androidDevice.getCountryCode() + " - " + androidDevice.getLanguage() + " - " + androidDevice.getAppVersion() + " - "
					+ email, androidDevice.getEmails() + " - " + androidDevice.getAndroidVersion() + " - " + androidDevice.getAppVersion(), STR.supportEmail);
			appInstall = new AppInstall(androidDevice.getId(), androidDevice, androidDevice.getEmails());
			pm.makePersistent(appInstall);

		} else {
			logger.debug("Updating install : " + androidDevice);
			appInstall = result.get(0);
			appInstall.setAndroidDevice(androidDevice);
		}
		return pm.detachCopy(appInstall);
	} catch (Exception e) {
		logger.error(ToolString.stack2string(e));
	} finally {
		pm.close();
	}
	return null;
}
 
Example 9
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 10
Source File: JdoClusterCountStore.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
/**
 * timestamp and time is ignore for db counts - the db value for these is used. They are assumed to be up-to-date with clusters.
 */
@Override
public Map<Long, Double> getTopCounts(int clusterId, long timestamp, int limit, double decay) {
	final PersistenceManager pm = getPM();
	Map<Long,Double> map = new HashMap<>();
	Query query = pm.newQuery( "javax.jdo.query.SQL", "select item_id,exp(-(greatest(unix_timestamp()-t,0)/?))*count as decayedCount from cluster_counts where id=? order by decayedCount desc limit "+limit );
	Collection<Object[]> res = (Collection<Object[]>)  query.execute(decay,clusterId);
	for(Object[] r : res)
	{
		Long itemId = (Long) r[0];
		Double count = (Double) r[1];
		map.put(itemId, count);
	}
	return map;
}
 
Example 11
Source File: DelegateSentryStore.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getGroupsByRoles(String component, Set<String> roles)
    throws SentryUserException {
  roles = toTrimmedLower(roles);
  Set<String> groupNames = Sets.newHashSet();
  if (roles.size() == 0) {
    return groupNames;
  }

  PersistenceManager pm = null;
  try{
    pm = openTransaction();
    //get groups by roles
    Query query = pm.newQuery(MSentryGroup.class);
    StringBuilder filters = new StringBuilder();
    query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role");
    List<String> rolesFiler = new LinkedList<String>();
    for (String role : roles) {
      rolesFiler.add("role.roleName == \"" + role + "\" ");
    }
    filters.append("roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")");
    query.setFilter(filters.toString());

    List<MSentryGroup> groups = (List<MSentryGroup>)query.execute();
    if (groups == null) {
      return groupNames;
    }
    for (MSentryGroup group : groups) {
      groupNames.add(group.getGroupName());
    }
    return groupNames;
  } finally {
    if (pm != null) {
      commitTransaction(pm);
    }
  }
}
 
Example 12
Source File: JdoUserClusterStore.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<UserCluster> getClusters(long userId) {
	final PersistenceManager pm = getPM();
	Query query = pm.newQuery( "javax.jdo.query.SQL","select user_id,user_clusters.cluster_id,weight,lastupdate,group_id from user_clusters, cluster_update, cluster_group where user_id=? and user_clusters.cluster_id=cluster_group.cluster_id");
	query.setResultClass(UserCluster.class);
	return (List<UserCluster>) query.execute(userId);
}
 
Example 13
Source File: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 5 votes vote down vote up
private Counter getThisCounter(PersistenceManager pm) {
  Counter current = null;
  final Query thisCounterQuery = pm.newQuery(Counter.class,
      "counterName == nameParam");
  thisCounterQuery.declareParameters("String nameParam");
  final List<Counter> counter = (List<Counter>) thisCounterQuery.execute(
      counterName);
  if (counter != null && !counter.isEmpty()) {
    current = counter.get(0);
  }
  return current;
}
 
Example 14
Source File: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 5 votes vote down vote up
public void increment(int count) {
  if (cache != null) {
    final Integer cachedCount = (Integer) cache.get("count" + counterName);
    if (cachedCount != null) {
      cache.put("count" + counterName,
          Integer.valueOf(count + cachedCount.intValue()));
    }
  }

  int shardCount = 0;
  PersistenceManager pm = PMF.get().getPersistenceManager();
  try {
    final DatastoreCounter current = getThisCounter(pm);
    shardCount = current.getShardCount();
  } finally {
    pm.close();
  }

  final Random generator = new Random();
  final int shardNum = generator.nextInt(shardCount);

  pm = PMF.get().getPersistenceManager();
  try {
    final Query randomShardQuery = pm.newQuery(DatastoreCounterShard.class);
    randomShardQuery.setFilter(
        "counterName == nameParam && shardNumber == numParam");
    randomShardQuery.declareParameters("String nameParam, int numParam");
    final List<DatastoreCounterShard> shards =
        (List<DatastoreCounterShard>) randomShardQuery.execute(
            counterName, shardNum);
    if (shards != null && !shards.isEmpty()) {
      final DatastoreCounterShard shard = shards.get(0);
      shard.increment(count);
      pm.makePersistent(shard);
    }
  } finally {
    pm.close();
  }
}
 
Example 15
Source File: PrivilegeOperatePersistence.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
private MSentryGMPrivilege getPrivilege(MSentryGMPrivilege privilege, PersistenceManager pm) {
  Query query = pm.newQuery(MSentryGMPrivilege.class);
  query.setFilter(MSentryGMPrivilege.toQuery(privilege));
  query.setUnique(true);
  return (MSentryGMPrivilege)query.execute();
}
 
Example 16
Source File: JdoSql.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testJdoQueriesAdditionalMethodSig(String input) {
    PersistenceManager pm = getPM();

    pm.newQuery(UserEntity.class,new ArrayList(),"id == "+ input); //Injection?

    pm.newQuery(UserEntity.class,new ArrayList(),"id == 1");

    pm.newQuery(UserEntity.class,"id == "+ input); //Injection?

    pm.newQuery(UserEntity.class,"id == 1");

    pm.newQuery((Extent) null,"id == "+input); //Injection?

    pm.newQuery((Extent) null,"id == 1");

}
 
Example 17
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 18
Source File: JdoSqlFilter.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testJdoSafeGrouping() {
    PersistenceManager pm = getPM();
    Query q = pm.newQuery(UserEntity.class);
    q.setGrouping(FIELD_TEST);
}
 
Example 19
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
private Set<MSentryPrivilege> getChildPrivileges(PersistenceManager pm, Set<String> roleNames,
    MSentryPrivilege parent) throws SentryInvalidInputException {
  // Column and URI do not have children
  if (!isNULL(parent.getColumnName()) || !isNULL(parent.getURI())) {
    return new HashSet<MSentryPrivilege>();
  }

  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 == \"" + parent.getServerName() + "\"");
  if (!isNULL(parent.getDbName())) {
    filters.append(" && dbName == \"" + parent.getDbName() + "\"");
    if (!isNULL(parent.getTableName())) {
      filters.append(" && tableName == \"" + parent.getTableName() + "\"");
      filters.append(" && columnName != \"__NULL__\"");
    } else {
      filters.append(" && tableName != \"__NULL__\"");
    }
  } else {
    filters.append(" && (dbName != \"__NULL__\" || URI != \"__NULL__\")");
  }

  query.setFilter(filters.toString());
  query.setResult("privilegeScope, serverName, dbName, tableName, columnName," +
      " URI, action, grantOption");
  Set<MSentryPrivilege> privileges = new HashSet<MSentryPrivilege>();
  for (Object[] privObj : (List<Object[]>) query.execute()) {
    MSentryPrivilege priv = new MSentryPrivilege();
    priv.setPrivilegeScope((String) privObj[0]);
    priv.setServerName((String) privObj[1]);
    priv.setDbName((String) privObj[2]);
    priv.setTableName((String) privObj[3]);
    priv.setColumnName((String) privObj[4]);
    priv.setURI((String) privObj[5]);
    priv.setAction((String) privObj[6]);
    priv.setGrantOption((Boolean) privObj[7]);
    privileges.add(priv);
  }
  return privileges;
}
 
Example 20
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);
    }
  }
}