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 File: PrivilegeOperatePersistence.java From incubator-sentry with Apache License 2.0 | 6 votes |
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 #2
Source File: DelegateSentryStore.java From incubator-sentry with Apache License 2.0 | 6 votes |
@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 #3
Source File: SentryStore.java From incubator-sentry with Apache License 2.0 | 6 votes |
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 #4
Source File: CachingService.java From sc2gears with Apache License 2.0 | 6 votes |
/** * 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 #5
Source File: SentryStore.java From incubator-sentry with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: PrivilegeOperatePersistence.java From incubator-sentry with Apache License 2.0 | 6 votes |
/** * 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 #7
Source File: PrivilegeOperatePersistence.java From incubator-sentry with Apache License 2.0 | 6 votes |
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 #8
Source File: JDOFactory.java From seldon-server with Apache License 2.0 | 6 votes |
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 #9
Source File: ApiUserServiceImpl.java From sc2gears with Apache License 2.0 | 6 votes |
@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 #10
Source File: DelegateSentryStore.java From incubator-sentry with Apache License 2.0 | 6 votes |
/** * 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 #11
Source File: JdoClusterCountStore.java From seldon-server with Apache License 2.0 | 6 votes |
@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 #12
Source File: TenantMapper.java From ezScrum with GNU General Public License v2.0 | 6 votes |
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 #13
Source File: GuestServiceImpl.java From appengine-gwtguestbook-namespaces-java with Apache License 2.0 | 6 votes |
@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 #14
Source File: SentryStore.java From incubator-sentry with Apache License 2.0 | 6 votes |
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 #15
Source File: TenantManagerTest.java From ezScrum with GNU General Public License v2.0 | 6 votes |
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 #16
Source File: UserStore.java From two-token-sw with Apache License 2.0 | 6 votes |
/** * 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 #17
Source File: JdoUserClusterStore.java From seldon-server with Apache License 2.0 | 6 votes |
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 #18
Source File: SentryStore.java From incubator-sentry with Apache License 2.0 | 6 votes |
@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 #19
Source File: TransactionPeer.java From seldon-server with Apache License 2.0 | 6 votes |
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 #20
Source File: JdoClusterCountStore.java From seldon-server with Apache License 2.0 | 6 votes |
@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 #21
Source File: OpenPersistenceManagerInViewTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testOpenPersistenceManagerInViewInterceptor() throws Exception { PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); PersistenceManager pm = mock(PersistenceManager.class); OpenPersistenceManagerInViewInterceptor interceptor = new OpenPersistenceManagerInViewInterceptor(); interceptor.setPersistenceManagerFactory(pmf); MockServletContext sc = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(sc); given(pmf.getPersistenceManager()).willReturn(pm); interceptor.preHandle(new ServletWebRequest(request)); assertTrue(TransactionSynchronizationManager.hasResource(pmf)); // check that further invocations simply participate interceptor.preHandle(new ServletWebRequest(request)); interceptor.preHandle(new ServletWebRequest(request)); interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); interceptor.preHandle(new ServletWebRequest(request)); interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); interceptor.postHandle(new ServletWebRequest(request), null); assertTrue(TransactionSynchronizationManager.hasResource(pmf)); interceptor.afterCompletion(new ServletWebRequest(request), null); assertFalse(TransactionSynchronizationManager.hasResource(pmf)); }
Example #22
Source File: AndroidRpcImpl.java From flickr-uploader with GNU General Public License v2.0 | 5 votes |
@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 #23
Source File: UserStore.java From two-token-sw with Apache License 2.0 | 5 votes |
/** * Checks if an email is registered in this site. * * @param email the email address to be checked * @return whether the email is registered */ public static boolean isEmailRegistered(String email) { PersistenceManager pm = pmf.getPersistenceManager(); try { UserRecord user = findUserByEmail(pm, email); return user != null; } finally { pm.close(); } }
Example #24
Source File: SentryStore.java From incubator-sentry with Apache License 2.0 | 5 votes |
/** * Import the sentry mapping data. * * @param tSentryMappingData * Include 2 maps to save the mapping data, the following is the example of the data * structure: * for the following mapping data: * group1=role1,role2 * group2=role2,role3 * role1=server=server1->db=db1 * role2=server=server1->db=db1->table=tbl1,server=server1->db=db1->table=tbl2 * role3=server=server1->url=hdfs://localhost/path * * The GroupRolesMap in TSentryMappingData will be saved as: * { * TSentryGroup(group1)={role1, role2}, * TSentryGroup(group2)={role2, role3} * } * The RolePrivilegesMap in TSentryMappingData will be saved as: * { * role1={TSentryPrivilege(server=server1->db=db1)}, * role2={TSentryPrivilege(server=server1->db=db1->table=tbl1), * TSentryPrivilege(server=server1->db=db1->table=tbl2)}, * role3={TSentryPrivilege(server=server1->url=hdfs://localhost/path)} * } * @param isOverwriteForRole * The option for merging or overwriting the existing data during import, true for * overwriting, false for merging */ public void importSentryMetaData(TSentryMappingData tSentryMappingData, boolean isOverwriteForRole) throws Exception { boolean rollbackTransaction = true; PersistenceManager pm = null; // change all role name in lowercase TSentryMappingData mappingData = lowercaseRoleName(tSentryMappingData); try { pm = openTransaction(); Set<String> existRoleNames = getAllRoleNames(pm); // Map<String, Set<TSentryGroup>> importedRoleGroupsMap = covertToRoleNameTGroupsMap(mappingData .getGroupRolesMap()); Set<String> importedRoleNames = importedRoleGroupsMap.keySet(); // if import with overwrite role, drop the duplicated roles in current DB first. if (isOverwriteForRole) { dropDuplicatedRoleForImport(pm, existRoleNames, importedRoleNames); // refresh the existRoleNames for the drop role existRoleNames = getAllRoleNames(pm); } // import the mapping data for [role,privilege], the existRoleNames will be updated importSentryRolePrivilegeMapping(pm, existRoleNames, mappingData.getRolePrivilegesMap()); importSentryGroupRoleMapping(pm, existRoleNames, importedRoleGroupsMap); commitTransaction(pm); rollbackTransaction = false; } finally { if (rollbackTransaction) { rollbackTransaction(pm); } } }
Example #25
Source File: JdoUserClusterStore.java From seldon-server with Apache License 2.0 | 5 votes |
@Override public List<UserCluster> getClusters() { 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_clusters.cluster_id=cluster_group.cluster_id order by user_id asc"); query.setResultClass(UserCluster.class); return (List<UserCluster>) query.execute(); }
Example #26
Source File: ShardedCounter.java From appengine-modules-sample-java with Apache License 2.0 | 5 votes |
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 #27
Source File: GuideToJDO.java From tutorials with MIT License | 5 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) public void QueryJPQL() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); // JPQL : LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------"); Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'"); List results = (List) q.execute(); Iterator<Product> iter = results.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 #28
Source File: ShardedCounter.java From appengine-modules-sample-java with Apache License 2.0 | 5 votes |
public boolean isInDatastore() { boolean counterStored = false; final PersistenceManager pm = PMF.get().getPersistenceManager(); try { if (getThisCounter(pm) != null) { counterStored = true; } } finally { pm.close(); } return counterStored; }
Example #29
Source File: UserStore.java From two-token-sw with Apache License 2.0 | 5 votes |
/** * Returns the user for an email, or null if not found. * * @param userId the id of the user to be checked * @return the user object, or null if not exist. */ public static UserImpl getUserById(long userId) { UserImpl user = null; PersistenceManager pm = pmf.getPersistenceManager(); try { UserRecord record = findUserById(pm, userId); if (record != null) { user = createUserByRecord(record); } } finally { pm.close(); } return user; }
Example #30
Source File: PersistenceManagerFactoryUtils.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Return whether the given JDO PersistenceManager is transactional, that is, * bound to the current thread by Spring's transaction facilities. * @param pm the JDO PersistenceManager to check * @param pmf JDO PersistenceManagerFactory that the PersistenceManager * was created with (can be {@code null}) * @return whether the PersistenceManager is transactional */ public static boolean isPersistenceManagerTransactional( PersistenceManager pm, PersistenceManagerFactory pmf) { if (pmf == null) { return false; } PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf); return (pmHolder != null && pm == pmHolder.getPersistenceManager()); }