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

The following examples show how to use com.google.appengine.api.memcache.MemcacheService#get() . 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: 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 3
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 4
Source File: GeoFencingAPI.java    From google-geoEngine with Apache License 2.0 5 votes vote down vote up
/**
 * 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 5
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 6
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 7
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 8
Source File: GeoFencingAPI.java    From google-geoEngine with Apache License 2.0 4 votes vote down vote up
/**
 * Endpoint for finding the fences that intersect with a polyline.
 */@ApiMethod(name = "polyline", httpMethod = "post", path = "polyline")
public ArrayList < MyFence > queryPolyLine(@Named("group") String group, MyPolyLine polyline) {
    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) {
        //Create coordinate array.
        double[][] points = polyline.getCoordinates();
        Coordinate[] coordinates = new Coordinate[points.length];
        int i = 0;
        for (double[] point: points) {
            Coordinate coordinate = new Coordinate(point[0], point[1]);
            coordinates[i++] = coordinate;
        }
        //Create polyline.
        GeometryFactory fact = new GeometryFactory();
        LineString linestring = new GeometryFactory().createLineString(coordinates);

        List < MyPolygon > items = index.query(linestring.getEnvelopeInternal());
        if (!items.isEmpty()) {
            for (MyPolygon poly: items) {
                if (linestring.crosses(poly) || poly.contains(linestring)) {
                    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 9
Source File: GeoFencingAPI.java    From google-geoEngine with Apache License 2.0 4 votes vote down vote up
/**
 * Endpoint for finding the fences that intersect with a polygon.
 */@ApiMethod(name = "polygon", httpMethod = "post", path = "polygon")
public ArrayList < MyFence > queryPolygon(@Named("group") String group, MyPolyLine polyline) {
    ArrayList < MyFence > fences = new ArrayList < MyFence > ();

    //Get index from Memcache
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    STRtree index = (STRtree) syncCache.get(group); // read from cache
    if (index != null) {
        //Create coordinate array.
        double[][] points = polyline.getCoordinates();
        Coordinate[] coordinates = new Coordinate[points.length];
        int i = 0;
        for (double[] point: points) {
            Coordinate coordinate = new Coordinate(point[0], point[1]);
            coordinates[i++] = coordinate;
        }
        //Create polygon.
        GeometryFactory fact = new GeometryFactory();
        LinearRing linear = new GeometryFactory().createLinearRing(coordinates);
        Polygon polygon = new Polygon(linear, null, fact);

        List < MyPolygon > items = index.query(polygon.getEnvelopeInternal());
        if (!items.isEmpty()) {
            for (MyPolygon poly: items) {
                if (polygon.contains(poly) || !polygon.disjoint(poly)) {
                    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;
}