Exemplo n.º 1
0
  @Override
  public List<Integer> years() {
    List<Integer> years = new ArrayList<Integer>();

    Query q = new Query(sitemapEntity.getKind());
    q.addSort(sitemapEntity.getCreatedDateProperty(), SortDirection.ASCENDING);
    List<Entity> e = ds.prepare(q).asList(FetchOptions.Builder.withLimit(1));
    int start;
    if (e.size() == 1) {
      start =
          DateUtils.getYear((Date) e.get(0).getProperty(sitemapEntity.getCreatedDateProperty()));
    } else {
      return years;
    }

    q = new Query(sitemapEntity.getKind());
    q.addSort(sitemapEntity.getCreatedDateProperty(), SortDirection.DESCENDING);
    e = ds.prepare(q).asList(FetchOptions.Builder.withLimit(1));

    int end =
        DateUtils.getYear((Date) e.get(0).getProperty(sitemapEntity.getCreatedDateProperty()));

    for (int i = start; i <= end; i++) {
      years.add(i);
    }
    return years;
  }
Exemplo n.º 2
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String source = req.getParameter("source");
    ImagesService imagesService = ImagesServiceFactory.getImagesService();

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    List<Filter> filters = new ArrayList<Filter>();
    Query query = new Query(GAEFeedRepository.FEED_ITEM_KIND);
    filters.add(new Query.FilterPredicate("source", FilterOperator.EQUAL, source));
    filters.add(new Query.FilterPredicate("img1A", FilterOperator.EQUAL, 1));
    filters.add(new Query.FilterPredicate("img2A", FilterOperator.EQUAL, 1));

    query.setFilter(CompositeFilterOperator.and(filters));

    query.addSort("publishedDate", SortDirection.DESCENDING);
    PreparedQuery pq = datastore.prepare(query);
    int pageSize = 30;

    resp.setContentType("text/html");
    resp.getWriter().println(" <ul>");

    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);
    String startCursor = req.getParameter("cursor");

    // If this servlet is passed a cursor parameter, let's use it
    if (startCursor != null) {
      fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
    }

    QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
    for (Entity entity : results) {
      resp.getWriter()
          .println(
              "<li>"
                  + entity.getProperty("imageLink")
                  + " / "
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + " / <img height=40 width=40 src=\""
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + "\" />");
    }

    resp.getWriter().println("</li>  </entity></ul>  ");

    String cursor = results.getCursor().toWebSafeString();

    // Assuming this servlet lives at '/people'
    resp.getWriter()
        .println(
            "<a href=\"/p8admin/ListFeedItems?cursor="
                + cursor
                + "&source="
                + source
                + "\">Next page</a>");
  }
Exemplo n.º 3
0
 public List<Entry<String, Entity>> scan(
     String start, String end, int max, SortDirection direction, boolean keysOnly) {
   Preconditions.checkNotNull(start);
   Preconditions.checkNotNull(end);
   Preconditions.checkArgument(max > -1);
   if (max == 0) {
     return Lists.newArrayList();
   }
   Query query = new Query(kind);
   query.addFilter(
       "__key__", FilterOperator.GREATER_THAN_OR_EQUAL, KeyFactory.createKey(kind, escape(start)));
   query.addFilter("__key__", FilterOperator.LESS_THAN, KeyFactory.createKey(kind, escape(end)));
   query.addSort("__key__", direction);
   if (keysOnly) {
     query.setKeysOnly();
   }
   PreparedQuery preparedQuery = service.prepare(query);
   List<Entry<String, Entity>> result = Lists.newArrayList();
   for (Entity entity : preparedQuery.asIterable(FetchOptions.Builder.withLimit(max))) {
     if (keysOnly) {
       result.add(Maps.immutableEntry(unescape(entity.getKey().getName()), (Entity) null));
     } else {
       result.add(Maps.immutableEntry(unescape(entity.getKey().getName()), entity));
     }
   }
   return result;
 }
Exemplo n.º 4
0
  /**
   * This method lists all the entities inserted in datastore. It uses HTTP GET method and paging
   * support.
   *
   * @return A CollectionResponse class containing the list of all entities persisted and a cursor
   *     to the next page.
   * @throws UnauthorizedException
   */
  @ApiMethod(
      name = "findAll",
      scopes = {Config.EMAIL_SCOPE},
      clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID})
  public CollectionResponse<ServiceResponse> findAll(
      @Named("_name") String _name,
      @Nullable @Named("cursor") String cursorString,
      @Nullable @Named("limit") Integer limit,
      User user)
      throws UnauthorizedException {
    if (user == null) {
      throw new UnauthorizedException("UnauthorizedException # User is Null.");
    }
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    if (limit == null) {
      limit = 10;
    }
    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(limit);
    if (cursorString != null) {
      fetchOptions.startCursor(Cursor.fromWebSafeString(cursorString));
    }
    Query q = new Query(_name);
    q.addSort("_updatedAt", SortDirection.DESCENDING);
    PreparedQuery pq = datastore.prepare(q);
    QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);

    List<ServiceResponse> responses = new ArrayList<ServiceResponse>();
    ServiceResponse res = null;
    for (Entity entity : results) {
      res = new ServiceResponse();
      // TODO add properties from entity to service response
      res.set_id(entity.getKey().getId());

      res.set_createdAt((Date) entity.getProperty(_createdAt));
      res.set_createdBy((String) entity.getProperty(_createdBy));

      res.set_upatedAt((Date) entity.getProperty(_updatedAt));
      res.set_updatedBy((String) entity.getProperty(_updatedBy));

      res.set_status((String) entity.getProperty(_status));

      Text dataText = (Text) entity.getProperty(data);
      res.setData(dataText.getValue());

      responses.add(res);
    }

    cursorString = results.getCursor().toWebSafeString();

    return CollectionResponse.<ServiceResponse>builder()
        .setItems(responses)
        .setNextPageToken(cursorString)
        .build();
  }
Exemplo n.º 5
0
 @Override
 public List<EprSpectrModel> getEprSpectrs(QueryEsrSpectrModel q) {
   ArrayList<EprSpectrModel> vRet = new ArrayList<EprSpectrModel>();
   DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
   Query query = new Query(q.loc + EprSpectrModel.class.getSimpleName());
   // if (q.bDate) {
   if (q.bAsc) {
     query = query.addSort(EprSpectr.DATE, Query.SortDirection.ASCENDING);
   } else {
     query = query.addSort(EprSpectr.DATE, Query.SortDirection.DESCENDING);
   }
   int count = q.skip + 1;
   for (Entity esrSpecEntity :
       datastoreService
           .prepare(query)
           .asIterable(FetchOptions.Builder.withLimit(q.limit).offset(q.skip))) {
     EprSpectr anek = new EprSpectr(esrSpecEntity);
     EprSpectrModel anekModel = anek.getEprSpectrModel();
     // anekModel.num = count++;
     vRet.add(anekModel);
   }
   // }
   return vRet;
 }
Exemplo n.º 6
0
 /** Google issueId:1458158 */
 @Test
 public void testIntFilter() {
   Query q = new Query(kindName);
   Query.Filter filter =
       Query.CompositeFilterOperator.and(
           new FilterPredicate("intData1", Query.FilterOperator.LESS_THAN, 20),
           new FilterPredicate("intData1", Query.FilterOperator.GREATER_THAN, 1),
           new FilterPredicate("intData1", Query.FilterOperator.EQUAL, null));
   q.setFilter(filter);
   q.addSort("intData1", Query.SortDirection.ASCENDING);
   q.setAncestor(rootKey);
   assertEquals(1, service.prepare(q).countEntities(fo));
   List<Entity> elist = service.prepare(q).asList(fo);
   assertEquals(Arrays.asList(1L, 10L, null), elist.get(0).getProperty("intData1"));
 }
Exemplo n.º 7
0
 @Test
 public void testStrFilter() {
   Query q = new Query(kindName);
   q.setAncestor(rootKey);
   Query.Filter filter =
       Query.CompositeFilterOperator.and(
           new FilterPredicate("stringData", Query.FilterOperator.LESS_THAN, "qqq"),
           new FilterPredicate("stringData", Query.FilterOperator.GREATER_THAN, "mmm"));
   q.setFilter(filter);
   q.addSort("stringData", Query.SortDirection.ASCENDING);
   assertEquals(2, service.prepare(q).countEntities(fo));
   List<Entity> elist = service.prepare(q).asList(fo);
   assertEquals(Arrays.asList("abc", "xyz", "mno"), elist.get(0).getProperty("stringData"));
   assertEquals(Arrays.asList("ppp", "iii", "ddd"), elist.get(1).getProperty("stringData"));
 }
  /** Make a new Query object that is exactly like the old. Too bad Query isn't Cloneable. */
  protected com.google.appengine.api.datastore.Query cloneRawQuery(
      com.google.appengine.api.datastore.Query orig) {
    com.google.appengine.api.datastore.Query copy =
        new com.google.appengine.api.datastore.Query(orig.getKind(), orig.getAncestor());

    for (FilterPredicate filter : orig.getFilterPredicates())
      copy.addFilter(filter.getPropertyName(), filter.getOperator(), filter.getValue());

    for (SortPredicate sort : orig.getSortPredicates())
      copy.addSort(sort.getPropertyName(), sort.getDirection());

    // This should be impossible but who knows what might happen in the future
    if (orig.isKeysOnly()) copy.setKeysOnly();

    return copy;
  }
  public List<EventTemplate> getAllEventTemplatesKeys() {
    Query q = new Query("EventTemplate");
    q.addSort("name");
    PreparedQuery pq = ds.prepare(q);

    List<EventTemplate> temps = new ArrayList<EventTemplate>();
    String name = null;
    String id = null;
    for (Entity result : pq.asIterable()) {
      name = (String) result.getProperty("name");
      id = result.getKey().getName();
      EventTemplate et = new EventTemplate(id);
      et.setName(name);
      temps.add(et);
      et = null;
    }
    return temps;
  }
  /**
   * Tests pagination of datastore entities. Verifies forward and backward paging returns entities
   * in the exact same order, even with duplicate values.
   *
   * @throws Exception
   */
  public void test() throws Exception {

    // Initialize some test entities.
    final List<Entity> entities = initializeTestData();

    // Add the entities to the datastore.
    DatastoreServiceFactory.getDatastoreService().put(entities);

    // Create a query to get the people, sorted by their initials.
    Query q = new Query(KIND);
    q.addSort(PROPERTY_NAME, SortDirection.ASCENDING);

    // This is to guarantee the order of duplicate initials.  This is not
    // necessary if you are not concerned with the order of the duplicates.
    q.addSort(KEY, SortDirection.ASCENDING);

    // Fetch with a page size of 30 people.
    final FetchOptions options = FetchOptions.Builder.withDefaults();
    options.limit(30);

    // Get first page.
    final Page page1 = getPage(q, options);
    System.out.println("Page 1");
    System.out.println(page1);

    // Get the next page by setting the cursor to the "next" cursor
    // from the current page.
    options.startCursor(page1.next);
    final Page page2 = getPage(q, options);
    System.out.println("Page 2");
    System.out.println(page2);

    // Make sure the next page starts after the previous page.
    assertTrue(page1.last().compareTo(page2.first()) < 0);

    // Get the next page by setting the cursor to the "next" cursor
    // from the current page.
    options.startCursor(page2.next);
    final Page page3 = getPage(q, options);
    System.out.println("Page 3");
    System.out.println(page3);

    // Make sure the next page starts after the previous page.
    assertTrue(page1.last().compareTo(page2.first()) < 0);

    // For paging backward, create the same query in the reverse order.
    // Of course, each page will create a new query according to the
    // page direction desired.
    q = new Query(KIND);
    q.addSort(PROPERTY_NAME, SortDirection.DESCENDING);
    q.addSort(KEY, SortDirection.DESCENDING);

    // Get the previous page by setting the cursor to the "previous"
    // cursor from the current page.
    options.startCursor(page3.previous);
    final Page page2a = getPage(q, options);
    System.out.println("Page 2a");

    // As the page will be returned in the reverse order because the
    // query is reversed, reverse the page for comparison with the
    // original.
    final Page reverse2a = page2a.reverse();
    System.out.println(reverse2a);

    // Make sure this page 2 is exactly like the original.
    assertEquals(page2, reverse2a);

    // Get the previous page by setting the cursor to the "previous"
    // cursor from the current page.
    options.startCursor(page2a.next);
    final Page page1a = getPage(q, options);
    System.out.println("Page 1a");

    // As the page will be returned in the reverse order because the
    // query is reversed, reverse the page for comparison with the
    // original.
    final Page reverse1a = page1a.reverse();
    System.out.println(reverse1a);

    // Make sure this page 1 is exactly like the original.
    assertEquals(page1, reverse1a);
  }
Exemplo n.º 11
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int index;

    DatastoreService ds;
    MemcacheService ms;

    Cookie[] cookies;
    boolean insideFlag;

    String delpw;
    String paramOffset;
    String paramSize;
    int offset;
    int size;

    Key postObjGroupKey;
    Query q;
    List<Entity> postObjList;
    PostObj postObj;

    Gson gson;
    List<String> filelinkList;

    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");

    ds = DatastoreServiceFactory.getDatastoreService();
    ms = MemcacheServiceFactory.getMemcacheService();

    insideFlag = false;
    try {
      cookies = req.getCookies();
      if (cookies.length > 0) {
        if (ms.contains(cookies[0].getValue()) == true) {
          insideFlag = true;
        }
      }
    } catch (Exception e) {
      insideFlag = false;
    }

    delpw = req.getParameter("delpw");
    if (delpw != null) {
      if (delpw.equals("") == true) {
        delpw = null;
      }
    }

    paramOffset = req.getParameter("offset");
    if (paramOffset != null) {
      offset = Integer.valueOf(paramOffset);
    } else {
      offset = 0;
    }

    paramSize = req.getParameter("size");
    if (paramSize != null) {
      size = Integer.valueOf(paramSize);
    } else {
      size = 4096;
    }

    postObjGroupKey = KeyFactory.createKey("PostObjGroup", 1L);
    q = new Query("PostObj", postObjGroupKey);
    if (delpw != null) {
      q.addFilter("delpw", FilterOperator.EQUAL, delpw);
      q.addSort("delpw");
    }
    q.addSort("posttime", SortDirection.DESCENDING);
    postObjList = ds.prepare(q).asList(FetchOptions.Builder.withOffset(offset).limit(size));

    postObj = new PostObj();
    filelinkList = new ArrayList<String>();
    for (index = 0; index < postObjList.size(); index++) {
      postObj.getDB(postObjList.get(index));
      if ((postObj.flag.equals("showgallery") == false && insideFlag == true)
          || (postObj.flag.equals("showgallery") == true && insideFlag == false)
          || delpw != null) {
        filelinkList.add(postObj.filelink);
      }
    }

    gson = new Gson();
    resp.getWriter().print(gson.toJson(filelinkList));
  }