com.google.appengine.api.memcache.MemcacheServiceFactory Java Examples
The following examples show how to use
com.google.appengine.api.memcache.MemcacheServiceFactory.
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: SetAnnouncementServlet.java From ud859 with GNU General Public License v3.0 | 6 votes |
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Query for conferences with less than 5 seats lef Iterable<Conference> iterable = ofy().load().type(Conference.class) .filter("seatsAvailable <", 5) .filter("seatsAvailable >", 0); List<String> conferenceNames = new ArrayList<>(0); for (Conference conference : iterable) { conferenceNames.add(conference.getName()); } if (conferenceNames.size() > 0) { StringBuilder announcementStringBuilder = new StringBuilder( "Last chance to attend! The following conferences are nearly sold out: "); Joiner joiner = Joiner.on(", ").skipNulls(); announcementStringBuilder.append(joiner.join(conferenceNames)); MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(); memcacheService.put(Constants.MEMCACHE_ANNOUNCEMENTS_KEY, announcementStringBuilder.toString()); } response.setStatus(204); }
Example #2
Source File: AppstatsMonitoredServlet.java From appengine-java-vm-runtime with Apache License 2.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { URLFetchServiceFactory.getURLFetchService() .fetchAsync(new URL("http://www.example.com/asyncWithGet")) .get(); } catch (Exception anythingMightGoWrongHere) { // fall through } URLFetchServiceFactory.getURLFetchService() .fetchAsync(new URL("http://www.example.com/asyncWithoutGet")); MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); String randomKey = "" + Math.random(); String randomValue = "" + Math.random(); memcache.put(randomKey, randomValue); resp.setContentType("text/plain"); resp.getOutputStream().println(randomKey); }
Example #3
Source File: MemcacheTest.java From appengine-tck with Apache License 2.0 | 6 votes |
@Test public void testNamespace() { // memcache.setNamespace() is deprecated. MemcacheService otherMemcache = MemcacheServiceFactory.getMemcacheService("other"); otherMemcache.clearAll(); memcache.clearAll(); String key = createTimeStampKey("testNamespace"); otherMemcache.put(key, "default"); assertNull("This key should not exist in the default namespace.", memcache.get(key)); assertNotNull(otherMemcache.get(key)); String key2 = createTimeStampKey("testNamespace2"); memcache.put(key2, "default2"); assertNull("This key should not exist in the other namespace.", otherMemcache.get(key2)); assertNotNull(memcache.get(key2)); }
Example #4
Source File: MemcacheAsync2Test.java From appengine-tck with Apache License 2.0 | 6 votes |
@Test public void testAsyncWithNamespace() { String namespace = "namespace-123"; AsyncMemcacheService ams = MemcacheServiceFactory.getAsyncMemcacheService(namespace); String key = "some-random-key"; String value = "some-random-value"; waitOnFuture(ams.put(key, value)); // non-namespaced lookup Assert.assertFalse(memcache.contains(key)); MemcacheService ms = MemcacheServiceFactory.getMemcacheService(namespace); Assert.assertEquals(value, ms.get(key)); }
Example #5
Source File: MemcacheBestPracticeServlet.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String path = req.getRequestURI(); if (path.startsWith("/favicon.ico")) { return; // ignore the request for favicon.ico } MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); byte[] whoKey = "who".getBytes(); byte[] countKey = "count".getBytes(); byte[] who = (byte[]) syncCache.get(whoKey); String whoString = who == null ? "nobody" : new String(who); resp.getWriter().print("Previously incremented by " + whoString + "\n"); syncCache.put(whoKey, "Java".getBytes()); Long count = syncCache.increment(countKey, 1L, 0L); resp.getWriter().print("Count incremented by Java = " + count + "\n"); }
Example #6
Source File: ShardedCounterServiceImplTest.java From appengine-counter with Apache License 2.0 | 6 votes |
@Test public void testDecrementShardWork_PreExistingCounter_NegativeAmount() throws Exception { // Make sure there's only 1 shard in the counter so we don't have unpredictable results. final ShardedCounterServiceConfiguration config = new ShardedCounterServiceConfiguration.Builder() .withNumInitialShards(1).build(); impl = new ShardedCounterServiceImpl(MemcacheServiceFactory.getMemcacheService(), config); impl.increment(TEST_COUNTER1, 1); assertThat(impl.getCounter(TEST_COUNTER1).get().getCount(), is(BigInteger.valueOf(1L))); final CounterDataGetCreateContainer counterDataGetCreateContainer = impl.getOrCreateCounterData(TEST_COUNTER1); final CounterData counterData = counterDataGetCreateContainer.getCounterData(); final CounterOperation decrementShardResult = impl.new IncrementShardWork(counterData, UUID.randomUUID(), Optional.of(1), -1, counterDataGetCreateContainer.isNewCounterDataCreated()).run(); assertThat(decrementShardResult.getAppliedAmount(), is(1L)); // The counter indicates a count of 1 still due to cache. assertThat(impl.getCounter(TEST_COUNTER1).get().getCount(), is(BigInteger.valueOf(1L))); MemcacheServiceFactory.getMemcacheService().clearAll(); assertThat(impl.getCounter(TEST_COUNTER1).get().getCount(), is(BigInteger.ZERO)); assertThat(counterDataGetCreateContainer.isNewCounterDataCreated(), is(false)); }
Example #7
Source File: Mutex.java From yawp with MIT License | 6 votes |
public boolean aquire() { MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(ns); long start = System.currentTimeMillis(); while (true) { if (memcache.increment(key, 1L, 0L) == 1L) { return true; } if (System.currentTimeMillis() - start > maxWait) { return false; } try { Thread.sleep(100L); } catch (InterruptedException e) { } } }
Example #8
Source File: JoinTask.java From yawp with MIT License | 5 votes |
private void init() { this.r = yawp().namespace(ns); this.memcache = MemcacheServiceFactory.getMemcacheService(ns); this.indexCacheKey = CacheHelper.createIndexCacheKey(sinkGroupUri); this.lockCacheKey = CacheHelper.createLockCacheKey(sinkGroupUri, index); this.indexHash = CacheHelper.createIndexHash(sinkGroupUri, index); }
Example #9
Source File: FetchMessagesServlet.java From cloud-pubsub-samples-java with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public final void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { // First retrieve messages from the memcache MemcacheService memcacheService = MemcacheServiceFactory .getMemcacheService(); List<String> messages = (List<String>) memcacheService.get(Constants.MESSAGE_CACHE_KEY); if (messages == null) { // If no messages in the memcache, look for the datastore DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); PreparedQuery query = datastore.prepare( new Query("PubsubMessage").addSort("receipt-time", Query.SortDirection.DESCENDING)); messages = new ArrayList<>(); for (Entity entity : query.asIterable( FetchOptions.Builder.withLimit(MAX_COUNT))) { String message = (String) entity.getProperty("message"); messages.add(message); } // Store them to the memcache for future use. memcacheService.put(Constants.MESSAGE_CACHE_KEY, messages); } ObjectMapper mapper = new ObjectMapper(); resp.setContentType("application/json; charset=UTF-8"); mapper.writeValue(resp.getWriter(), messages); resp.getWriter().close(); }
Example #10
Source File: CountServlet.java From appengine-java-vm-runtime with Apache License 2.0 | 5 votes |
private int memcacheCount() { int memcacheValue = (int) MemcacheServiceFactory.getMemcacheService() .increment(KEY, Long.valueOf(1), Long.valueOf(0)) .longValue(); return memcacheValue; }
Example #11
Source File: ShardedCounterServiceConstructorTest.java From appengine-counter with Apache License 2.0 | 5 votes |
@Test(expected = IllegalArgumentException.class) public void testShardedCounterServiceConstructor_ValidMemcache_0Shards() { final ShardedCounterServiceConfiguration.Builder builder = new ShardedCounterServiceConfiguration.Builder(); builder.withNumInitialShards(0); shardedCounterService = new ShardedCounterServiceImpl(MemcacheServiceFactory.getMemcacheService(), builder.build()); }
Example #12
Source File: SessionManagerTest.java From appengine-java-vm-runtime with Apache License 2.0 | 5 votes |
@Override public void setUp() throws Exception { super.setUp(); helper.setUp(); memcache = MemcacheServiceFactory.getMemcacheService(""); datastore = DatastoreServiceFactory.getDatastoreService(); NamespaceManager.set(startNamespace()); manager = new SessionManager(Arrays.asList(new DatastoreSessionStore(), new MemcacheSessionStore())); NamespaceManager.set(testNamespace()); }
Example #13
Source File: ForkTask.java From yawp with MIT License | 5 votes |
private void init() { logger.info(String.format("fork-task - pipe: %s, sinkId: %s", payload.getPipeClazz().getName(), payload.getSinkUri())); this.r = yawp().namespace(payload.getNs()); this.pipe = newPipeInstance(); this.sinkGroupUri = payload.getSinkGroupUri(); this.indexCacheKey = createIndexCacheKey(sinkGroupUri); this.memcache = MemcacheServiceFactory.getMemcacheService(payload.getNs()); }
Example #14
Source File: MemcacheMultitenancyTest.java From appengine-tck with Apache License 2.0 | 5 votes |
@Test public void testMemcacheServiceNotBoundToSpecificNamespaceAlwaysUsesCurrentNamespace() { MemcacheService service = MemcacheServiceFactory.getMemcacheService(); NamespaceManager.set("one"); service.put("key", "value in namespace one"); NamespaceManager.set("two"); service.put("key", "value in namespace two"); NamespaceManager.set("one"); assertEquals("value in namespace one", service.get("key")); NamespaceManager.set("two"); assertEquals("value in namespace two", service.get("key")); }
Example #15
Source File: MemcacheCommonServiceTest.java From appengine-tck with Apache License 2.0 | 5 votes |
@Test /** * Call getNamespace() via BaseMemcacheService interface for method coverage reporting. */ public void testGetNamespace() { assertNull("Default namespace should be null.", ((BaseMemcacheService) memcache).getNamespace()); assertNull("Default namespace should be null.", ((BaseMemcacheService) asyncMemcache).getNamespace()); String cacheName = "My-CacheNamespaceForSpecialCase.09"; MemcacheService namedMemcache = MemcacheServiceFactory.getMemcacheService(cacheName); assertEquals(cacheName, ((BaseMemcacheService) namedMemcache).getNamespace()); }
Example #16
Source File: MemcacheCommonServiceTest.java From appengine-tck with Apache License 2.0 | 5 votes |
@Before public void setUp() { memcache = MemcacheServiceFactory.getMemcacheService(); memcache.clearAll(); asyncMemcache = MemcacheServiceFactory.getAsyncMemcacheService(); asyncMemcache.clearAll(); }
Example #17
Source File: MemcacheMultitenancyTest.java From appengine-tck with Apache License 2.0 | 5 votes |
@Test public void testMemcacheServiceBoundToSpecificNamespaceIgnoresNamespaceManager() { NamespaceManager.set("one"); MemcacheService service = MemcacheServiceFactory.getMemcacheService("two"); service.put("key", "value"); NamespaceManager.set("three"); assertEquals("two", service.getNamespace()); assertTrue(service.contains("key")); assertEquals("value", service.get("key")); }
Example #18
Source File: ConferenceApi.java From ud859 with GNU General Public License v3.0 | 5 votes |
@ApiMethod( name = "getAnnouncement", path = "announcement", httpMethod = HttpMethod.GET ) public Announcement getAnnouncement() { MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(); Object message = memcacheService.get(Constants.MEMCACHE_ANNOUNCEMENTS_KEY); if (message != null) { return new Announcement(message.toString()); } return null; }
Example #19
Source File: AbstractShardedCounterServiceTest.java From appengine-counter with Apache License 2.0 | 5 votes |
/** * Create a new {@link CounterService} with the specified "number of * initial shards" as found in {@code numInitialShards} . * * @param numInitialShards * * @return */ protected ShardedCounterService initialShardedCounterService(int numInitialShards) { ShardedCounterServiceConfiguration config = new ShardedCounterServiceConfiguration.Builder() .withNumInitialShards(numInitialShards).build(); ShardedCounterService service = new ShardedCounterServiceImpl(MemcacheServiceFactory.getMemcacheService(), config); return service; }
Example #20
Source File: AbstractShardedCounterServiceTest.java From appengine-counter with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { // Don't call super.setUp because we initialize slightly differently // here... countdownLatch = new LocalTaskQueueTestConfig.TaskCountDownLatch(1); // See // http://www.ensor.cc/2010/11/unit-testing-named-queues-spring.html // NOTE: THE QUEUE XML PATH RELATIVE TO WEB APP ROOT, More info // below // http://stackoverflow.com/questions/11197058/testing-non-default-app-engine-task-queues final LocalTaskQueueTestConfig localTaskQueueConfig = new LocalTaskQueueTestConfig() .setDisableAutoTaskExecution(false).setQueueXmlPath("src/test/resources/queue.xml") .setTaskExecutionLatch(countdownLatch).setCallbackClass(DeleteShardedCounterDeferredCallback.class); // Use a different queue.xml for testing purposes helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig().setApplyAllHighRepJobPolicy(), new LocalMemcacheServiceTestConfig(), new LocalCapabilitiesServiceTestConfig(), localTaskQueueConfig); helper.setUp(); memcache = MemcacheServiceFactory.getMemcacheService(); capabilitiesService = CapabilitiesServiceFactory.getCapabilitiesService(); // New Objectify 5.1 Way. See https://groups.google.com/forum/#!topic/objectify-appengine/O4FHC_i7EGk this.session = ObjectifyService.begin(); // Enable Joda Translators JodaTimeTranslators.add(ObjectifyService.factory()); ObjectifyService.factory().register(CounterData.class); ObjectifyService.factory().register(CounterShardData.class); ObjectifyService.factory().register(CounterShardOperationData.class); shardedCounterServiceImpl = new ShardedCounterServiceImpl(); this.shardedCounterService = shardedCounterServiceImpl; }
Example #21
Source File: MetadataEntityGroupTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void entityGroupCount_printsCount() throws Exception { StringWriter responseWriter = new StringWriter(); MemcacheService cache = MemcacheServiceFactory.getMemcacheService(); Entity entity1 = new Entity("Simple"); Key key1 = datastore.put(entity1); Key entityGroupKey = Entities.createEntityGroupKey(key1); EntityGroupCount groupCount = new EntityGroupCount(0, 0); groupCount.showEntityGroupCount( datastore, cache, new PrintWriter(responseWriter), entityGroupKey); assertThat(responseWriter.toString()).contains(" entities"); }
Example #22
Source File: MemcacheAsyncCacheServlet.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String path = req.getRequestURI(); if (path.startsWith("/favicon.ico")) { return; // ignore the request for favicon.ico } // [START example] AsyncMemcacheService asyncCache = MemcacheServiceFactory.getAsyncMemcacheService(); asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); String key = "count-async"; byte[] value; long count = 1; Future<Object> futureValue = asyncCache.get(key); // Read from cache. // ... Do other work in parallel to cache retrieval. try { value = (byte[]) futureValue.get(); if (value == null) { value = BigInteger.valueOf(count).toByteArray(); asyncCache.put(key, value); } else { // Increment value count = new BigInteger(value).longValue(); count++; value = BigInteger.valueOf(count).toByteArray(); // Put back in cache asyncCache.put(key, value); } } catch (InterruptedException | ExecutionException e) { throw new ServletException("Error when waiting for future value", e); } // [END example] // Output content resp.setContentType("text/plain"); resp.getWriter().print("Value is " + count + "\n"); }
Example #23
Source File: MemcacheSyncCacheServlet.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String path = req.getRequestURI(); if (path.startsWith("/favicon.ico")) { return; // ignore the request for favicon.ico } MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); String key = "count-sync"; byte[] value; long count = 1; value = (byte[]) syncCache.get(key); if (value == null) { value = BigInteger.valueOf(count).toByteArray(); syncCache.put(key, value); } else { // Increment value count = new BigInteger(value).longValue(); count++; value = BigInteger.valueOf(count).toByteArray(); // Put back in cache syncCache.put(key, value); } // Output content resp.setContentType("text/plain"); resp.getWriter().print("Value is " + count + "\n"); }
Example #24
Source File: MemcacheConcurrentServlet.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String path = req.getRequestURI(); if (path.startsWith("/favicon.ico")) { return; // ignore the request for favicon.ico } String key = "count-concurrent"; // Using the synchronous cache. MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); // Write this value to cache using getIdentifiable and putIfUntouched. for (long delayMs = 1; delayMs < 1000; delayMs *= 2) { IdentifiableValue oldValue = syncCache.getIdentifiable(key); byte[] newValue = oldValue == null ? BigInteger.valueOf(0).toByteArray() : increment((byte[]) oldValue.getValue()); // newValue depends on old value resp.setContentType("text/plain"); resp.getWriter().print("Value is " + new BigInteger(newValue).intValue() + "\n"); if (oldValue == null) { // Key doesn't exist. We can safely put it in cache. syncCache.put(key, newValue); break; } else if (syncCache.putIfUntouched(key, oldValue, newValue)) { // newValue has been successfully put into cache. break; } else { // Some other client changed the value since oldValue was retrieved. // Wait a while before trying again, waiting longer on successive loops. try { Thread.sleep(delayMs); } catch (InterruptedException e) { throw new ServletException("Error when sleeping", e); } } } }
Example #25
Source File: AppEngineDataStoreFactory.java From google-http-java-client with Apache License 2.0 | 5 votes |
AppEngineDataStore(AppEngineDataStoreFactory dataStoreFactory, String id) { super(dataStoreFactory, id); memcache = dataStoreFactory.disableMemcache ? null : MemcacheServiceFactory.getMemcacheService(id); memcacheExpiration = dataStoreFactory.memcacheExpiration; dataStoreService = DatastoreServiceFactory.getDatastoreService(); }
Example #26
Source File: GeoFencingAPI.java From google-geoEngine with Apache License 2.0 | 5 votes |
/** * Endpoint for finding the fences a certain point is in. */@ApiMethod(name = "point", httpMethod = "get", path = "point") public ArrayList < MyFence > queryPoint(@Named("group") String group, @Named("lng") double lng, @Named("lat") double lat) { ArrayList < MyFence > fences = new ArrayList < MyFence > (); //Get the Index from Memcache. MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); GeometryFactory gf = new GeometryFactory(); STRtree index = (STRtree) syncCache.get(group); // read from cache if (index != null) { Coordinate coord = new Coordinate(lng, lat); Point point = gf.createPoint(coord); List < MyPolygon > items = index.query(point.getEnvelopeInternal()); if (!items.isEmpty()) { for (MyPolygon poly: items) { if (poly.contains(point)) { long id = poly.getID(); MyFence newFence = new MyFence(); newFence.setId(id); fences.add(newFence); } } } } else { try { MyIndex.buildIndex(group); } catch (IOException e) { e.printStackTrace(); } } return fences; }
Example #27
Source File: ShardedCounterServiceCounterShardDecrementTest.java From appengine-counter with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { super.setUp(); final MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(); final ShardedCounterServiceConfiguration shardedCounterServiceConfiguration = new ShardedCounterServiceConfiguration.Builder() .build(); shardedCounterService = new ShardedCounterServiceImpl(memcacheService, shardedCounterServiceConfiguration); }
Example #28
Source File: ShardedCounterServiceConstructorTest.java From appengine-counter with Apache License 2.0 | 5 votes |
@Test public void testShardedCounterServiceConstructorFull() { final ShardedCounterServiceConfiguration config = new ShardedCounterServiceConfiguration.Builder() .withDeleteCounterShardQueueName(DELETE_COUNTER_SHARD_QUEUE_NAME).withNumInitialShards(10) .withRelativeUrlPathForDeleteTaskQueue("RELATIVE-URL-PATH-FOR-DELETE-QUEUE").build(); shardedCounterService = new ShardedCounterServiceImpl(MemcacheServiceFactory.getMemcacheService(), config); assertThat(shardedCounterService.getCounter(TEST_COUNTER1).isPresent(), is(false)); }
Example #29
Source File: ShardedCounterServiceConstructorTest.java From appengine-counter with Apache License 2.0 | 5 votes |
@Test public void testShardedCounterServiceConstructor_NoRelativeUrlPath() { final ShardedCounterServiceConfiguration config = new ShardedCounterServiceConfiguration.Builder() .withDeleteCounterShardQueueName(DELETE_COUNTER_SHARD_QUEUE_NAME).build(); shardedCounterService = new ShardedCounterServiceImpl(MemcacheServiceFactory.getMemcacheService(), config); assertThat(shardedCounterService.getCounter(TEST_COUNTER1).isPresent(), is(false)); }
Example #30
Source File: ShardedCounterServiceConstructorTest.java From appengine-counter with Apache License 2.0 | 5 votes |
@Test(expected = RuntimeException.class) public void testShardedCounterServiceConstructor_ValidMemcache_NegativeShards() { final ShardedCounterServiceConfiguration.Builder builder = new ShardedCounterServiceConfiguration.Builder(); builder.withNumInitialShards(-10); shardedCounterService = new ShardedCounterServiceImpl(MemcacheServiceFactory.getMemcacheService(), builder.build()); }