Java Code Examples for com.google.appengine.api.memcache.MemcacheServiceFactory#getMemcacheService()

The following examples show how to use com.google.appengine.api.memcache.MemcacheServiceFactory#getMemcacheService() . 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 vote down vote up
@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: MemcacheCommonServiceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    memcache = MemcacheServiceFactory.getMemcacheService();
    memcache.clearAll();

    asyncMemcache = MemcacheServiceFactory.getAsyncMemcacheService();
    asyncMemcache.clearAll();
}
 
Example 3
Source File: FetchMessagesServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
@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 4
Source File: ShardedCounterServiceConstructorTest.java    From appengine-counter with Apache License 2.0 5 votes vote down vote up
@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 5
Source File: MemcacheConcurrentServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@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 6
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
AppEngineDataStore(AppEngineDataStoreFactory dataStoreFactory, String id) {
  super(dataStoreFactory, id);
  memcache =
      dataStoreFactory.disableMemcache ? null : MemcacheServiceFactory.getMemcacheService(id);
  memcacheExpiration = dataStoreFactory.memcacheExpiration;
  dataStoreService = DatastoreServiceFactory.getDatastoreService();
}
 
Example 7
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
@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 8
Source File: ForkTask.java    From yawp with MIT License 5 votes vote down vote up
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 9
Source File: ShardedCounterServiceConstructorTest.java    From appengine-counter with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: AbstractShardedCounterServiceTest.java    From appengine-counter with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: BackendConfigManager.java    From io2014-codelabs with Apache License 2.0 4 votes vote down vote up
/**
 * Default constructor.
 */
public BackendConfigManager() {
  this(DatastoreServiceFactory.getDatastoreService(),
      MemcacheServiceFactory.getMemcacheService());
}
 
Example 12
Source File: MemcacheTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    memcache = MemcacheServiceFactory.getMemcacheService();
    memcache.clearAll();
}
 
Example 13
Source File: Mutex.java    From yawp with MIT License 4 votes vote down vote up
public void release() {
    MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(ns);
    memcache.delete(key);
}
 
Example 14
Source File: SetAnnouncementServlet.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Query for conferences with less than 5 seats left
    Iterable<Conference> iterable = ofy().load().type(Conference.class)
            .filter("seatsAvailable <", 5)
            .filter("seatsAvailable >", 0);

    // Get the names of the nearly sold out conferences
    List<String> conferenceNames = new ArrayList<>(0);
    for (Conference conference : iterable) {
        conferenceNames.add(conference.getName());
    }
    if (conferenceNames.size() > 0) {

        // Build a String that announces the nearly sold-out conferences
        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));

        // Get the Memcache Service
        MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();

        // Put the announcement String in memcache,
        // keyed by Constants.MEMCACHE_ANNOUNCEMENTS_KEY
        String announcementKey = Constants.MEMCACHE_ANNOUNCEMENTS_KEY;
        String announcementText = announcementStringBuilder.toString();

        memcacheService.put(announcementKey, announcementText);
        /**
        memcacheService.put(Constants.MEMCACHE_ANNOUNCEMENTS_KEY,
                announcementStringBuilder.toString());
        **/
    }

    // Set the response status to 204 which means
    // the request was successful but there's no data to send back
    // Browser stays on the same page if the get came from the browser
    response.setStatus(204);
}
 
Example 15
Source File: MyIndex.java    From google-geoEngine with Apache License 2.0 4 votes vote down vote up
public static int buildIndex(String group) throws IOException{
    //Get all fences of group from DataStore.
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key fenceKey = KeyFactory.createKey("Geofence", group);

    Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING);
    List<Entity> fencesFromStore = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

    if (!fencesFromStore.isEmpty()) {
    	//Create STRTree-Index.
        STRtree index = new STRtree();
        //Loop through the fences from DataStore.
        for (Entity fenceFromStore : fencesFromStore) {
            long id = (long) fenceFromStore.getProperty("id");
            Gson gson = new Gson();
            Text vText = (Text) fenceFromStore.getProperty("vertices");
            String vString = vText.getValue();
            double[][] vertices = gson.fromJson(vString, double[][].class);

            //Store coordinates in an array.
            Coordinate[] coordinates = new Coordinate[vertices.length];
            int i = 0;
            for(double[] point : vertices){
                Coordinate coordinate = new Coordinate(point[0],point[1]);
                coordinates[i++] = coordinate;
            }
            //Create polygon from the coordinates.
            GeometryFactory fact = new GeometryFactory();
            LinearRing linear = new GeometryFactory().createLinearRing(coordinates);
            MyPolygon polygon = new MyPolygon(linear, null, fact, id);
            //Add polygon to index.
            index.insert(polygon.getEnvelopeInternal(), polygon);
        }
        //Build the index.
        index.build();
        //Write the index to Memcache.
        MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
        //Last param is expiration date. Set to null to keep it in Memcache forever.
        syncCache.put(group, index, null); 
    }
    return fencesFromStore.size();
}
 
Example 16
Source File: MemcacheStatisticsTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    service = MemcacheServiceFactory.getMemcacheService();
}
 
Example 17
Source File: CloudEndpointsConfigManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 4 votes vote down vote up
public CloudEndpointsConfigManager() {
  this(DatastoreServiceFactory.getDatastoreService(),
      MemcacheServiceFactory.getMemcacheService());
}
 
Example 18
Source File: MemcacheTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    ms = MemcacheServiceFactory.getMemcacheService();
}
 
Example 19
Source File: Reports.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs an instance of {@code Reports}.
 */
public Reports() {
    this.datastoreService = DatastoreServiceFactory.getDatastoreService();
    this.memcacheService = MemcacheServiceFactory.getMemcacheService();
}
 
Example 20
Source File: ShardedCounterServiceImpl.java    From appengine-counter with Apache License 2.0 2 votes vote down vote up
/**
 * Default Constructor for Dependency-Injection that uses {@link MemcacheServiceFactory} to construct the
 * {@link MemcacheService} and {@link CapabilitiesServiceFactory} to construct the {@link CapabilitiesService}.
 * dependency for this service.
 */
public ShardedCounterServiceImpl()
{
	this(MemcacheServiceFactory.getMemcacheService());
}