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

The following examples show how to use javax.jdo.PersistenceManager#close() . 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: 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 2
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public List<TenantDataStore> getTenantList() {
	List<TenantDataStore> list = new ArrayList<TenantDataStore>();
	PersistenceManager pm = PMF.get().getPersistenceManager();
	Extent<TenantDataStore> extent = pm.getExtent(TenantDataStore.class, false);
	Iterator<TenantDataStore> ir = extent.iterator();

	while (ir.hasNext()) {
		TenantDataStore tenants = (TenantDataStore) ir.next();
		list.add(tenants);

	}
	extent.closeAll();
	pm.close();

	return list;
}
 
Example 3
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void ListProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price > 10");
        List<Product> products = (List<Product>) q.execute();
        Iterator<Product> iter = products.iterator();
        while (iter.hasNext()) {
            Product p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example 4
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 5
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public boolean isTenantExist(String tenantId) {
	boolean Exist = false;
	PersistenceManager pm = PMF.get().getPersistenceManager();
	Extent<TenantDataStore> extent = pm.getExtent(TenantDataStore.class, false);
	Iterator<TenantDataStore> ir = extent.iterator();

	while (ir.hasNext()) {
		TenantDataStore tenants = (TenantDataStore) ir.next();
		if (tenants.getTenantId().equalsIgnoreCase(tenantId))
			Exist = true;

	}
	extent.closeAll();
	pm.close();
	return Exist;
}
 
Example 6
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 7
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< String > getAuthorizationKey( final String sharedAccount ) {
	LOGGER.fine( sharedAccount == null ? "" : "Shared account: " + sharedAccount );
	
	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 Account account = ServerUtils.getAccount( pm, sharedAccount, user );
		
		if ( account == null )
			return RpcResult.createNoPermissionErrorResult();
		if ( sharedAccount != null && !account.isPermissionGranted( user, Permission.VIEW_AUTHORIZATION_KEY ) )
			return RpcResult.createNoPermissionErrorResult();
		
		return new RpcResult< String >( account.getAuthorizationKey() );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 8
Source File: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 5 votes vote down vote up
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 9
Source File: GuideToJDO.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void QuerySQL() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        // SQL :
        LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------");
        Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT");
        query.setClass(Product.class);
        List<Product> results = query.executeList();

        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 10
Source File: OAuthServiceImpl.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Stores user-specific oauth token information in Datastore.
 * 
 * @param user profile consisting of user's request token, access token, and
 *        consumer secret.
 */
private void storeUserProfile(OAuthUser user) {
  PersistenceManager pm = pmf.getPersistenceManager();
  try {
    pm.makePersistent(user);
  } finally {
    pm.close();
  }
}
 
Example 11
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 12
Source File: UserStore.java    From two-token-sw with Apache License 2.0 5 votes vote down vote up
/**
 * 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 13
Source File: AndroidRpcImpl.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object[] checkPremiumStatus(AndroidDevice androidDevice) {
	if (premiumDevices.contains(androidDevice.getId())) {
		return new Object[] { true, null, true };
	}
	boolean premium = false;
	String sku = null;
	boolean purchased = false;
	PersistenceManager pm = PMF.get().getPersistenceManager();
	try {
		Query query = pm.newQuery(Coupon.class);
		query.setFilter(":param.contains(email)");
		List<Coupon> result = (List<Coupon>) query.execute(androidDevice.getEmails());
		logger.debug(androidDevice.getEmails() + " : " + result.size() + " coupons");
		for (Coupon coupon : result) {
			logger.debug("coupon : " + coupon);
			if (coupon.getPurchased() || coupon.getDateUpdated().after(releaseDate)) {
				premium = coupon.isPremium();
				sku = coupon.getSku();
				purchased = coupon.getPurchased();
			} else {
				if (ToolString.isNotBlank(coupon.getSku())) {
					sku = coupon.getSku();
				} else {
					logger.warn("cannot use old coupon here");
				}
			}
		}
	} catch (Exception e) {
		logger.error(ToolString.stack2string(e));
	} finally {
		pm.close();
	}
	logger.debug("premium:" + premium + ", sku:" + sku + ", purchased:" + purchased);
	return new Object[] { premium, sku, purchased };
}
 
Example 14
Source File: GuideToJDO.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void QueryJDOQL() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        // Declarative JDOQL :
        LOGGER.log(Level.INFO, "Declarative JDOQL --------------------------------------------------------------");
        Query qDJDOQL = pm.newQuery(Product.class);
        qDJDOQL.setFilter("name == 'Tablet' && price == price_value");
        qDJDOQL.declareParameters("double price_value");
        List<Product> resultsqDJDOQL = qDJDOQL.setParameters(80.0).executeList();

        Iterator<Product> iterDJDOQL = resultsqDJDOQL.iterator();
        while (iterDJDOQL.hasNext()) {
            Product p = iterDJDOQL.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 15
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 16
Source File: AndroidRpcImpl.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public AppInstall ensureInstall(AndroidDevice androidDevice) {
	PersistenceManager pm = PMF.get().getPersistenceManager();
	try {
		AppInstall appInstall;
		Query query = pm.newQuery(AppInstall.class);
		query.setFilter("deviceId == :param");
		List<AppInstall> result = (List<AppInstall>) query.execute(androidDevice.getId());
		if (result.isEmpty()) {
			logger.debug("New install : " + androidDevice);
			String email = androidDevice.getEmails().isEmpty() ? null : androidDevice.getEmails().iterator().next();
			sendEmail(STR.supportEmail, "[FlickrUploader] New install - " + androidDevice.getCountryCode() + " - " + androidDevice.getLanguage() + " - " + androidDevice.getAppVersion() + " - "
					+ email, androidDevice.getEmails() + " - " + androidDevice.getAndroidVersion() + " - " + androidDevice.getAppVersion(), STR.supportEmail);
			appInstall = new AppInstall(androidDevice.getId(), androidDevice, androidDevice.getEmails());
			pm.makePersistent(appInstall);

		} else {
			logger.debug("Updating install : " + androidDevice);
			appInstall = result.get(0);
			appInstall.setAndroidDevice(androidDevice);
		}
		return pm.detachCopy(appInstall);
	} catch (Exception e) {
		logger.error(ToolString.stack2string(e));
	} finally {
		pm.close();
	}
	return null;
}
 
Example 17
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< EntityListResult< MousePrintInfo > > getMousePrintInfoList( final String sharedAccount, final PageInfo pageInfo, final MousePrintFilters filters ) {
	final String filtersString = filters.toString();
	LOGGER.fine( ( sharedAccount == null ? "" : "Shared account: " + sharedAccount + ", " ) + "pageInfo: {" + pageInfo.toString() + "}"
		+ ( filtersString.isEmpty() ? "" :  ", filters: {" + filtersString + "}" ) );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( pageInfo.getLimit() > MAX_PAGE_SIZE ) {
		LOGGER.warning( "Too big limit supplied: " + pageInfo.getLimit() );
		return RpcResult.createErrorResult( "Too big limit supplied: " + pageInfo.getLimit() );
	}
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = ServerUtils.getAccountKey( pm, sharedAccount, user, Permission.VIEW_MOUSE_PRINTS );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final List< Object > paramsList     = new ArrayList< Object >();
		final StringBuilder  filtersBuilder = new StringBuilder( "ownerk==p1" );
		final StringBuilder  paramsBuilder  = new StringBuilder( "KEY p1" );
		
		paramsList.add( accountKey );
		if ( filters.getFromDate() != null ) {
			paramsList.add( filters.getFromDate() );
			filtersBuilder.append( " && end>p" ).append( paramsList.size() );
			paramsBuilder.append( ", DATE p" ).append( paramsList.size() );
		}
		if ( filters.getToDate() != null ) {
			filters.getToDate().setTime( filters.getToDate().getTime() + 24L*60*60*1000 ); // Add one day so replays from this day will be included
			paramsList.add( filters.getToDate() );
			filtersBuilder.append( " && end<p" ).append( paramsList.size() );
			paramsBuilder.append( ", DATE p" ).append( paramsList.size() );
		}
		final List< Smpd > mousePrintList = new JQBuilder<>( pm, Smpd.class ).filter( filtersBuilder.toString(), paramsBuilder.toString() ).desc( "end" ).pageInfo( pageInfo ).get( paramsList.toArray() );
		
		final List< MousePrintInfo > mousePrintInfoList = new ArrayList< MousePrintInfo >( mousePrintList.size() );
		for ( final Smpd mousePrint : mousePrintList ) {
			final MousePrintInfo mousePrintInfo = new MousePrintInfo();
			
			mousePrintInfo.setRecordingStart( mousePrint.getStart () );
			mousePrintInfo.setRecordingEnd  ( mousePrint.getEnd   () );
			mousePrintInfo.setScreenWidth   ( mousePrint.getWidth () );
			mousePrintInfo.setScreenHeight  ( mousePrint.getHeight() );
			mousePrintInfo.setFileSize      ( mousePrint.getSize  () );
			mousePrintInfo.setSamplesCount  ( mousePrint.getCount () );
			mousePrintInfo.setSha1          ( mousePrint.getSha1  () );
			mousePrintInfo.setFileName      ( mousePrint.getFname () );
			
			mousePrintInfoList.add( mousePrintInfo );
		}
		
		return new RpcResult< EntityListResult< MousePrintInfo > >( new EntityListResult< MousePrintInfo >( mousePrintInfoList, JDOCursorHelper.getCursor( mousePrintList ).toWebSafeString() ) );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 18
Source File: InfoServlet.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
/**
 * Returns private data for a replay.<br>
 * Sends back an XML with the requested data.
 * 
 * <p>Example XML response:<br>
    * <blockquote><pre>
 * &lt;?xml version="1.0" encoding="UTF-8"?&gt;
 * &lt;privateData docVersion="1.0"&gt;
 *     &lt;authKeyValid&gt;true&lt;/authKeyValid&gt;
 *     &lt;replayStored&gt;true&lt;/replayStored&gt;
 *     &lt;labels&gt;
 *         &lt;label color="ffffff" bgColor="d4343e" checked="true"&gt;GG&lt;/label&gt;
 *         &lt;label color="ffffff" bgColor="0042ff" checked="false"&gt;Funny&lt;/label&gt;
 *     &lt;/labels&gt;
 *     &lt;comment&gt;Some comment.&lt;/comment&gt;
 * &lt;/privateData&gt;
    * </pre></blockquote></p>
    * 
 * @param authorizationKey authorization key of the user
 */
private static void getPrivateData( final String authorizationKey, final HttpServletRequest request, final HttpServletResponse response ) throws IOException {
	final String sha1 = request.getParameter( PARAM_SHA1 );
	
	LOGGER.fine( "Authorization key: " + authorizationKey + "sha1: " + sha1 );
	
	if ( sha1 == null || sha1.isEmpty() ) {
		LOGGER.warning( "Missing parameters!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing parameters!" );
		return;
	}
	
	PersistenceManager pm = null;
	try {
		pm = PMF.get().getPersistenceManager();
		
		response.setContentType( "text/xml" );
		response.setCharacterEncoding( "UTF-8" );
		// Set no-cache
		setNoCache( response );
		
		// Output contains strings, let's produce XML using a document builder (this will ensure proper encoding of strings)...
		final Document document    = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		final Element  rootElement = document.createElement( "privateData" );
		rootElement.setAttribute( "docVersion", "1.0" );
		document.appendChild( rootElement );
		
		final List< Account > accountList = new JQBuilder<>( pm, Account.class ).filter( "authorizationKey==p1", "String p1" ).get( authorizationKey );
		
		Element element = document.createElement( "authKeyValid" );
		element.setTextContent( Boolean.toString( !accountList.isEmpty() ) );
		rootElement.appendChild( element );
		
		if ( !accountList.isEmpty() ) {
			final Account account = accountList.get( 0 );
			final List< Rep > replayList = new JQBuilder<>( pm, Rep.class ).filter( "ownerk==p1 && sha1==p2", "KEY p1, String p2" ).get( account.getKey(), sha1 );
			
			element = document.createElement( "replayStored" );
			element.setTextContent( Boolean.toString( !replayList.isEmpty() ) );
			rootElement.appendChild( element );
			
			if ( !replayList.isEmpty() ) {
				final Rep            replay = replayList.get( 0 );
				final List< Integer > labels = replay.getLabels();
				
				// Labels
				final Element labelsElement = document.createElement( "labels" );
				final List< String > labelNames = ServerUtils.getLabelNames( account );
				for ( int i = 0; i < labelNames.size(); i++ ) {
					element = document.createElement( "label" );
					element.setTextContent( labelNames.get( i ) );
					element.setAttribute( "checked", Boolean.toString( labels != null && labels.contains( i ) ) );
					element.setAttribute( "color"  , i < Consts.DEFAULT_REPLAY_LABEL_COLORS   .length ? Consts.DEFAULT_REPLAY_LABEL_COLORS   [ i ] : "ffffff" );
					element.setAttribute( "bgColor", i < Consts.DEFAULT_REPLAY_LABEL_BG_COLORS.length ? Consts.DEFAULT_REPLAY_LABEL_BG_COLORS[ i ] : "000000" );
					labelsElement.appendChild( element );
				}
				rootElement.appendChild( labelsElement );
				
				// Comment
				element = document.createElement( "comment" );
				element.setTextContent( replay.getComment() );
				rootElement.appendChild( element );
			}
		}
		
		final Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.transform( new DOMSource( document ), new StreamResult( response.getOutputStream() ) );
		
	} catch ( final TransformerException te ) {
		LOGGER.log( Level.SEVERE, "", te );
		response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error!" );
       } catch ( final ParserConfigurationException pce ) {
		LOGGER.log( Level.SEVERE, "", pce );
		response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error!" );
       } finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 19
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 20
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< List< ApiCallStatInfo > > getApiActivity( final String firstDay, final String lastDay ) {
	LOGGER.fine( "First day: " + firstDay + ", last day: " + lastDay );
	
	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();
		
		// To keep track of total
		final ApiCallStatInfo totalApiCallStatInfo = new ApiCallStatInfo();
		totalApiCallStatInfo.setGoogleAccount( "TOTAL: ∑ ALL" );
		
		final Map< Key, ApiCallStatInfo > apiAccountKeyApiCallStatInfoMap  = new HashMap< Key, ApiCallStatInfo >();
		
		final JQBuilder< ApiCallStat > q = new JQBuilder<>( pm, ApiCallStat.class ).filter( "day>=p1 && day<=p2", "String p1, String p2" ).range( 0, 1000 );
		
		while ( true ) {
			final List< ApiCallStat > apiCallStatList = q.get( firstDay, lastDay );
			
			for ( final ApiCallStat apiCallStat : apiCallStatList ) {
				ApiCallStatInfo apiCallStatInfo = apiAccountKeyApiCallStatInfoMap.get( apiCallStat.getOwnerKey() );
				if ( apiCallStatInfo == null ) {
					apiAccountKeyApiCallStatInfoMap.put( apiCallStat.getOwnerKey(), apiCallStatInfo = new ApiCallStatInfo() );
					final ApiAccount apiAccount = pm.getObjectById( ApiAccount.class, apiCallStat.getOwnerKey() );
					apiCallStatInfo.setGoogleAccount( apiAccount.getUser().getEmail() );
					apiCallStatInfo.setPaidOps      ( apiAccount.getPaidOps        () );
					// Integrate paid Ops into totals, ONCE only per API account
					totalApiCallStatInfo.setPaidOps( totalApiCallStatInfo.getPaidOps() + apiCallStatInfo.getPaidOps() );
				}
				
				ServerUtils.integrateApiCallStatIntoInfo( apiCallStatInfo, apiCallStat );
				
				// Keep track of totals
				ServerUtils.integrateApiCallStatIntoInfo( totalApiCallStatInfo, apiCallStat );
			}
			
			if ( apiCallStatList.size() < 1000 )
				break;
			
			q.cursor( apiCallStatList );
		}
		
		final List< ApiCallStatInfo > apiCallStatInfoList = new ArrayList< ApiCallStatInfo >( apiAccountKeyApiCallStatInfoMap.size() + 1 );
		// First add the total info record (sorting will not move it even if only 1 stat record which will have the same used ops)
		apiCallStatInfoList.add( totalApiCallStatInfo );
		apiCallStatInfoList.addAll( apiAccountKeyApiCallStatInfoMap.values() );
		
		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();
	}
}