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

The following examples show how to use javax.jdo.PersistenceManager#getObjectById() . 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: TenantMapper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void updateTenant(String tenantId, String name, String description,RentService rentService) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);

	TenantDataStore tenant = pm.getObjectById(TenantDataStore.class, key);
	tenant.setTenantId(tenantId);
	tenant.setTenantname(name);
	tenant.setDescription(description);
	tenant.setRentService(rentService);
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}
}
 
Example 2
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
private void updateRepProfile( final PersistenceManager pm, final String sha1, final boolean incCommentsCount, final boolean incGgsCount, final boolean incBgsCount ) {
	LOGGER.fine( "sha1: " + sha1 );
	
	final Key         rpKey      = ServerUtils.getSingleKeyQueryResult( RepProfile.class, "sha1", sha1 );
	final RepProfile  repProfile = rpKey == null ? new RepProfile( sha1 ) : pm.getObjectById( RepProfile.class, rpKey );
	
	if ( incCommentsCount )
		repProfile.incrementCommentsCount();
	if ( incGgsCount )
		repProfile.incrementGgsCount();
	if ( incBgsCount )
		repProfile.incrementBgsCount();
	
	if ( repProfile.getKey() == null )
		pm.makePersistent( repProfile );
}
 
Example 3
Source File: OAuthServiceImpl.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves user's oauth information from Datastore.
 * 
 * @return the user profile (or null if not found).
 */
private OAuthUser retrieveUserProfile() {
  PersistenceManager pm = pmf.getPersistenceManager();
  OAuthUser userProfile = null;
  try {
    userProfile = pm.getObjectById(OAuthUser.class, userRecordKey);
  } catch (JDOObjectNotFoundException e) {
    LOG.info("Datastore object not yet initialized with key: " + userRecordKey);
  } finally {
    pm.close();
  }
  return userProfile;
}
 
Example 4
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public void renewTenant(String tenantId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenant = pm.getObjectById(TenantDataStore.class, key);
	
	tenant.setEnable(true);		
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}
}
 
Example 5
Source File: ModifyProjectActionGAETest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
private ProjectDataStore getProjectDS(String projectId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key projectKey = KeyFactory.createKey(ProjectDataStore.class.getSimpleName(), projectId);
	ProjectDataStore projectDS;
	
	try {
		projectDS = pm.getObjectById(ProjectDataStore.class, projectKey);

	} finally {
		pm.close();
	}
	
	return projectDS;
}
 
Example 6
Source File: OAuthServiceImpl.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves user's oauth information from Datastore.
 * 
 * @return the user profile (or null if not found).
 */
private OAuthUser retrieveUserProfile() {
  PersistenceManager pm = pmf.getPersistenceManager();
  OAuthUser userProfile = null;
  try {
    userProfile = pm.getObjectById(OAuthUser.class, userRecordKey);
  } catch (JDOObjectNotFoundException e) {
    LOG.info("Datastore object not yet initialized with key: " + userRecordKey);
  } finally {
    pm.close();
  }
  return userProfile;
}
 
Example 7
Source File: SimpleLoginFormHandler.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
public void renderLogin(String userRecordKey, Wavelet wavelet) {
  // Clear login form.
  wavelet.getRootBlip().all().delete();

  PersistenceManager pm = SingletonPersistenceManagerFactory.get().getPersistenceManager();
  OAuthUser userProfile = null;
  try {
    userProfile = pm.getObjectById(OAuthUser.class, userRecordKey);
  } catch (JDOObjectNotFoundException objectNotFound) {
    LOG.severe("Error fetching object from datastore with key: " + userRecordKey);
  } finally {
    pm.close();
  }
  String url = userProfile.getAuthUrl();

  // Add authentication prompt and insert link to service provider log-in page
  // to wavelet.
  wavelet.getRootBlip().all().delete();
  StringBuilder b = new StringBuilder();
  b.append("\n");
  int startIndex = b.length();
  b.append(LOGIN_LINK_TEXT + "\n\n");
  wavelet.getRootBlip().append(b.toString());

  // Add button to click when authentication is complete.
  wavelet.getRootBlip().append(new FormElement(ElementType.BUTTON, LOGIN_BUTTON_ID,
      LOGIN_BUTTON_CAPTION));

  // Linkify the authorization link.
  wavelet.getRootBlip().range(startIndex, startIndex + LOGIN_LINK_TEXT.length()).annotate(
      LINK_ANNOTATION_KEY, url);
}
 
Example 8
Source File: OAuthHmacThreeLeggedFlow.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public Credential loadCredential(PersistenceManager pm) {
  try {
    return pm.getObjectById(OAuthHmacCredential.class, userId);
  } catch (JDOObjectNotFoundException e) {
    return null;
  }
}
 
Example 9
Source File: JDOTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public A load(String id) {
	final PersistenceManager em = createPersistenceManager();
	em.currentTransaction().begin();
	final A a = (A) em.getObjectById(A.class, id);
	em.currentTransaction().commit();
	em.close();
	return a;
}
 
Example 10
Source File: SimpleLoginFormHandler.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public void renderLogin(String userRecordKey, Wavelet wavelet) {
  // Clear login form.
  wavelet.getRootBlip().all().delete();

  PersistenceManager pm = SingletonPersistenceManagerFactory.get().getPersistenceManager();
  OAuthUser userProfile = null;
  try {
    userProfile = pm.getObjectById(OAuthUser.class, userRecordKey);
  } catch (JDOObjectNotFoundException objectNotFound) {
    LOG.severe("Error fetching object from datastore with key: " + userRecordKey);
  } finally {
    pm.close();
  }
  String url = userProfile.getAuthUrl();

  // Add authentication prompt and insert link to service provider log-in page
  // to wavelet.
  wavelet.getRootBlip().all().delete();
  StringBuilder b = new StringBuilder();
  b.append("\n");
  int startIndex = b.length();
  b.append(LOGIN_LINK_TEXT + "\n\n");
  wavelet.getRootBlip().append(b.toString());

  // Add button to click when authentication is complete.
  wavelet.getRootBlip().append(new FormElement(ElementType.BUTTON, LOGIN_BUTTON_ID,
      LOGIN_BUTTON_CAPTION));

  // Linkify the authorization link.
  wavelet.getRootBlip().range(startIndex, startIndex + LOGIN_LINK_TEXT.length()).annotate(
      LINK_ANNOTATION_KEY, url);
}
 
Example 11
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
private void processFileWithContent( final PersistenceManager pm, final Key fileKey, final String fileTypeString ) throws IOException {
	LOGGER.fine( "File key: " + fileKey + ", file type: " + fileTypeString );
	
	final FileType fileType = FileType.fromString( fileTypeString );
	
	final FileMetaData fmd;
	try {
		fmd =  (FileMetaData) pm.getObjectById( FILE_TYPE_CLASS_MAP.get( fileType ), fileKey );
	} catch ( final JDOObjectNotFoundException jonfe ) {
		LOGGER.warning( "File not found! (Deleted?)" );
		return;
	}
	LOGGER.fine( "sha1: " + fmd.getSha1() );
	if ( fmd.getBlobKey() != null && fmd.getContent() == null ) {
		LOGGER.warning( "This file is already processed!" );
		return;
	}
	if ( fmd.getContent() == null ) {
		LOGGER.warning( "File does not have content!" );
		return;
	}
	
	// Store content in the Blobstore
	final FileService      fileService = FileServiceFactory.getFileService();
	final AppEngineFile    appeFile    = fileService.createNewBlobFile( FILE_TYPE_MIME_TYPE_MAP.get( fileType ), fmd.getSha1() );
	final FileWriteChannel channel     = fileService.openWriteChannel( appeFile, true );
	final ByteBuffer       bb          = ByteBuffer.wrap( fmd.getContent().getBytes() );
	while ( bb.hasRemaining() )
		channel.write( bb );
	channel.closeFinally();
	
	fmd.setBlobKey( fileService.getBlobKey( appeFile ) );
	fmd.setContent( null );
	
	// I do not catch exceptions (so the task will be retried)
}
 
Example 12
Source File: ProjectMapperTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
private ProjectDataStore getProjectDS(String projectId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key projectKey = KeyFactory.createKey(ProjectDataStore.class.getSimpleName(), projectId);
	ProjectDataStore projectDS;
	
	try {
		projectDS = pm.getObjectById(ProjectDataStore.class, projectKey);

	} finally {
		pm.close();
	}
	
	return projectDS;
}
 
Example 13
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
private void updateFileDelStats( 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 );
	if ( fsKey != null ) {
		final FileStat fileStat = pm.getObjectById( FileStat.class, fsKey );
		fileStat.deregisterFile( fileType, fileSize );
		// fileStat must not be deleted: it stores the bandwidth info and the last updated info
	}
}
 
Example 14
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 15
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
private void updateFileStoreStats( final PersistenceManager pm, final Key accountKey, final long paidStorage, final int notificationQuotaLevel, final int inBandwidthIncrement, final int 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 );
	
	if ( fileSize > 0 ) {
		// Check notification storage quota level
		final long quotaLevel = paidStorage * notificationQuotaLevel / 100;
		if ( fileStat.getStorage() < quotaLevel && fileStat.getStorage() + fileSize >= quotaLevel ) {
			ServerUtils.logEvent( accountKey, Type.NOTIFICATION_STORAGE_QUOTA_EXCEEDED );
			
			final Account account = pm.getObjectById( Account.class, accountKey );
			final String body = ServerUtils.concatenateLines(
					"Hi " + account.getAddressedBy() + ",", null,
					"Your Sc2gears Database account exceeded the notification storage quota level!", null,
					"You can check your storage limit here:",
					"https://sciigears.appspot.com/User.html", null,
					"You can purchase additional storage. For price details visit your User page (above) or see:",
					"https://sites.google.com/site/sc2gears/sc2gears-database", null,
					"Regards,",
					"   Andras Belicza" );
			ServerUtils.sendEmail( account, "Account exceeded notification storage quota level", body );
		}
	}
	
	if ( fileSize > 0 )
		fileStat.registerFile( fileType, fileSize );
	fileStat.increaseInbw( fileType, inBandwidthIncrement );
	
	if ( fileStat.getKey() == null )
		pm.makePersistent( fileStat );
}
 
Example 16
Source File: TenantManagerTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
private TenantDataStore getTenantDS(String tenantId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();
	
	Key tenantKey = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenantDS;
	try {
		tenantDS = pm.getObjectById(TenantDataStore.class, tenantKey);

	} finally {
		pm.close();
	}
	
	return tenantDS;
}
 
Example 17
Source File: ScrumRoleMapperTest.java    From ezScrum with GNU General Public License v2.0 4 votes vote down vote up
private Project getProjectFromDS(String projectId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();
	Project project = null; // fix later

	try {
		// 以 projectID 為 key 來取出相對應的 Project data
		Key key = KeyFactory.createKey(
				ProjectDataStore.class.getSimpleName(), projectId);
		ProjectDataStore p = pm.getObjectById(ProjectDataStore.class, key);

		// Project data 從 DB 轉存到 Memory
		project = new Project(p.getName());

		project.setDisplayName(p.getDisplayName());
		project.setComment(p.getComment());
		project.setManager(p.getManager());
		project.setCreateDate(p.getCreateDate());

		// follow ori.
		IProjectDescription aProjDesc = new ProjectDescription(projectId);
		
		aProjDesc.setName(projectId);	// ID
		aProjDesc.setDisplayName(project.getDisplayName());
		aProjDesc.setComment(project.getComment());		
		aProjDesc.setProjectManager(project.getProjectManager());
		aProjDesc.setCreateDate(project.getCreateDate());
		
		project.setProjectDesc(aProjDesc);
		
		// 有關 Scrum Role 權限設定的資料
		List<ScrumRoleDataStore> scrumRolesDS = p.getScrumRoles();
		System.out.println("DB get ScrumRolesDS.size = " + scrumRolesDS.size());
		
		for (int i = 0; i < scrumRolesDS.size(); i++) {				
			ScrumRoleDataStore srDS = scrumRolesDS.get(i);
			ScrumRole sr = new ScrumRole(projectId, srDS.getRoleName());

			// follow ScrumRole.xml order
			sr.setAccessProductBacklog(srDS.getAccessProductBacklog());
			sr.setAccessReleasePlan(srDS.getAccessReleasePlan());
			sr.setAccessSprintPlan(srDS.getAccessSprintPlan());
			sr.setAccessSprintBacklog(srDS.getAccessSprintBacklog());
			sr.setAccessTaskBoard(srDS.getAccessTaskBoard());
			sr.setAccessUnplannedItem(srDS.getAccessUnplannedItem());				
			sr.setAccessRetrospective(srDS.getAccessRetrospective());
			sr.setReadReport(srDS.getReadReport());
			sr.setEditProject(srDS.getEditProject());

			project.setScrumRole(srDS.getRoleName(), sr);
		}

	} finally {
		pm.close();
	}
	
	return project;			

}
 
Example 18
Source File: RoundtripTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
	protected void checkSample(File sample) throws Exception {
		// TODO Auto-generated method stub
		final JAXBContext context = createContext();
		logger.debug("Unmarshalling.");
		final Unmarshaller unmarshaller = context.createUnmarshaller();
		// Unmarshall the document
		final JAXBElement element = (JAXBElement) unmarshaller
				.unmarshal(sample);
		final Object object = element.getValue();
		logger.debug("Opening session.");
		// Open the session, save object into the database
		logger.debug("Saving the object.");
		final PersistenceManager saveManager = createPersistenceManager();
//		saveManager.setDetachAllOnCommit(true);
		final Transaction saveTransaction = saveManager.currentTransaction();
		saveTransaction.setNontransactionalRead(true);
		saveTransaction.begin();
		// final Object merged = saveSession.merge(object);
		// saveSession.replicate(object, ReplicationMode.OVERWRITE);
		// saveSession.get
		// final Serializable id =
		final Object mergedObject = saveManager.makePersistent(object);
		
//		final Object asd = saveManager.detachCopy(object);
		saveTransaction.commit();
//		final Object id = saveManager.getObjectId(mergedObject);
		final Object identity = JDOHelper.getObjectId(object);
		final Object id = identity instanceof SingleFieldIdentity ? ((SingleFieldIdentity) identity).getKeyAsObject() : identity;
		// Close the session
		saveManager.close();

		logger.debug("Opening session.");
		// Open the session, load the object
		final PersistenceManager loadManager = createPersistenceManager();
		final Transaction loadTransaction = loadManager.currentTransaction();
		loadTransaction.setNontransactionalRead(true);
		logger.debug("Loading the object.");
		final Object loadedObject = loadManager.getObjectById(mergedObject.getClass(), id);
		logger.debug("Closing the session.");

		final JAXBElement mergedElement = new JAXBElement(element.getName(),
				element.getDeclaredType(), object);

		final JAXBElement loadedElement = new JAXBElement(element.getName(),
				element.getDeclaredType(), loadedObject);

		logger.debug("Checking the document identity.");

		logger.debug("Source object:\n"
				+ ContextUtils.toString(context, mergedElement));
		logger.debug("Result object:\n"
				+ ContextUtils.toString(context, loadedElement));

		checkObjects(mergedObject, loadedObject);
		loadManager.close();

	}
 
Example 19
Source File: AbstractCallbackServlet.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
@Override
protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  // Parse the token that will be used to look up the flow object
  String completionCode = req.getParameter(completionCodeQueryParam);
  String errorCode = req.getParameter(ERROR_PARAM);

  if ((completionCode == null || "".equals(completionCode))
      && (errorCode == null || "".equals(errorCode))) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    resp.getWriter().print("Must have a query parameter: " + completionCodeQueryParam);
    return;
  } else if (errorCode != null && !"".equals(errorCode)) {
    resp.sendRedirect(deniedRedirectUrl);
    return;
  }

  // Get a key for the logged in user to retrieve the flow
  String userId = getUserId();

  // Get flow from the data store
  PersistenceManager manager = pmf.getPersistenceManager();
  try {
    ThreeLeggedFlow flow = null;
    try {
      flow = manager.getObjectById(flowType, userId);
    } catch (JDOObjectNotFoundException e) {
      LOG.severe("Unable to locate flow by user: " + userId);
      resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
      resp.getWriter().print("Unable to find flow for user: " + userId);
      return;
    }

    flow.setHttpTransport(getHttpTransport());
    flow.setJsonFactory(getJsonFactory());

    // Complete the flow object with the token we got in our query parameters
    Credential c = flow.complete(completionCode);
    manager.makePersistent(c);
    manager.deletePersistent(flow);
    resp.sendRedirect(redirectUrl);
  } finally {
    manager.close();
  }
}
 
Example 20
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< List< ApiCallStatInfo > > getApiCallStatInfoList( final String googleAccount ) {
	LOGGER.fine( "For Google account: " + googleAccount);
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final JQBuilder< ApiCallStat > q = new JQBuilder<>( pm, ApiCallStat.class ).range( 0, 1000 );
		
		final Object[] queryParams;
		if ( googleAccount != null && !googleAccount.isEmpty() ) {
			@SuppressWarnings( "unchecked" )
			final List< Key > apiAccountKey = (List< Key >) pm.newQuery( "select key from " + ApiAccount.class.getName() + " where user==:1" ).execute( new User( googleAccount, "gmail.com" ) );
			if ( apiAccountKey.isEmpty() )
				return new RpcResult< List<ApiCallStatInfo> >( new ArrayList< ApiCallStatInfo >( 0 ) );
			
			q.filter( "ownerKey==p1 && day==p2", "KEY p1, String p2" );
			queryParams = new Object[] { apiAccountKey.get( 0 ), ApiCallStat.DAY_TOTAL };
		}
		else {
			q.filter( "day==p1", "String p1" );
			queryParams = new Object[] { ApiCallStat.DAY_TOTAL };
		}
		
		// To keep track of total
		final ApiCallStatInfo totalApiCallStatInfo = new ApiCallStatInfo();
		totalApiCallStatInfo.setGoogleAccount( "TOTAL: ∑ ALL" );
		
		final List< ApiCallStatInfo > apiCallStatInfoList = new ArrayList< ApiCallStatInfo >();
		// First add the total info record
		apiCallStatInfoList.add( totalApiCallStatInfo );
		
		while ( true ) {
			final List< ApiCallStat > apiCallStatList = q.get( queryParams );
			
			for ( final ApiCallStat apiCallStat : apiCallStatList ) {
				final ApiCallStatInfo info = new ApiCallStatInfo();
				
				final ApiAccount apiAccount  = pm.getObjectById( ApiAccount.class, apiCallStat.getOwnerKey() );
				info.setGoogleAccount   ( apiAccount .getUser().getEmail () );
				info.setPaidOps         ( apiAccount .getPaidOps         () );
				ServerUtils.integrateApiCallStatIntoInfo( info, apiCallStat );
				apiCallStatInfoList.add( info );
				
				// Keep track of totals
				totalApiCallStatInfo.integrateApiCallStat( info );
				totalApiCallStatInfo.setPaidOps( totalApiCallStatInfo.getPaidOps() + info.getPaidOps() );
			}
			
			if ( apiCallStatList.size() < 1000 )
				break;
			
			q.cursor( apiCallStatList );
		}
		
		Collections.sort( apiCallStatInfoList, new Comparator< ApiCallStatInfo >() {
			@Override
			public int compare( final ApiCallStatInfo i1, final ApiCallStatInfo i2 ) {
				return new Long( i2.getUsedOps() ).compareTo( i1.getUsedOps() );
			}
		} );
		
		return new RpcResult< List<ApiCallStatInfo> >( apiCallStatInfoList );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}