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

The following examples show how to use javax.jdo.PersistenceManager#makePersistent() . 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: UserStore.java    From two-token-sw with 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 2
Source File: UserStore.java    From two-token-sw with 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 updateProfile(String email, String displayName,
    String photoUrl) {
  PersistenceManager pm = pmf.getPersistenceManager();
  try {
    UserRecord user = findUserByEmail(pm, email);
    if (user != null) {
      user.setDisplayName(displayName);
      user.setPhotoUrl(photoUrl);
      pm.makePersistent(user);
      return AccountOperationResponseCode.OK;
    } else {
      return AccountOperationResponseCode.USER_NOT_FOUND;
    }
  } finally {
    pm.close();
  }
}
 
Example 3
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private void revokeRolePartial(PersistenceManager pm, MSentryRole mRole,
    MSentryPrivilege currentPrivilege, MSentryPrivilege persistedPriv, String addAction)
    throws SentryInvalidInputException {
  // If table / URI, remove ALL
  persistedPriv.removeRole(mRole);
  privCleaner.incPrivRemoval();
  pm.makePersistent(persistedPriv);

  currentPrivilege.setAction(AccessConstants.ALL);
  persistedPriv = getMSentryPrivilege(convertToTSentryPrivilege(currentPrivilege), pm);
  if (persistedPriv != null && mRole.getPrivileges().contains(persistedPriv)) {
    persistedPriv.removeRole(mRole);
    privCleaner.incPrivRemoval();
    pm.makePersistent(persistedPriv);

    currentPrivilege.setAction(addAction);
    persistedPriv = getMSentryPrivilege(convertToTSentryPrivilege(currentPrivilege), pm);
    if (persistedPriv == null) {
      persistedPriv = convertToMSentryPrivilege(convertToTSentryPrivilege(currentPrivilege));
      mRole.appendPrivilege(persistedPriv);
    }
    persistedPriv.appendRole(mRole);
    pm.makePersistent(persistedPriv);
  }
}
 
Example 4
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
public void CreateProducts() {
    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);
        for (int i = 0; i < 100; i++) {
            String nam = "Product-" + i;
            double price = rnd.nextDouble();
            Product productx = new Product(nam, price);
            pm.makePersistent(productx);
        }
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example 5
Source File: TenantManagerTest.java    From ezScrum with 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 6
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void addTenant(String tenantId, String name, String description, RentService rentService) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenant = new TenantDataStore(key);
	tenant.setTenantname(name);
	tenant.setTenantId(tenantId);
	tenant.setDescription(description);	
	tenant.setRentService(rentService);
	
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}	
}
 
Example 7
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
public void persistXML() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        ProductXML productXML = new ProductXML(0, "Tablet", 80.0);
        pm.makePersistent(productXML);
        ProductXML productXML2 = new ProductXML(1, "Phone", 20.0);
        pm.makePersistent(productXML2);
        ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0);
        pm.makePersistent(productXML3);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example 8
Source File: SentryStore.java    From incubator-sentry with 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 9
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
private void updateFileDownlStats( final PersistenceManager pm, final Key accountKey, final long fileSize, final String fileTypeString ) {
	LOGGER.fine( "Account key: " + accountKey );
	
	final FileType fileType = FileType.fromString( fileTypeString );
	final Key      fsKey    = ServerUtils.getSingleKeyQueryResult( FileStat.class, "ownerKey", accountKey );
	final FileStat fileStat = fsKey == null ? new FileStat( accountKey ) : pm.getObjectById( FileStat.class, fsKey );
	
	fileStat.increaseOutbw( fileType, fileSize );
	
	if ( fileStat.getKey() == null )
		pm.makePersistent( fileStat );
}
 
Example 10
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 11
Source File: SentryStore.java    From incubator-sentry with 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 12
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public void stopTenant(String tenantId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenant = pm.getObjectById(TenantDataStore.class, key);
	
	tenant.setEnable(false);		
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}
}
 
Example 13
Source File: PrivilegeOperatePersistence.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
public void revokePrivilege(PrivilegeObject privilege,MSentryRole role, PersistenceManager pm) throws SentryUserException {
  MSentryGMPrivilege mPrivilege = getPrivilege(convertToPrivilege(privilege), pm);
  if (mPrivilege == null) {
    mPrivilege = convertToPrivilege(privilege);
  } else {
    mPrivilege = (MSentryGMPrivilege) pm.detachCopy(mPrivilege);
  }

  Set<MSentryGMPrivilege> privilegeGraph = Sets.newHashSet();
  privilegeGraph.addAll(populateIncludePrivileges(Sets.newHashSet(role), mPrivilege, pm));

  /**
   * Get the privilege graph
   * populateIncludePrivileges will get the privileges that needed revoke
   */
  for (MSentryGMPrivilege persistedPriv : privilegeGraph) {
    /**
     * force to load all roles related this privilege
     * avoid the lazy-loading risk,such as:
     * if the roles field of privilege aren't loaded, then the roles is a empty set
     * privilege.removeRole(role) and pm.makePersistent(privilege)
     * will remove other roles that shouldn't been removed
     */
    revokeRolePartial(mPrivilege, persistedPriv, role, pm);
  }
  pm.makePersistent(role);
}
 
Example 14
Source File: ApiUserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< ApiUserInfo > getApiUserInfo( final String sharedApiAccount ) {
	LOGGER.fine( "sharedApiAccount: " + sharedApiAccount );
	
	final ApiUserInfo apiUserInfo = new ApiUserInfo();
	
	final UserService userService = UserServiceFactory.getUserService();
	final User        user        = userService.getCurrentUser();
	
	if ( user == null )
		apiUserInfo.setLoginUrl( userService.createLoginURL( "/ApiUser.html" ) );
	else {
		
		apiUserInfo.setUserNickname( user.getNickname() );
		apiUserInfo.setUserName    ( user.getNickname() );
		apiUserInfo.setLogoutUrl   ( userService.createLogoutURL( "/ApiUser.html" ) );
		
		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			
			final ApiAccount apiAccount = getApiAccount( pm, sharedApiAccount, user );
			
			if ( sharedApiAccount == null ) {
				if ( apiAccount != null ) {
					final List< ApiVisit > apiVisitList = new JQBuilder<>( pm, ApiVisit.class ).filter( "visitorKey==p1", "KEY p1" ).desc( "date" ).range( 0, 1 ).get( apiAccount.getKey() );
					if ( !apiVisitList.isEmpty() )
						apiUserInfo.setLastVisit( apiVisitList.get( 0 ).getDate() );
				}
				
				// Check if visiting user is new (unique)
				final com.google.appengine.api.datastore.Query q = new com.google.appengine.api.datastore.Query( ApiVisit.class.getSimpleName() );
				q.setFilter( new FilterPredicate( "user", FilterOperator.EQUAL, user ) );
				final boolean isNew = ServerUtils.isQueryResultEmpty( q );
				
				// Log API visit
				final ApiVisit apiVisit = new ApiVisit( user );
				apiVisit.fillTracking( getThreadLocalRequest() );
				if ( apiAccount != null )
					apiVisit.setVisitorKey( apiAccount.getKey() );
				pm.makePersistent( apiVisit );
				
				// Update API visit stats
				TaskServlet.register_updateDownloadStat( API_VISIT_STATS_FILE_NAME, getThreadLocalRequest().getHeader( "User-Agent" ), isNew, 1 );
				
				if ( apiAccount != null ) {
					if ( apiAccount.getName() != null && !apiAccount.getName().isEmpty() )
						apiUserInfo.setUserName( apiAccount.getName() );
					apiUserInfo.setAdmin( userService.isUserAdmin() );
					
					final List< String >  sharedAccounts;
					if ( apiUserInfo.isAdmin() ) {
						// Get list of API accounts we have access to
						final List< ApiAccount > sharedAccountList = new JQBuilder<>( pm, ApiAccount.class ).get(); // All (full list)
						sharedAccounts = new ArrayList< String >( sharedAccountList.size() );
						for ( final ApiAccount sharedAccount_ : sharedAccountList ) {
							if ( !user.equals( sharedAccount_.getUser() ) ) // Do not add ourselves, we insert that to the first later
								sharedAccounts.add( sharedAccount_.getUser().getEmail() );
						}
						// Sort by Google account
						Collections.sort( sharedAccounts, String.CASE_INSENSITIVE_ORDER );
					}
					else {
						sharedAccounts = new ArrayList< String >( 1 );
					}
					sharedAccounts.add( 0, apiAccount.getUser().getEmail() ); // Insert owner account to the first of the list
					apiUserInfo.setSharedAccounts( sharedAccounts );
				}
				else {
					// Send and display the Google Account email address:
					apiUserInfo.setUserName( user.getEmail() );
				}
			}
			else {
				// Accessing shared API account...
				apiUserInfo.setSharedApiAccount( sharedApiAccount );
			}
			
			if ( apiAccount != null ) {
				apiUserInfo.setHasApiAccount( true );
				apiUserInfo.setRepParserEngineVer( ReplayFactory.getVersion() );
			}
			
		} finally {
			if ( pm != null )
				pm.close();
		}
	}
	
	return new RpcResult< ApiUserInfo >( apiUserInfo );
}
 
Example 15
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
  public RpcResult< Void > register( final FreeAccountInfo freeAccountInfo ) {
final UserService userService = UserServiceFactory.getUserService();
final User user = userService.getCurrentUser();
if ( user == null )
	return RpcResult.createNotLoggedInErrorResult();

if ( freeAccountInfo.getGoogleAccount() == null || freeAccountInfo.getGoogleAccount().isEmpty() )
	return RpcResult.createErrorResult( "Google account is required! Refresh the page!" );

if ( !ServerUtils.isEmailValid( freeAccountInfo.getGoogleAccount() ) )
	return RpcResult.createErrorResult( "Invalid Google account! Refresh the page!" );

if ( !user.getEmail().equals( freeAccountInfo.getGoogleAccount() ) )
	return RpcResult.createErrorResult( "Google account does not match the user you're logged in with! Refresh the page!" );

if ( freeAccountInfo.getContactEmail() != null && freeAccountInfo.getContactEmail().length() > 500 )
	return RpcResult.createErrorResult( "Invalid contact email, cannot be longer than 500 characters!" );

if ( freeAccountInfo.getContactEmail() != null && !freeAccountInfo.getContactEmail().isEmpty() )
	if ( !ServerUtils.isEmailValid( freeAccountInfo.getContactEmail() ) )
		return RpcResult.createErrorResult( "Invalid contact email!" );

if ( freeAccountInfo.getName() != null && freeAccountInfo.getName().length() > 500 )
	return RpcResult.createErrorResult( "Invalid name, cannot be longer than 500 characters!" );

PersistenceManager pm = null;
try {
	
	pm = PMF.get().getPersistenceManager();
	
	if ( !( (List< ? >) pm.newQuery( "select key from " + Account.class.getName() + " where user==:1" ).execute( user ) ).isEmpty() )
		return RpcResult.createErrorResult( "There is already an account with this Google account! Refresh the page!" );
	
	// REGISTRATION IS DISABLED.
	if ( true )
		return RpcResult.createErrorResult( "Registration is disabled!" );
	
	// Create and save account
	final Account account = new Account( user );
	ServerUtils.initializeNewAccount( pm, account );
	if ( freeAccountInfo.getName() != null && !freeAccountInfo.getName().isEmpty() )
		account.setName( freeAccountInfo.getName() );
	if ( freeAccountInfo.getContactEmail() != null && !freeAccountInfo.getContactEmail().isEmpty() )
		account.setContactEmail( freeAccountInfo.getContactEmail() );
	account.setCountry( ServerUtils.countryCodeToName( getThreadLocalRequest().getHeader( "X-AppEngine-Country" ) ) );
	pm.makePersistent( account );
	
	// Email will be sent by the TaskServlet:
	TaskServlet.register_updatePackageTask( account.getKey() );
	
} finally {
	if ( pm != null )
		pm.close();
}

   return new RpcResult< Void >();
  }
 
Example 16
Source File: UserStore.java    From two-token-sw with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an new user by the input fields.
 * 
 * @param parameters user's input fields
 * @param errors an array to output multiple error messages
 * @return the created user
 */
public static UserImpl signup(Map<String, String[]> parameters, String ip,
    List<SignupError> errors) {
  log.entering("GaeStore", "signup");
  String email = getFirst(parameters, "email");
  String displayName = getFirst(parameters, "displayName");
  String photoUrl = getFirst(parameters, "photoUrl");
  String password = getFirst(parameters, "password");
  String confirm = getFirst(parameters, "confirm");
  if (Strings.isNullOrEmpty(email) || !EmailValidator.isValid(email)) {
    errors.add(SignupError.INVALID_EMAIL);
  }
  if (Strings.isNullOrEmpty(displayName)) {
    errors.add(SignupError.EMPTY_DISPLAY_NAME);
  }
  if (Strings.isNullOrEmpty(password)) {
    errors.add(SignupError.INVALID_PASSWORD);
  } else if (!password.equals(confirm)) {
    errors.add(SignupError.CONFIRM_MISMATCH);
  } else if (password.length() < 3) {
    errors.add(SignupError.INVALID_PASSWORD);
  }

  PersistenceManager pm = pmf.getPersistenceManager();
  try {
    UserRecord record = findUserByEmail(pm, email);
    if (record != null) {
      errors.add(SignupError.EMAIL_REGISTERED);
    } else if (errors.isEmpty()) {
      log.fine("Create new legacy user for: " + email);
      record = new UserRecord();
      record.setEmail(email);
      record.setDisplayName(displayName);
      record.setPhotoUrl(photoUrl);
      record.setPassword(password);
      record.setTosAccepted(true);
      pm.makePersistent(record);
      UserImpl user = createUserByRecord(record);
      return user;
    }
  } finally {
    pm.close();
  }
  log.exiting("GaeStore", "signup");
  return null;
}
 
Example 17
Source File: TopScoresServlet.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
/**
 * Stores the submitted Mouse practice game score.
 * @param authorizationKey authorization key of the user
 */
private static void submitMousePracticeScore( final String authorizationKey, final HttpServletRequest request, final HttpServletResponse response ) throws IOException {
	final String  userName    = request.getParameter( PARAM_USER_NAME     );
	final String  gameVersion = request.getParameter( PARAM_GAME_VERSION  );
	final Integer userScore   = getIntParam  ( request, PARAM_SCORE       );
	final Float   accuracy    = getFloatParam( request, PARAM_ACCURACY    );
	final Integer hits        = getIntParam  ( request, PARAM_HITS        );
	final Integer gameLength  = getIntParam  ( request, PARAM_GAME_LENGTH );
	final Long    randomSeed  = getLongParam ( request, PARAM_RANDOM_SEED );
	
	if ( userName == null || gameVersion == null || userScore == null || accuracy == null || hits == null || gameLength == null ) {
		LOGGER.warning( "Missing parameters!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing parameters!" );
		return;
	}
	
	LOGGER.fine( "Authorization key: " + authorizationKey + ", user score: " + userScore );
	
	if ( userScore <= 0 ) {
		LOGGER.warning( "Invalid parameter values!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid parameter values!" );
		return;
	}
	
	PersistenceManager pm = null;
	try {
		pm = PMF.get().getPersistenceManager();
		
		// Account
		final Key accountKey = CachingService.getAccountKeyByAuthKey( pm, authorizationKey );
		if ( accountKey == null ) {
			LOGGER.warning( "Unauthorized access, invalid Authorization Key!" );
			response.sendError( HttpServletResponse.SC_FORBIDDEN, "Unauthorized access, invalid Authorization Key!" );
			return;
		}
		
		final MousePracticeGameScore score = new MousePracticeGameScore();
		
		score.setAccountKey ( accountKey                                   );
		score.fillTracking  ( request                                      );
		score.setUserName   ( TopScoresServletApi.trimUserName( userName ) );
		score.setGameVersion( gameVersion                                  );
		score.setScore      ( userScore                                    );
		score.setAccuracy   ( accuracy                                     );
		score.setHits       ( hits                                         );
		score.setGameLength ( gameLength                                   );
		score.setRandomSeed ( randomSeed                                   );
		
		pm.makePersistent( score );
		
    	// Invalidate the cached top scores table
		CachingService.removeMousePracticeTopScores();
		
		// I do not delete scores beyond the table size, this will allow viewing the historical score table (score table at any given time) 
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 18
Source File: SentryStore.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
private MSentryPrivilege alterSentryRoleGrantPrivilegeCore(PersistenceManager pm,
    String roleName, TSentryPrivilege privilege)
    throws SentryNoSuchObjectException, SentryInvalidInputException {
  MSentryPrivilege mPrivilege = null;
  MSentryRole mRole = getMSentryRole(pm, roleName);
  if (mRole == null) {
    throw new SentryNoSuchObjectException("Role: " + roleName + " doesn't exist");
  } else {

    if (!isNULL(privilege.getColumnName()) || !isNULL(privilege.getTableName())
        || !isNULL(privilege.getDbName())) {
      // If Grant is for ALL and Either INSERT/SELECT already exists..
      // need to remove it and GRANT ALL..
      if (AccessConstants.ALL.equalsIgnoreCase(privilege.getAction())
          || AccessConstants.ACTION_ALL.equalsIgnoreCase(privilege.getAction())) {
        TSentryPrivilege tNotAll = new TSentryPrivilege(privilege);
        tNotAll.setAction(AccessConstants.SELECT);
        MSentryPrivilege mSelect = getMSentryPrivilege(tNotAll, pm);
        tNotAll.setAction(AccessConstants.INSERT);
        MSentryPrivilege mInsert = getMSentryPrivilege(tNotAll, pm);
        if (mSelect != null && mRole.getPrivileges().contains(mSelect)) {
          mSelect.removeRole(mRole);
          privCleaner.incPrivRemoval();
          pm.makePersistent(mSelect);
        }
        if (mInsert != null && mRole.getPrivileges().contains(mInsert)) {
          mInsert.removeRole(mRole);
          privCleaner.incPrivRemoval();
          pm.makePersistent(mInsert);
        }
      } else {
        // If Grant is for Either INSERT/SELECT and ALL already exists..
        // do nothing..
        TSentryPrivilege tAll = new TSentryPrivilege(privilege);
        tAll.setAction(AccessConstants.ALL);
        MSentryPrivilege mAll1 = getMSentryPrivilege(tAll, pm);
        tAll.setAction(AccessConstants.ACTION_ALL);
        MSentryPrivilege mAll2 = getMSentryPrivilege(tAll, pm);
        if (mAll1 != null && mRole.getPrivileges().contains(mAll1)) {
          return null;
        }
        if (mAll2 != null && mRole.getPrivileges().contains(mAll2)) {
          return null;
        }
      }
    }

    mPrivilege = getMSentryPrivilege(privilege, pm);
    if (mPrivilege == null) {
      mPrivilege = convertToMSentryPrivilege(privilege);
    }
    mPrivilege.appendRole(mRole);
    pm.makePersistent(mRole);
    pm.makePersistent(mPrivilege);
  }
  return mPrivilege;
}
 
Example 19
Source File: PrivilegeOperatePersistence.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
/**
 * Roles can be granted multi-bit set action like ALL action on resource object.
 * Take solr component for example, When a role has been granted ALL action but
 * QUERY or UPDATE or CREATE are revoked, we need to remove the ALL
 * privilege and add left privileges like UPDATE and CREATE(QUERY was revoked) or
 * QUERY and UPDATE(CREATEE was revoked).
 */
private void revokeRolePartial(MSentryGMPrivilege revokePrivilege,
    MSentryGMPrivilege persistedPriv, MSentryRole role,
    PersistenceManager pm) {
  String component = revokePrivilege.getComponentName();
  BitFieldAction revokeaction = getAction(component, revokePrivilege.getAction());
  BitFieldAction persistedAction = getAction(component, persistedPriv.getAction());
  BitFieldAction allAction = getAction(component, Action.ALL);

  if (revokeaction.implies(allAction)) {
    /**
     * if revoke action is ALL, directly revoke its children privileges and itself
     */
    persistedPriv.removeRole(role);
    pm.makePersistent(persistedPriv);
  } else {
    /**
     * if persisted action is ALL, it only revoke the requested action and left partial actions
     * like the requested action is SELECT, the UPDATE and CREATE action are left
     */
    if (persistedAction.implies(allAction)) {
      /**
       * revoke the ALL privilege
       */
      persistedPriv.removeRole(role);
      pm.makePersistent(persistedPriv);

      List<? extends BitFieldAction> actions = getActionFactory(component).getActionsByCode(allAction.getActionCode());
      for (BitFieldAction ac: actions) {
        if (ac.getActionCode() != revokeaction.getActionCode()) {
          /**
           * grant the left privileges to role
           */
          MSentryGMPrivilege tmpPriv = new MSentryGMPrivilege(persistedPriv);
          tmpPriv.setAction(ac.getValue());
          MSentryGMPrivilege leftPersistedPriv = getPrivilege(tmpPriv, pm);
          if (leftPersistedPriv == null) {
            //leftPersistedPriv isn't exist
            leftPersistedPriv = tmpPriv;
            role.appendGMPrivilege(leftPersistedPriv);
          }
          leftPersistedPriv.appendRole(role);
          pm.makePersistent(leftPersistedPriv);
        }
      }
    } else if (revokeaction.implies(persistedAction)) {
      /**
       * if the revoke action is equal to the persisted action and they aren't ALL action
       * directly remove the role from privilege
       */
      persistedPriv.removeRole(role);
      pm.makePersistent(persistedPriv);
    }
    /**
     * if the revoke action is not equal to the persisted action,
     * do nothing
     */
  }
}
 
Example 20
Source File: TestSentryRole.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeletePrivilegeAndRole() throws Exception {
  String roleName = "r1";
  //hive/impala privilege
  MSentryPrivilege hivePrivilege = new MSentryPrivilege();
  hivePrivilege.setServerName("hive.server1");
  hivePrivilege.setDbName("db1");
  hivePrivilege.setTableName("tb1");
  hivePrivilege.setPrivilegeScope("table");
  hivePrivilege.setAction("select");
  hivePrivilege.setURI(SentryStore.NULL_COL);
  hivePrivilege.setColumnName(SentryStore.NULL_COL);
  hivePrivilege.setGrantOption(true);

  //solr privilege
  MSentryGMPrivilege solrPrivilege = new MSentryGMPrivilege();
  solrPrivilege.setComponentName("solr");
  solrPrivilege.setServiceName("solr.server1");
  solrPrivilege.setAuthorizables(Arrays.asList(new Collection("c1")));
  solrPrivilege.setAction("query");
  solrPrivilege.setGrantOption(true);

  PersistenceManager pm = null;
  //create role
  pm = openTransaction();
  pm.makePersistent(new MSentryRole(roleName, System.currentTimeMillis()));
  commitTransaction(pm);

  //grant hivePrivilege and solrPrivilege to role
  pm = openTransaction();
  MSentryRole role = getMSentryRole(pm, roleName);
  hivePrivilege.appendRole(role);
  solrPrivilege.appendRole(role);
  pm.makePersistent(hivePrivilege);
  pm.makePersistent(solrPrivilege);
  commitTransaction(pm);

  //check
  pm = openTransaction();
  role = getMSentryRole(pm, roleName);
  pm.retrieve(role);
  assertEquals(1, role.getPrivileges().size());
  assertEquals(1, role.getGmPrivileges().size());
  commitTransaction(pm);

  //remove all privileges
  pm = openTransaction();
  role = getMSentryRole(pm, roleName);
  role.removeGMPrivileges();
  role.removePrivileges();
  pm.makePersistent(role);
  commitTransaction(pm);

  //check
  pm = openTransaction();
  role = getMSentryRole(pm, roleName);
  pm.retrieve(role);
  assertEquals(0, role.getPrivileges().size());
  assertEquals(0, role.getGmPrivileges().size());
  commitTransaction(pm);

  //delete role
  pm = openTransaction();
  role = getMSentryRole(pm, roleName);
  pm.deletePersistent(role);
  commitTransaction(pm);

  //check
  pm = openTransaction();
  role = getMSentryRole(pm, roleName);
  assertTrue(role == null);
  commitTransaction(pm);
}