Java Code Examples for com.google.appengine.api.memcache.MemcacheService#put()

The following examples show how to use com.google.appengine.api.memcache.MemcacheService#put() . 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: MemcacheBestPracticeServlet.java    From java-docs-samples with Apache License 2.0 6 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
  }

  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 2
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 3
Source File: AppstatsMonitoredServlet.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: TestReport.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the {@code TestReport} with the given build type id ordered by build id in the descendant order.
 *
 * @param buildTypeId      the build type id.
 * @param limit            the optional fetch limit, by default {@link com.google.appengine.tck.site.endpoints.TestReport#DEFAULT_FETCH_LIMIT}.
 * @param reports          the reports entry point
 * @return the matching test reports list or an empty one if none.
 */
@SuppressWarnings("unchecked")
public static List<TestReport> findByBuildTypeIdOrderByBuildIdDesc(String buildTypeId, Optional<Integer> limit, Reports reports) {
    final MemcacheService memcacheService = reports.getMemcacheService();
    List<TestReport> results = (List<TestReport>) memcacheService.get(buildTypeId);
    if (results == null) {
        final Filter buildTypeFilter = new Query.FilterPredicate("buildTypeId", FilterOperator.EQUAL, buildTypeId);
        final Query query = new Query(TEST_REPORT).setFilter(buildTypeFilter).addSort("buildId", DESCENDING);

        final DatastoreService datastoreService = reports.getDatastoreService();
        final PreparedQuery preparedQuery = datastoreService.prepare(query);
        final List<Entity> entities = preparedQuery.asList(FetchOptions.Builder.withLimit(limit.or(DEFAULT_FETCH_LIMIT)));

        results = new ArrayList<>();
        for (Entity oneEntity : entities) {
            final TestReport report = from(oneEntity);
            results.add(report);
        }

        memcacheService.put(buildTypeId, results);
    }
    return results;
}
 
Example 5
Source File: MemcacheTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: MemcacheSyncCacheServlet.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
  }

  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 7
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 8
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 9
Source File: MemcacheMultitenancyTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: MemcacheMultitenancyTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: LocalMemcacheTest.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private void doTest() {
  MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
  assertFalse(ms.contains("yar"));
  ms.put("yar", "foo");
  assertTrue(ms.contains("yar"));
}
 
Example 12
Source File: MultitenancyServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  String namespace;

  PrintWriter out = resp.getWriter();
  out.println("Code Snippets -- not yet fully runnable as an app");

  // [START temp_namespace]
  // Set the namepace temporarily to "abc"
  String oldNamespace = NamespaceManager.get();
  NamespaceManager.set("abc");
  try {
    //      ... perform operation using current namespace ...
  } finally {
    NamespaceManager.set(oldNamespace);
  }
  // [END temp_namespace]

  // [START per_user_namespace]
  if (com.google.appengine.api.NamespaceManager.get() == null) {
    // Assuming there is a logged in user.
    namespace = UserServiceFactory.getUserService().getCurrentUser().getUserId();
    NamespaceManager.set(namespace);
  }
  // [END per_user_namespace]
  String value = "something here";

  // [START ns_memcache]
  // Create a MemcacheService that uses the current namespace by
  // calling NamespaceManager.get() for every access.
  MemcacheService current = MemcacheServiceFactory.getMemcacheService();

  // stores value in namespace "abc"
  oldNamespace = NamespaceManager.get();
  NamespaceManager.set("abc");
  try {
    current.put("key", value); // stores value in namespace “abc”
  } finally {
    NamespaceManager.set(oldNamespace);
  }
  // [END ns_memcache]

  // [START specific_memcache]
  // Create a MemcacheService that uses the namespace "abc".
  MemcacheService explicit = MemcacheServiceFactory.getMemcacheService("abc");
  explicit.put("key", value); // stores value in namespace "abc"
  // [END specific_memcache]

  //[START searchns]
  // Set the current namespace to "aSpace"
  NamespaceManager.set("aSpace");
  // Create a SearchService with the namespace "aSpace"
  SearchService searchService = SearchServiceFactory.getSearchService();
  // Create an IndexSpec
  IndexSpec indexSpec = IndexSpec.newBuilder().setName("myIndex").build();
  // Create an Index with the namespace "aSpace"
  Index index = searchService.getIndex(indexSpec);
  // [END searchns]

  // [START searchns_2]
  // Create a SearchServiceConfig, specifying the namespace "anotherSpace"
  SearchServiceConfig config =
      SearchServiceConfig.newBuilder().setNamespace("anotherSpace").build();
  // Create a SearchService with the namespace "anotherSpace"
  searchService = SearchServiceFactory.getSearchService(config);
  // Create an IndexSpec
  indexSpec = IndexSpec.newBuilder().setName("myindex").build();
  // Create an Index with the namespace "anotherSpace"
  index = searchService.getIndex(indexSpec);
  // [END searchns_2]

}
 
Example 13
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 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);
}