javax.jdo.PersistenceManager Java Examples

The following examples show how to use javax.jdo.PersistenceManager. 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 Project: seldon-server   Author: SeldonIO   File: JdoClusterCountStore.java    License: 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 #2
Source Project: incubator-sentry   Author: apache   File: PrivilegeOperatePersistence.java    License: Apache License 2.0 6 votes vote down vote up
public boolean checkPrivilegeOption(Set<MSentryRole> roles, PrivilegeObject privilege, PersistenceManager pm) {
  MSentryGMPrivilege requestPrivilege = convertToPrivilege(privilege);
  boolean hasGrant = false;
  //get persistent privileges by roles
  Query query = pm.newQuery(MSentryGMPrivilege.class);
  StringBuilder filters = new StringBuilder();
  if (roles != null && roles.size() > 0) {
    query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role");
    List<String> rolesFiler = new LinkedList<String>();
    for (MSentryRole role : roles) {
      rolesFiler.add("role.roleName == \"" + role.getRoleName() + "\" ");
    }
    filters.append("roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")");
  }
  query.setFilter(filters.toString());

  List<MSentryGMPrivilege> tPrivileges = (List<MSentryGMPrivilege>)query.execute();
  for (MSentryGMPrivilege tPrivilege : tPrivileges) {
    if (tPrivilege.getGrantOption() && tPrivilege.implies(requestPrivilege)) {
      hasGrant = true;
      break;
    }
  }
  return hasGrant;
}
 
Example #3
Source Project: seldon-server   Author: SeldonIO   File: TransactionPeer.java    License: Apache License 2.0 6 votes vote down vote up
private static void setMySQLReadOnly(PersistenceManager pm,boolean readOnly) throws SQLException
{
    JDOConnection jdoconn = pm.getDataStoreConnection();
    try
    {
        Connection conn = (Connection) jdoconn.getNativeConnection();
        //com.mysql.jdbc.ReplicationConnection mySqlConn = (com.mysql.jdbc.ReplicationConnection) conn;  
        conn.setReadOnly(readOnly);
        String catalog =  ((org.datanucleus.api.jdo.JDOPersistenceManagerFactory) pm.getPersistenceManagerFactory()).getCatalog();
        conn.setCatalog(catalog);
    }
    finally
    {
        jdoconn.close();
    }
}
 
Example #4
Source Project: seldon-server   Author: SeldonIO   File: JdoUserClusterStore.java    License: Apache License 2.0 6 votes vote down vote up
public void addTransientCluster(final List<UserCluster> clusters)
{
	try 
	{
		final PersistenceManager pm = getPM();
		TransactionPeer.runTransaction(new Transaction(pm) { 
		    public void process()
		    { 
		    	for(UserCluster cluster : clusters)
		    	{
		    		Query query = pm.newQuery( "javax.jdo.query.SQL","insert into user_clusters_transient (t_id,user_id,cluster_id,weight) values (0,?,?,?)");
		    		query.execute(cluster.getUser(), cluster.getCluster(), cluster.getWeight());
		    		query.closeAll();
		    	}
		    }});
	} catch (DatabaseException e) 
	{
		if (clusters.size() > 0)
			logger.error("Failed to Add Transient cluster for user "+clusters.get(0).getUser(), e);
		else
			logger.error("Failed to add empty transient clusters", e);
	}
	
}
 
Example #5
Source Project: incubator-sentry   Author: apache   File: PrivilegeOperatePersistence.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Explore Privilege graph and collect privileges that are belong to the specific privilege
 */
@SuppressWarnings("unchecked")
private Set<MSentryGMPrivilege> populateIncludePrivileges(Set<MSentryRole> roles,
    MSentryGMPrivilege parent, PersistenceManager pm) {
  Set<MSentryGMPrivilege> childrens = Sets.newHashSet();

  Query query = pm.newQuery(MSentryGMPrivilege.class);
  StringBuilder filters = new StringBuilder();
  //add populateIncludePrivilegesQuery
  filters.append(MSentryGMPrivilege.populateIncludePrivilegesQuery(parent));
  // add filter for role names
  if (roles != null && roles.size() > 0) {
    query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role");
    List<String> rolesFiler = new LinkedList<String>();
    for (MSentryRole role : roles) {
      rolesFiler.add("role.roleName == \"" + role.getRoleName() + "\" ");
    }
    filters.append("&& roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")");
  }
  query.setFilter(filters.toString());

  List<MSentryGMPrivilege> privileges = (List<MSentryGMPrivilege>)query.execute();
  childrens.addAll(privileges);
  return childrens;
}
 
Example #6
Source Project: incubator-sentry   Author: apache   File: DelegateSentryStore.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void clearAllTables() {
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();
    pm.newQuery(MSentryRole.class).deletePersistentAll();
    pm.newQuery(MSentryGroup.class).deletePersistentAll();
    pm.newQuery(MSentryGMPrivilege.class).deletePersistentAll();
    commitUpdateTransaction(pm);
    rollbackTransaction = false;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example #7
Source Project: sc2gears   Author: icza   File: CachingService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Account key associated with the specified authorization key.
 * @param pm               reference to the persistence manager
 * @param authorizationKey authorization key to return the account key for
 * @return the Account key associated with the specified authorization key; or <code>null</code> if the authorization key is invalid
 */
public static Key getAccountKeyByAuthKey( final PersistenceManager pm, final String authorizationKey ) {
	final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey;
	final String accountKeyString = (String) memcacheService.get( memcacheKey );
	if ( accountKeyString != null )
		return KeyFactory.stringToKey( accountKeyString );
	
	final Query q = new Query( Account.class.getSimpleName() );
	q.setFilter( new FilterPredicate( "authorizationKey", FilterOperator.EQUAL, authorizationKey ) );
	q.setKeysOnly();
	final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
	if ( entityList.isEmpty() )
		return null;
	
	final Key accountKey = entityList.get( 0 ).getKey();
	try {
		memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
	}
	catch ( final MemcacheServiceException mse ) {
		LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
		// Ignore memcache errors, do not prevent serving user request
	}
	
	return accountKey;
}
 
Example #8
Source Project: incubator-sentry   Author: apache   File: PrivilegeOperatePersistence.java    License: Apache License 2.0 6 votes vote down vote up
public Set<PrivilegeObject> getPrivilegesByProvider(String component,
    String service, Set<MSentryRole> roles,
    List<? extends Authorizable> authorizables, PersistenceManager pm) {
  Set<PrivilegeObject> privileges = Sets.newHashSet();
  if (roles == null || roles.isEmpty()) {
    return privileges;
  }

  MSentryGMPrivilege parentPrivilege = new MSentryGMPrivilege(component, service, authorizables, null, null);
  Set<MSentryGMPrivilege> privilegeGraph = Sets.newHashSet();
  privilegeGraph.addAll(populateIncludePrivileges(roles, parentPrivilege, pm));

  for (MSentryGMPrivilege mPrivilege : privilegeGraph) {
    privileges.add(new Builder()
                             .setComponent(mPrivilege.getComponentName())
                             .setService(mPrivilege.getServiceName())
                             .setAction(mPrivilege.getAction())
                             .setAuthorizables(mPrivilege.getAuthorizables())
                             .withGrantOption(mPrivilege.getGrantOption())
                             .build());
  }
  return privileges;
}
 
Example #9
Source Project: seldon-server   Author: SeldonIO   File: JDOFactory.java    License: Apache License 2.0 6 votes vote down vote up
public PersistenceManager getPersistenceManager(String key)
 {
  PersistenceManagerFactory pmf = factories.get(key);
  if (pmf == null)
  {
throw new APIException(APIException.INTERNAL_DB_ERROR);
  }
  if (pmf != null)
  {
  	PersistenceManager pm = (PersistenceManager) pmRet.getPersistenceManager(key,pmf);
  	if (!pm.currentTransaction().isActive())
  		TransactionPeer.startReadOnlyTransaction(pm);
  	return pm;
  }
  else
  	return null;
 }
 
Example #10
Source Project: sc2gears   Author: icza   File: ApiUserServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RpcResult< String > getApiKey( final String sharedApiAccount ) {
	LOGGER.fine( "sharedApiAccount: " + sharedApiAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final ApiAccount apiAccount = getApiAccount( pm, sharedApiAccount, user );
		if ( apiAccount == null )
			return RpcResult.createNoPermissionErrorResult();
		else
			return new RpcResult< String >( apiAccount.getApiKey() );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #11
Source Project: ezScrum   Author: ezScrum   File: TenantManagerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void createTenant( String tenantId, String tenantName, String tenantDescription, RentService rentService){
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenant = new TenantDataStore(key);
	tenant.setTenantId(tenantId);
	tenant.setTenantname(tenantName);
	tenant.setDescription(tenantDescription);	
	tenant.setRentService(rentService);
	
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}	
}
 
Example #12
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected Map<String, MSentryRole> getRolesMap() {
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();

    Query query = pm.newQuery(MSentryRole.class);
    List<MSentryRole> mSentryRoles = (List<MSentryRole>) query.execute();
    Map<String, MSentryRole> existRolesMap = Maps.newHashMap();
    if (mSentryRoles != null) {
      // change the List<MSentryRole> -> Map<roleName, Set<MSentryRole>>
      for (MSentryRole mSentryRole : mSentryRoles) {
        existRolesMap.put(mSentryRole.getRoleName(), mSentryRole);
      }
    }

    commitTransaction(pm);
    rollbackTransaction = false;
    return existRolesMap;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example #13
Source Project: ezScrum   Author: ezScrum   File: TenantMapper.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void addTenantAdmin(Account account){
	PersistenceManager pm = PMF.get().getPersistenceManager();
	Key key = KeyFactory.createKey(AccountDataStore.class.getSimpleName(), account.getID());
	
	AccountDataStore accountData = new AccountDataStore(key, account.getID(), account.getPassword());
	accountData.setName(account.getName());
	accountData.setEmail(account.getEmail());
	accountData.setEnable(account.getEnable());
	
	// ?
	List<String> permissions = new ArrayList<String>();
	for (int i=0; i<account.getPermissionList().size(); i++) {
		permissions.add(account.getPermissionList().get(i).getPermissionName());
	}
	accountData.setPermissions(permissions);

	try {
		pm.makePersistent(accountData);
	} finally {
		pm.close();
	}	
}
 
Example #14
Source Project: incubator-sentry   Author: apache   File: DelegateSentryStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Grant option check
 * @param component
 * @param pm
 * @param privilegeReader
 * @throws SentryUserException
 */
private void grantOptionCheck(PrivilegeObject requestPrivilege, String grantorPrincipal,PersistenceManager pm)
    throws SentryUserException {

  if (Strings.isNullOrEmpty(grantorPrincipal)) {
    throw new SentryInvalidInputException("grantorPrincipal should not be null or empty");
  }

  Set<String> groups = getRequestorGroups(grantorPrincipal);
  if (groups == null || groups.isEmpty()) {
    throw new SentryGrantDeniedException(grantorPrincipal
        + " has no grant!");
  }
  //admin group check
  if (!Sets.intersection(adminGroups, toTrimmed(groups)).isEmpty()) {
    return;
  }
  //privilege grant option check
  Set<MSentryRole> mRoles = delegate.getRolesForGroups(pm, groups);
  if (!privilegeOperator.checkPrivilegeOption(mRoles, requestPrivilege, pm)) {
    throw new SentryGrantDeniedException(grantorPrincipal
        + " has no grant!");
  }
}
 
Example #15
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Roles can be granted ALL, SELECT, and INSERT on tables. When
 * a role has ALL and SELECT or INSERT are revoked, we need to remove the ALL
 * privilege and add SELECT (INSERT was revoked) or INSERT (SELECT was revoked).
 */
private void revokePartial(PersistenceManager pm,
    TSentryPrivilege requestedPrivToRevoke, MSentryRole mRole,
    MSentryPrivilege currentPrivilege) throws SentryInvalidInputException {
  MSentryPrivilege persistedPriv = getMSentryPrivilege(convertToTSentryPrivilege(currentPrivilege), pm);
  if (persistedPriv == null) {
    persistedPriv = convertToMSentryPrivilege(convertToTSentryPrivilege(currentPrivilege));
  }

  if (requestedPrivToRevoke.getAction().equalsIgnoreCase("ALL") || requestedPrivToRevoke.getAction().equalsIgnoreCase("*")) {
    persistedPriv.removeRole(mRole);
    privCleaner.incPrivRemoval();
    pm.makePersistent(persistedPriv);
  } else if (requestedPrivToRevoke.getAction().equalsIgnoreCase(AccessConstants.SELECT)
      && !currentPrivilege.getAction().equalsIgnoreCase(AccessConstants.INSERT)) {
    revokeRolePartial(pm, mRole, currentPrivilege, persistedPriv, AccessConstants.INSERT);
  } else if (requestedPrivToRevoke.getAction().equalsIgnoreCase(AccessConstants.INSERT)
      && !currentPrivilege.getAction().equalsIgnoreCase(AccessConstants.SELECT)) {
    revokeRolePartial(pm, mRole, currentPrivilege, persistedPriv, AccessConstants.SELECT);
  }
}
 
Example #16
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 6 votes vote down vote up
public CommitContext alterSentryRoleAddGroups( String grantorPrincipal, String roleName,
    Set<TSentryGroup> groupNames)
        throws SentryNoSuchObjectException {
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();
    alterSentryRoleAddGroupsCore(pm, roleName, groupNames);
    CommitContext commit = commitUpdateTransaction(pm);
    rollbackTransaction = false;
    return commit;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example #17
Source Project: seldon-server   Author: SeldonIO   File: JdoClusterCountStore.java    License: 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 #18
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 6 votes vote down vote up
private MSentryPrivilege getMSentryPrivilege(TSentryPrivilege tPriv, PersistenceManager pm) {
  Query query = pm.newQuery(MSentryPrivilege.class);
  query.setFilter("this.serverName == \"" + toNULLCol(safeTrimLower(tPriv.getServerName())) + "\" "
      + "&& this.dbName == \"" + toNULLCol(safeTrimLower(tPriv.getDbName())) + "\" "
      + "&& this.tableName == \"" + toNULLCol(safeTrimLower(tPriv.getTableName())) + "\" "
      + "&& this.columnName == \"" + toNULLCol(safeTrimLower(tPriv.getColumnName())) + "\" "
      + "&& this.URI == \"" + toNULLCol(safeTrim(tPriv.getURI())) + "\" "
      + "&& this.grantOption == grantOption "
      + "&& this.action == \"" + toNULLCol(safeTrimLower(tPriv.getAction())) + "\"");
  query.declareParameters("Boolean grantOption");
  query.setUnique(true);
  Boolean grantOption = null;
  if (tPriv.getGrantOption().equals(TSentryGrantOption.TRUE)) {
    grantOption = true;
  } else if (tPriv.getGrantOption().equals(TSentryGrantOption.FALSE)) {
    grantOption = false;
  }
  Object obj = query.execute(grantOption);
  if (obj != null) {
    return (MSentryPrivilege) obj;
  }
  return null;
}
 
Example #19
Source Project: appengine-gwtguestbook-namespaces-java   Author: googlearchive   File: GuestServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<GuestbookEntryTransferObject> getTenLatestEntries() {
  PersistenceManager pm = PersistenceManagerHelper.getPersistenceManager();
  try {
    // Set the query to get the ten latest guest entries
    Query query = pm.newQuery(GuestbookEntry.class);
    query.setOrdering("timestamp DESC");
    query.setRange("0, 10");
    List<GuestbookEntry> entries = (List<GuestbookEntry>) query.execute();

    // Create a new guestbook entry transfer object for each entry and add
    // them to the list
    List<GuestbookEntryTransferObject> entryTransferObjects =
        new ArrayList<GuestbookEntryTransferObject>(entries.size());
    for (GuestbookEntry entry : entries) {
      entryTransferObjects.add(new GuestbookEntryTransferObject(entry
          .getName(), entry.getMessage()));
    }
    return entryTransferObjects;
  } finally {
    if (pm.currentTransaction().isActive()) {
      pm.currentTransaction().rollback();
    }
  }
}
 
Example #20
Source Project: two-token-sw   Author: googlearchive   File: UserStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Changes the password for an email.
 * 
 * @param email the email address to be updated
 * @param oldPassword the old password
 * @param newPassword the new password
 * @return response code for the operation
 */
public static AccountOperationResponseCode updatePassword(String email, String oldPassword,
    String newPassword) {
  PersistenceManager pm = pmf.getPersistenceManager();
  try {
    UserRecord user = findUserByEmail(pm, email);
    if (user != null) {
      user.setPassword(newPassword);
      pm.makePersistent(user);
      return AccountOperationResponseCode.OK;
    } else {
      return AccountOperationResponseCode.USER_NOT_FOUND;
    }
  } finally {
    pm.close();
  }
}
 
Example #21
Source Project: Alpine   Author: stevespringett   File: PersistenceManagerFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JDO PersistenceManager.
 * @return a PersistenceManager
 */
public static PersistenceManager createPersistenceManager() {
    if (Config.isUnitTestsEnabled()) {
        pmf = (JDOPersistenceManagerFactory)JDOHelper.getPersistenceManagerFactory(JdoProperties.unit(), "Alpine");
    }
    if (pmf == null) {
        throw new IllegalStateException("Context is not initialized yet.");
    }
    return pmf.getPersistenceManager();
}
 
Example #22
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
Get the MSentry object from roleName
Note: Should be called inside a transaction
 */
public MSentryRole getMSentryRole(PersistenceManager pm, String roleName) {
  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(roleName);
  return sentryRole;
}
 
Example #23
Source Project: incubator-sentry   Author: apache   File: TestSentryRole.java    License: Apache License 2.0 5 votes vote down vote up
private MSentryRole getMSentryRole(PersistenceManager pm, String roleName) {
  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(roleName);
  return sentryRole;
}
 
Example #24
Source Project: incubator-sentry   Author: apache   File: PrivilegeOperatePersistence.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Set<PrivilegeObject> getPrivilegesByRole(Set<MSentryRole> roles, PersistenceManager pm) {
  Set<PrivilegeObject> privileges = Sets.newHashSet();
  if (roles == null || roles.size() == 0) {
    return privileges;
  }
  Query query = pm.newQuery(MSentryGMPrivilege.class);
  StringBuilder filters = new StringBuilder();
  // add filter for role names
  query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role");
  List<String> rolesFiler = new LinkedList<String>();
  for (MSentryRole role : roles) {
    rolesFiler.add("role.roleName == \"" + role.getRoleName() + "\" ");
  }
  filters.append("roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")");

  query.setFilter(filters.toString());
  List<MSentryGMPrivilege> mPrivileges = (List<MSentryGMPrivilege>) query.execute();
  if (mPrivileges == null || mPrivileges.isEmpty()) {
    return privileges;
  }
  for (MSentryGMPrivilege mPrivilege : mPrivileges) {
    privileges.add(new Builder()
                             .setComponent(mPrivilege.getComponentName())
                             .setService(mPrivilege.getServiceName())
                             .setAction(mPrivilege.getAction())
                             .setAuthorizables(mPrivilege.getAuthorizables())
                             .withGrantOption(mPrivilege.getGrantOption())
                             .build());
  }
  return privileges;
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: PersistenceManagerFactoryUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtain a JDO PersistenceManager via the given factory. Is aware of a
 * corresponding PersistenceManager bound to the current thread,
 * for example when using JdoTransactionManager. Will create a new
 * PersistenceManager else, if "allowCreate" is {@code true}.
 * <p>Same as {@code getPersistenceManager}, but throwing the original JDOException.
 * @param pmf PersistenceManagerFactory to create the PersistenceManager with
 * @param allowCreate if a non-transactional PersistenceManager should be created
 * when no transactional PersistenceManager can be found for the current thread
 * @return the PersistenceManager
 * @throws JDOException if the PersistenceManager couldn't be created
 * @throws IllegalStateException if no thread-bound PersistenceManager found and
 * "allowCreate" is {@code false}
 * @see #getPersistenceManager(javax.jdo.PersistenceManagerFactory, boolean)
 * @see JdoTransactionManager
 */
public static PersistenceManager doGetPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate)
	throws JDOException, IllegalStateException {

	Assert.notNull(pmf, "No PersistenceManagerFactory specified");

	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null) {
		if (!pmHolder.isSynchronizedWithTransaction() &&
				TransactionSynchronizationManager.isSynchronizationActive()) {
			pmHolder.setSynchronizedWithTransaction(true);
			TransactionSynchronizationManager.registerSynchronization(
					new PersistenceManagerSynchronization(pmHolder, pmf, false));
		}
		return pmHolder.getPersistenceManager();
	}

	if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
		throw new IllegalStateException("No JDO PersistenceManager bound to thread, " +
				"and configuration does not allow creation of non-transactional one here");
	}

	logger.debug("Opening JDO PersistenceManager");
	PersistenceManager pm = pmf.getPersistenceManager();

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering transaction synchronization for JDO PersistenceManager");
		// Use same PersistenceManager for further JDO actions within the transaction.
		// Thread object will get removed by synchronization at transaction completion.
		pmHolder = new PersistenceManagerHolder(pm);
		pmHolder.setSynchronizedWithTransaction(true);
		TransactionSynchronizationManager.registerSynchronization(
				new PersistenceManagerSynchronization(pmHolder, pmf, true));
		TransactionSynchronizationManager.bindResource(pmf, pmHolder);
	}

	return pm;
}
 
Example #26
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Rename given privilege from all roles drop the old privilege and create the new one
 * @param tAuthorizable
 * @param newTAuthorizable
 * @throws SentryNoSuchObjectException
 * @throws SentryInvalidInputException
 */
public void renamePrivilege(TSentryAuthorizable tAuthorizable,
    TSentryAuthorizable newTAuthorizable)
    throws SentryNoSuchObjectException, SentryInvalidInputException {
  PersistenceManager pm = null;
  boolean rollbackTransaction = true;

  TSentryPrivilege tPrivilege = toSentryPrivilege(tAuthorizable);
  TSentryPrivilege newPrivilege = toSentryPrivilege(newTAuthorizable);

  try {
    pm = openTransaction();
    // In case of tables or DBs, check all actions
    if (isMultiActionsSupported(tPrivilege)) {
      for (String privilegeAction : ALL_ACTIONS) {
        tPrivilege.setAction(privilegeAction);
        newPrivilege.setAction(privilegeAction);
        renamePrivilegeForAllRoles(pm, tPrivilege, newPrivilege);
      }
    } else {
      renamePrivilegeForAllRoles(pm, tPrivilege, newPrivilege);
    }
    rollbackTransaction = false;
    commitTransaction(pm);
  } catch (JDODataStoreException e) {
    throw new SentryInvalidInputException("Failed to get privileges: "
        + e.getMessage());
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example #27
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 5 votes vote down vote up
private void alterSentryRoleRevokePrivilegeCore(PersistenceManager pm,
    String roleName, TSentryPrivilege tPrivilege)
    throws SentryNoSuchObjectException, SentryInvalidInputException {
  Query query = pm.newQuery(MSentryRole.class);
  query.setFilter("this.roleName == t");
  query.declareParameters("java.lang.String t");
  query.setUnique(true);
  MSentryRole mRole = (MSentryRole) query.execute(roleName);
  if (mRole == null) {
    throw new SentryNoSuchObjectException("Role: " + roleName + " doesn't exist");
  } else {
    query = pm.newQuery(MSentryPrivilege.class);
    MSentryPrivilege mPrivilege = getMSentryPrivilege(tPrivilege, pm);
    if (mPrivilege == null) {
      mPrivilege = convertToMSentryPrivilege(tPrivilege);
    } else {
      mPrivilege = (MSentryPrivilege) pm.detachCopy(mPrivilege);
    }

    Set<MSentryPrivilege> privilegeGraph = Sets.newHashSet();
    if (mPrivilege.getGrantOption() != null) {
      privilegeGraph.add(mPrivilege);
    } else {
      MSentryPrivilege mTure = new MSentryPrivilege(mPrivilege);
      mTure.setGrantOption(true);
      privilegeGraph.add(mTure);
      MSentryPrivilege mFalse = new MSentryPrivilege(mPrivilege);
      mFalse.setGrantOption(false);
      privilegeGraph.add(mFalse);
    }
    // Get the privilege graph
    populateChildren(pm, Sets.newHashSet(roleName), mPrivilege, privilegeGraph);
    for (MSentryPrivilege childPriv : privilegeGraph) {
      revokePrivilegeFromRole(pm, tPrivilege, mRole, childPriv);
    }
    pm.makePersistent(mRole);
  }
}
 
Example #28
Source Project: google-oauth-java-client   Author: googleapis   File: AbstractFlowUserServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Start the auth flow. Don't run any code after this method that will change the response object.
 */
private void startAuthFlow(
    HttpServletResponse resp, PersistenceManager pm, ThreeLeggedFlow oauthFlow)
    throws IOException {
  pm.makePersistent(oauthFlow);
  String authorizationUrl = oauthFlow.getAuthorizationUrl();
  resp.sendRedirect(authorizationUrl);
}
 
Example #29
Source Project: incubator-sentry   Author: apache   File: SentryStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This returns a Mapping of Role -> [Groups]
 */
public Map<String, LinkedList<String>> retrieveFullRoleImage() {
  Map<String, LinkedList<String>> retVal = new HashMap<String, LinkedList<String>>();
  boolean rollbackTransaction = true;
  PersistenceManager pm = null;
  try {
    pm = openTransaction();
    Query query = pm.newQuery(MSentryGroup.class);
    List<MSentryGroup> groups = (List<MSentryGroup>) query.execute();
    for (MSentryGroup mGroup : groups) {
      for (MSentryRole role : mGroup.getRoles()) {
        LinkedList<String> rUpdate = retVal.get(role.getRoleName());
        if (rUpdate == null) {
          rUpdate = new LinkedList<String>();
          retVal.put(role.getRoleName(), rUpdate);
        }
        rUpdate.add(mGroup.getGroupName());
      }
    }
    commitTransaction(pm);
    return retVal;
  } finally {
    if (rollbackTransaction) {
      rollbackTransaction(pm);
    }
  }
}
 
Example #30
Source Project: appengine-modules-sample-java   Author: GoogleCloudPlatform   File: ShardedCounter.java    License: Apache License 2.0 5 votes vote down vote up
public int addShards(int count) {
  int numShards = 0;
  PersistenceManager pm = PMF.get().getPersistenceManager();
  try {
    final DatastoreCounter current = getThisCounter(pm);
    if (current != null) {
      numShards = current.getShardCount().intValue();
      current.setShardCount(numShards + count);
      pm.makePersistent(current);
    }
  } finally {
    pm.close();
  }

  pm = PMF.get().getPersistenceManager();
  try {
    for (int i = 0; i < count; i++) {
      final DatastoreCounterShard newShard = new DatastoreCounterShard(
          getCounterName(), numShards);
      pm.makePersistent(newShard);
      numShards++;
    }
  } finally {
    pm.close();
  }

  if (cache != null) {
    cache.put("shards" + counterName, Integer.valueOf(numShards));
  }

  return numShards;
}