com.googlecode.objectify.ObjectifyService Java Examples

The following examples show how to use com.googlecode.objectify.ObjectifyService. 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: ShardedCounterServiceShardIncrementInExistingTXTest.java    From appengine-counter with Apache License 2.0 6 votes vote down vote up
/**
 * Test an increment where there is an active parent transaction, but the counter does not exist (ExistingTx: T;
 * ExistingCounter: F)
 */
@Test
public void decrement_TransactionActive_NoExistingCounter_CounterNotCached()
{
	final String counterName = UUID.randomUUID().toString();

	// Perform another increment in a Work, but abort it before it can commit.
	ObjectifyService.ofy().transactNew(new VoidWork()
	{
		@Override
		public void vrun()
		{
			// Do something else as part of the TX.
			final Key<CounterShardData> counterShardDataKey = CounterShardData.key(
				CounterData.key(UUID.randomUUID().toString()), 0);
			final CounterShardData counterShardData = new CounterShardData(counterShardDataKey);
			ObjectifyService.ofy().save().entity(counterShardData);

			// The actual test.
			singleShardShardedCounterService.increment(counterName, 10L);
		}
	});

	assertThat(this.singleShardShardedCounterService.getCounter(counterName).get().getCount(), is(BigInteger.TEN));
	this.assertCounterShardValue(counterName, 10L);
}
 
Example #2
Source File: SignGuestbookServlet.java    From appengine-java-guestbook-multiphase with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  Greeting greeting;

  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser();  // Find out who the user is.

  String guestbookName = req.getParameter("guestbookName");
  String content = req.getParameter("content");
  if (user != null) {
    greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
  } else {
    greeting = new Greeting(guestbookName, content);
  }

  // Use Objectify to save the greeting and now() is used to make the call synchronously as we
  // will immediately get a new page using redirect and we want the data to be present.
  ObjectifyService.ofy().save().entity(greeting).now();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #3
Source File: SignGuestbookServletTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

  MockitoAnnotations.initMocks(this);
  helper.setUp();
  ds = DatastoreServiceFactory.getDatastoreService();

  //  Set up some fake HTTP requests
  when(mockRequest.getRequestURI()).thenReturn(FAKE_URL);
  when(mockRequest.getParameter("guestbookName")).thenReturn("default2");
  when(mockRequest.getParameter("content")).thenReturn(testPhrase);

  stringWriter = new StringWriter();
  when(mockResponse.getWriter()).thenReturn(new PrintWriter(stringWriter));

  servletUnderTest = new SignGuestbookServlet();

  ObjectifyService.init();
  ObjectifyService.register(Guestbook.class);
  ObjectifyService.register(Greeting.class);

  closeable = ObjectifyService.begin();

  cleanDatastore(ds, "default");
}
 
Example #4
Source File: ExportUtilsTest.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
/**
 * Setup method for the test.
 */
@Before
public void setUp() {

  helper.setUp();
  ObjectifyService.register(TechGalleryUser.class);
  ObjectifyService.register(UserProfile.class);
  ObjectifyService.register(Technology.class);
  ObjectifyService.begin();

  createProfiles();

  ObjectifyService.ofy().save().entity(techGalleryUser).now();
  ObjectifyService.ofy().save().entity(techGalleryUser2).now();
  ObjectifyService.ofy().save().entity(userProfile).now();
  ObjectifyService.ofy().save().entity(userProfile2).now();
}
 
Example #5
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the email with a particular emailId
 * @param emailId id of the email
 */  @Override
public Email getEmail(final long emailId) {
  final Result<Email> result = new Result<Email>();
  // if i try to run this in runjobwithretries it tells me can't run
  // non-ancestor query as a transaction. ObjectifyStorageio has some samples
  // of not using transactions (run with) so i grabbed
  Objectify datastore = ObjectifyService.begin();
  for (EmailData emailData : datastore.query(EmailData.class)
      .filter("id", emailId)/*.order("-datestamp")*/) {
    Email email = new Email(emailData.id, emailData.senderId, emailData.receiverId,
        emailData.title, emailData.body, emailData.datestamp);
    result.t = email;
    break;
  }
  return result.t;
}
 
Example #6
Source File: ShardedCounterServiceShardIncrementTest.java    From appengine-counter with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testIncrement_CounterIsBeingDeleted() throws InterruptedException
{
	// Store this in the Datastore to trigger the exception below...
	CounterData counterData = new CounterData(TEST_COUNTER1, 1);
	counterData.setCounterStatus(CounterStatus.DELETING);
	ObjectifyService.ofy().save().entity(counterData).now();

	try
	{
		shardedCounterService.increment(TEST_COUNTER1, 1);
	}
	catch (IllegalArgumentException e)
	{
		assertEquals("Can't mutate the amount of counter '" + TEST_COUNTER1
			+ "' because it's currently in the DELETING state but must be in in the AVAILABLE state!",
			e.getMessage());
		throw e;
	}
}
 
Example #7
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * check if gallery app is activated
 * @param galleryId the id of the gallery app
 */
@Override
public boolean isGalleryAppActivated(final long galleryId){
  final Result<Boolean> success = new Result<Boolean>();
  try {
    runJobWithRetries(new JobRetryHelper() {
      @Override
      public void run(Objectify datastore) {
          datastore = ObjectifyService.begin();
          success.t = false;
          Key<GalleryAppData> galleryKey = galleryKey(galleryId);
          GalleryAppData appData = datastore.find(galleryKey);
          if(appData != null){
            if(appData.active){
              success.t = true;
            }
          }
       }
    });
  } catch (ObjectifyException e) {
     throw CrashReport.createAndLogError(LOG, null, "error in galleryStorageIo.markReportAsResolved", e);
  }
  return success.t;
}
 
Example #8
Source File: ShardedCounterServiceImpl.java    From appengine-counter with Apache License 2.0 6 votes vote down vote up
/**
 * Reset the indicated CounterShardData 'count' to zero.
 *
 * @return
 */
@Override
public void vrun()
{
	final Key<CounterData> counterDataKey = CounterData.key(counterName);
	final Key<CounterShardData> counterShardDataKey = CounterShardData.key(counterDataKey, shardNumber);
	final CounterShardData counterShardData = ObjectifyService.ofy().load().key(counterShardDataKey).now();
	if (counterShardData == null)
	{
		return;
	}
	else
	{
		counterShardData.setCount(0L);
		counterShardData.setUpdatedDateTime(DateTime.now(DateTimeZone.UTC));
		logger.log(Level.FINE, String.format("Resetting CounterShardData (%s-->ShardNum: %s) to zero!",
			counterShardDataKey, shardNumber, counterShardData.getCount()));
		ObjectifyService.ofy().save().entities(counterShardData).now();
	}
}
 
Example #9
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * mark an report as resolved
 * @param reportId the id of the app
 */
@Override
public boolean markReportAsResolved(final long reportId, final long galleryId){
  final Result<Boolean> success = new Result<Boolean>();
  try {
    runJobWithRetries(new JobRetryHelper() {
      @Override
      public void run(Objectify datastore) {
        datastore = ObjectifyService.begin();
        success.t = false;
        Key<GalleryAppData> galleryKey = galleryKey(galleryId);
        for (GalleryAppReportData reportData : datastore.query(GalleryAppReportData.class).ancestor(galleryKey)) {
          if(reportData.id == reportId){
            reportData.resolved = !reportData.resolved;
            datastore.put(reportData);
            success.t = true;
            break;
          }
        }
       }
    });
   } catch (ObjectifyException e) {
       throw CrashReport.createAndLogError(LOG, null, "error in galleryStorageIo.markReportAsResolved", e);
   }
   return success.t;
}
 
Example #10
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * get the list of children Gallery Apps
 *
 * @param galleryId
 *          id of gallery app
 * @return the list of children Gallery Apps
 */
public List<GalleryApp> remixedTo(final long galleryId) {
  final List<GalleryApp> apps = new ArrayList<GalleryApp>();
  try {
    runJobWithRetries(new JobRetryHelper() {
      @Override
      public void run(Objectify datastore) {
            datastore = ObjectifyService.begin();
            for (GalleryAppAttributionData attributionData:datastore.query(GalleryAppAttributionData.class).filter("attributionId",galleryId)) {
              GalleryAppData galleryAppData = datastore.find(galleryKey(attributionData.galleryId));
              if(!galleryAppData.active) continue;
              GalleryApp gApp = new GalleryApp();
              makeGalleryApp(galleryAppData, gApp);
              apps.add(gApp);
            }
      }
    });
  } catch (ObjectifyException e) {
    throw CrashReport.createAndLogError(LOG, null,
        "error in galleryStorageIo.saveAttribution", e);
  }
  return apps;
}
 
Example #11
Source File: ShardedCounterServiceImpl.java    From appengine-counter with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<CounterOperation> getCounterOperation(String counterName, int shardNumber, UUID counterOperationId)
{
	// Load the counterOperationData
	final Key<CounterData> counterDataKey = CounterData.key(counterName);
	final Key<CounterShardData> counterShardDataKey = CounterShardData.key(counterDataKey, shardNumber);
	final Key<CounterShardOperationData> counterShardOperationDataKey = CounterShardOperationData
		.key(counterShardDataKey, counterOperationId);

	final CounterShardOperationData counterShardOperationData = ObjectifyService.ofy().load()
		.key(counterShardOperationDataKey).now();

	if (counterShardOperationData == null)
	{
		return Optional.absent();
	}
	else
	{
		return Optional.<CounterOperation> of(new CounterOperation.Impl(counterShardOperationData));
	}
}
 
Example #12
Source File: ObjectifyWaxDataStore.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Override
public WaxDataItem update(String sessionId, String itemId, WaxDataItem newItem)
    throws InvalidSessionException, InvalidWaxDataItemException {
  if (!itemId.equals(newItem.getId())) {
    // TODO: I think this is a facility provided by Apiary in the non-Swarm case, but
    // unsure if it's supported in Swarm.
    throw new InvalidWaxDataItemException(newItem.getId());
  }
  WaxSession session = getSession(sessionId);
  for (int i = 0; i < session.getItems().size(); i++) {
    WaxDataItem item = session.getItems().get(i);
    if (itemId.equals(item.getId())) {
      session.getItems().set(i, newItem);
      ObjectifyService.ofy().save().entities(session).now();
      return newItem;
    }
  }
  return null;
}
 
Example #13
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a wrapped class which contains a list of most downloaded
 * gallery apps and total number of results in database
 * @param start starting index of apps you want
 * @param count number of apps you want
 * @return list of {@link GalleryApp}
 */
@Override
public GalleryAppListResult getMostDownloadedApps(int start, final int count) {
  final List<GalleryApp> apps = new ArrayList<GalleryApp>();
  // If I try to run this in runjobwithretries, it tells me can't run
  // non-ancestor query as a transaction. ObjectifyStorageio has some samples
  // of not using transactions (run with) so I grabbed.

  Objectify datastore = ObjectifyService.begin();
  for (GalleryAppData appData:datastore.query(GalleryAppData.class).order("-numDownloads").filter("active", true).offset(start).limit(count)) {
    GalleryApp gApp = new GalleryApp();
    makeGalleryApp(appData, gApp);
    apps.add(gApp);
  }
  int totalCount = datastore.query(GalleryAppData.class).order("-numDownloads").filter("active", true).count();
  return new GalleryAppListResult(apps, totalCount);
}
 
Example #14
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a wrapped class which contains list of most recently
 * updated galleryApps and total number of results in database
 * @param start starting index of apps you want
 * @param count number of apps you want
 * @return list of {@link GalleryApp}
 */
@Override
public GalleryAppListResult getRecentGalleryApps(int start, final int count) {
  final List<GalleryApp> apps = new ArrayList<GalleryApp>();
  // If I try to run this in runjobwithretries, it tells me can't run
  // non-ancestor query as a transaction. ObjectifyStorageio has some samples
  // of not using transactions (run with) so I grabbed.

  Objectify datastore = ObjectifyService.begin();
  for (GalleryAppData appData:datastore.query(GalleryAppData.class).order("-dateModified").filter("active", true).offset(start).limit(count)) {
    GalleryApp gApp = new GalleryApp();
    makeGalleryApp(appData, gApp);
    apps.add(gApp);
  }
  int totalCount = datastore.query(GalleryAppData.class).order("-dateModified").filter("active", true).count();
  return new GalleryAppListResult(apps, totalCount);
}
 
Example #15
Source File: MoveServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void doPost_notMyTurn_move() throws Exception {
  // Insert a game
  Objectify ofy = ObjectifyService.ofy();
  Game game = new Game(USER_ID, "my-opponent", "         ", false);
  ofy.save().entity(game).now();
  String gameKey = game.getId();

  when(mockRequest.getParameter("gameKey")).thenReturn(gameKey);
  when(mockRequest.getParameter("cell")).thenReturn("1");

  servletUnderTest.doPost(mockRequest, mockResponse);

  verify(mockResponse).sendError(401);
}
 
Example #16
Source File: ShardedCounterServiceShardIncrementInExistingTXTest.java    From appengine-counter with Apache License 2.0 5 votes vote down vote up
/**
 * Test an increment where there is an active transaction, but the counter does not exist (ExistingTx: T;
 * ExistingCounter: T), and then the transaction aborts after the call to increment.
 */
@Test
public void increment_Abort_TransactionActive_ExistingCounter_CounterCached()
{
	final String counterName = UUID.randomUUID().toString();
	singleShardShardedCounterService.increment(counterName, 1L);
	assertThat(this.singleShardShardedCounterService.getCounter(counterName).get().getCount(), is(BigInteger.ONE));
	this.assertCounterShardValue(counterName, 1L);

	try
	{
		// Perform another increment in a Work, but abort it before it can commit.
		ObjectifyService.ofy().transactNew(new VoidWork()
		{
			@Override
			public void vrun()
			{
				// Do something else as part of the TX.
				final Key<CounterShardData> counterShardDataKey = CounterShardData.key(
					CounterData.key(UUID.randomUUID().toString()), 0);
				ObjectifyService.ofy().save().entity(counterShardDataKey);

				// The actual test.
				singleShardShardedCounterService.increment(counterName, 10L);

				throw new RuntimeException("Abort the Transaction!");
			}
		});
		fail();
	}
	catch (Exception e)
	{
		// Eat the Exception.
	}

	assertThat(this.singleShardShardedCounterService.getCounter(counterName).get().getCount(),
		is(BigInteger.valueOf(1L)));
	this.assertCounterShardValue(counterName, 1L);
}
 
Example #17
Source File: MoveServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void doPost_myTurn_move() throws Exception {
  // Insert a game
  Objectify ofy = ObjectifyService.ofy();
  Game game = new Game(USER_ID, "my-opponent", "         ", true);
  ofy.save().entity(game).now();
  String gameKey = game.getId();

  when(mockRequest.getParameter("gameKey")).thenReturn(gameKey);
  when(mockRequest.getParameter("cell")).thenReturn("1");

  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  servletUnderTest.doPost(mockRequest, mockResponse);

  game = ofy.load().type(Game.class).id(gameKey).safe();
  assertThat(game.board).isEqualTo(" X       ");

  verify(mockHttpTransport, times(2))
      .buildRequest(eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$"));
}
 
Example #18
Source File: TicTacToeServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  helper.setUp();
  dbSession = ObjectifyService.begin();

  // Set up a fake HTTP response.
  when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://timbre/"));
  when(mockRequest.getRequestDispatcher("/WEB-INF/view/index.jsp")).thenReturn(requestDispatcher);

  servletUnderTest = new TicTacToeServlet();

  helper.setEnvIsLoggedIn(true);
}
 
Example #19
Source File: ShardedCounterServiceShardIncrementInExistingTXTest.java    From appengine-counter with Apache License 2.0 5 votes vote down vote up
/**
 * Test an increment where there is an active transaction, but the counter does not exist (ExistingTx: T;
 * ExistingCounter: F), and then the transaction aborts after the call to increment.
 */
@Test
public void increment_Abort_TransactionActive_NoExistingCounter_CounterNotCached()
{
	final String counterName = UUID.randomUUID().toString();

	try
	{
		// Perform another increment in a Work, but abort it before it can commit.
		ObjectifyService.ofy().transactNew(new VoidWork()
		{
			@Override
			public void vrun()
			{
				// Do something else as part of the TX.
				final Key<CounterShardData> counterShardDataKey = CounterShardData.key(
					CounterData.key(UUID.randomUUID().toString()), 0);
				ObjectifyService.ofy().save().entity(counterShardDataKey);

				// The actual test.
				singleShardShardedCounterService.increment(counterName, 10L);

				throw new RuntimeException("Abort the Transaction!");
			}
		});
		fail();
	}
	catch (Exception e)
	{
		// Eat the Exception.
	}

	assertThat(this.singleShardShardedCounterService.getCounter(counterName).isPresent(), is(false));
	this.assertCounterShardValue(counterName, null);
}
 
Example #20
Source File: TicTacToeServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void doGet_noGameKey() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  servletUnderTest.doGet(mockRequest, mockResponse);

  // Make sure the game object was created for a new game
  Objectify ofy = ObjectifyService.ofy();
  Game game = ofy.load().type(Game.class).first().safe();
  assertThat(game.userX).isEqualTo(USER_ID);

  verify(mockHttpTransport, times(1))
      .buildRequest(eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$"));
  verify(requestDispatcher).forward(mockRequest, mockResponse);
  verify(mockRequest).setAttribute(eq("token"), anyString());
  verify(mockRequest).setAttribute("game_key", game.id);
  verify(mockRequest).setAttribute("me", USER_ID);
  verify(mockRequest).setAttribute("channel_id", USER_ID + game.id);
  verify(mockRequest).setAttribute(eq("initial_message"), anyString());
  verify(mockRequest).setAttribute(eq("game_link"), anyString());
}
 
Example #21
Source File: DeleteServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  helper.setUp();
  dbSession = ObjectifyService.begin();

  servletUnderTest = new DeleteServlet();

  helper.setEnvIsLoggedIn(true);
  // Make sure there are no firebase requests if we don't expect it
  FirebaseChannel.getInstance().httpTransport = null;
}
 
Example #22
Source File: ObjectifyWaxDataStore.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private WaxSession getSession(String sessionId) throws InvalidSessionException {
  WaxSession session = ObjectifyService.ofy().load().type(WaxSession.class).id(sessionId).now();
  if (session != null) {
    return session;
  }
  throw new InvalidSessionException(sessionId);
}
 
Example #23
Source File: ObjectifyJacksonModuleTest.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() {
    super.setUp();
    helper.setUp();
    closeable = ObjectifyService.begin();
    ObjectifyService.register( Bean.class );
    objectMapper.registerModule( new ObjectifyJacksonModule() );
    ObjectifyService.ofy().save().entity( ObjectifyAbstractTester.BEAN ).now();
}
 
Example #24
Source File: OfyHelper.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * A ServletContextListener initializer.
 * @param event .
 */
public void contextInitialized(ServletContextEvent event) {
  // This will be invoked as part of a warmup request, or the first user request if no warmup
  // request.
  ObjectifyService.init();
  ObjectifyService.register(Guestbook.class);
  ObjectifyService.register(Greeting.class);
}
 
Example #25
Source File: ShareTechnologyTest.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    SystemProperty.applicationVersion.set("test");
    helper.setUp();
    closeable = ObjectifyService.begin();
    currentUser = UserServiceFactory.getUserService().getCurrentUser();
}
 
Example #26
Source File: EndorsementServiceTest.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Setup method for the test.
 */
@Before
public void setUp() {
  helper.setUp();
  ObjectifyService.register(TechGalleryUser.class);
  ObjectifyService.register(Endorsement.class);
  ObjectifyService.begin();
}
 
Example #27
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Returns total number of GalleryApps
 * @return number of GalleryApps
 */
@Override
public Integer getNumGalleryApps() {
  Objectify datastore = ObjectifyService.begin();
  int num = datastore.query(GalleryAppData.class).count();
  return num;
}
 
Example #28
Source File: ShardedCounterServiceDeleteTest.java    From appengine-counter with Apache License 2.0 5 votes vote down vote up
/**
 * After calling {@link ShardedCounterService#delete(String)}, the following code asserts that a task was properly
 * added to a task queue, and then manually deletes the counterShards (simulating what would happen in a real task
 * queue).
 * 
 * @throws InterruptedException
 */
private void assertPostDeleteCallSuccess(String counterName) throws InterruptedException
{
	Counter counter = shardedCounterService.getCounter(counterName).get();
	Assert.assertEquals(CounterStatus.DELETING, counter.getCounterStatus());

	// See here:
	// http://stackoverflow.com/questions/6632809/gae-unit-testing-taskqueue-with-testbed
	// The dev app server is single-threaded, so it can't run tests in the
	// background properly. Thus, we test that the task was added to the
	// queue properly. Then, we manually run the shard-deletion code and
	// assert that it's working properly.

	if (countdownLatch.getCount() == 1)
	{
		this.waitForCountdownLatchThenReset();
	}

	// By this point, the task should be processed in the queue and should
	// not exist...
	this.assertNumTasksInQueue(0);

	this.shardedCounterService.onTaskQueueCounterDeletion(counterName);
	this.assertAllCounterShardsExists(counterName, 0);

	// Don't call shardedCounterService.getCounter(counterName), or it will
	// initialize a new CounterData and the test will fail!
	Key<CounterData> counterDataKey = CounterData.key(counterName);
	CounterData counterData = ObjectifyService.ofy().load().key(counterDataKey).now();
	assertTrue(counterData == null);
}
 
Example #29
Source File: OfyFilterTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@After
public void after() {
  ObjectifyFilter.complete();
  ObjectifyService.setFactory(factory);
  ObjectifyFilter.complete();
  helper.tearDown();
}
 
Example #30
Source File: ObjectifyBenchmarkTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected void doInsert(List<Data> list) {
    long start = System.currentTimeMillis();
    Map<Key<Data>, Data> saved = ObjectifyService.ofy().save().entities(list).now();
    long end = System.currentTimeMillis();

    logDuration(String.format("Save [%d]", saved.size()), start, end);

    Assert.assertEquals(list.size(), saved.size());
}