@Test
  public void updateFieldInEntity() throws EntityNotFoundException {

    Entity person = new Entity("Person");
    person.setProperty("firstName", "Ivan");
    person.setProperty("age", 22l);

    Key key = datastore.put(person);

    // Start transaction
    Transaction transaction = datastore.beginTransaction();
    try {

      Entity result = datastore.get(key);
      result.setProperty("age", 30l);

      datastore.put(result);

      transaction.commit();

    } finally {
      if (transaction.isActive()) {
        transaction.rollback();
      }
    }

    Entity result = datastore.get(key);
    assertThat("Ivan", is(equalTo(result.getProperty("firstName"))));
    assertThat(30l, is(equalTo(result.getProperty("age"))));
  }
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String userName = req.getParameter("name");
    String comment = req.getParameter("comment");

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    if (userName != null && comment != null) {
      Entity commentEntity = new Entity("Comment", guestbookKey);
      commentEntity.setProperty("name", userName);
      commentEntity.setProperty("comment", comment);
      datastore.put(commentEntity);
    }

    Query query = new Query("Comment", guestbookKey);
    List<Entity> comments = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
    //	  System.out.println();
    req.setAttribute("comments", comments);

    String url = "/guestBook.jsp";
    ServletContext sc = getServletContext();
    RequestDispatcher rd = sc.getRequestDispatcher(url);
    rd.forward(req, resp);
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] parts = req.getRequestURI().split("/");
    String secret = parts[parts.length - 1];
    String sessionId = parts[parts.length - 2];

    PoorSession session = PoorSessionManager.findSessionById(sessionId);
    if (session == null) {
      resp.sendError(404, "Wrong credentials");
      return;
    }

    Query query = new Query("User").addFilter("external-secret", FilterOperator.EQUAL, secret);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery preparedQuery = datastore.prepare(query);
    Entity entity = preparedQuery.asSingleEntity();

    if (entity == null) {
      resp.sendError(404, "Wrong credentials");
      return;
    }

    String userId = entity.getProperty("email").toString();
    log.info("Logging in user " + userId + "with session " + sessionId + " and secret " + secret);

    PoorSessionManager.loginSession(session, userId);

    // send success signal to the ext login page
    ChannelService channelService = ChannelServiceFactory.getChannelService();
    channelService.sendMessage(new ChannelMessage(sessionId, "success"));

    resp.getWriter().write("Your browser is now logged in");
  }
Beispiel #4
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setCharacterEncoding("UTF-8");

    String keyStr = "PushInfo";
    Key pushKey = KeyFactory.createKey("PushInfo", keyStr);

    String sellerID = req.getParameter("sellerID");
    String ID = req.getParameter("ID");
    String title = req.getParameter("sellerTitle");
    String number = req.getParameter("number");
    Date date = new Date();

    Entity entity = new Entity("PushInfo", pushKey);
    entity.setProperty("sellerID", sellerID);
    entity.setProperty("ID", ID);
    entity.setProperty("title", title);
    entity.setProperty("date", date);
    entity.setProperty("number", number);

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(entity);

    resp.getWriter().print("succeed save pushInfo");
  }
  /**
   * This inserts a new entity into App Engine datastore. If the entity already exists in the
   * datastore, an exception is thrown. It uses HTTP POST method.
   *
   * @param req the entity to be inserted.
   * @return The inserted entity.
   * @throws UnauthorizedException
   */
  @ApiMethod(
      name = "add",
      scopes = {Config.EMAIL_SCOPE},
      clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID})
  public ServiceResponse add(@Named("_name") String _name, ServiceRequest req, User user)
      throws UnauthorizedException {
    if (user == null) {
      throw new UnauthorizedException("UnauthorizedException # User is Null.");
    } else if (req == null || req.getData() == null) {
      return null;
    }

    String userEmail = user.getEmail();
    Date currentDate = new Date();

    DatastoreService dsService = DatastoreServiceFactory.getDatastoreService();
    Entity entity = new Entity(_name);

    entity.setProperty(_createdAt, currentDate);
    entity.setProperty(_createdBy, userEmail);

    entity.setProperty(_updatedAt, currentDate);
    entity.setProperty(_updatedBy, userEmail);

    entity.setProperty(_status, ACTIVE);
    entity.setUnindexedProperty(data, new Text(req.getData()));

    dsService.put(entity);

    ServiceResponse res = new ServiceResponse();
    res.set_id(entity.getKey().getId());

    return res;
  }
Beispiel #6
0
  @ApiMethod(name = "group.save", httpMethod = ApiMethod.HttpMethod.POST)
  public void setSaveGroup(@Named("groupId") Long groupId, Group data) throws IOException {

    // Get the key
    Key rootKey = KeyFactory.createKey("Root", 1);
    Key groupKey = KeyFactory.createKey(rootKey, "Group", groupId);

    // Get or create the group
    Entity group;
    try {
      group = dataStore.get(groupKey);

      //noinspection unchecked
      List<Key> keys = (List<Key>) group.getProperty("forms");
      keys = firstNonNull(keys, Collections.<Key>emptyList());
      // Erase all the previous data
      dataStore.delete(keys);
    } catch (EntityNotFoundException e) {
      logger.fine("Creating new group");
    }

    // Saves the new data
    JsonNode json = NewData.mapper().convertValue(data, JsonNode.class);
    NewData newData = new NewData(dataStore, json);
    newData.run(true);
  }
  /**
   * Persists {@code this} test report to the given {@link
   * com.google.appengine.api.datastore.DatastoreService} and invalidate the cache.
   *
   * @param reports the reports entry point
   */
  public void save(Reports reports) {
    final Entity entity = new Entity(TEST_REPORT, buildTypeId + buildId);
    entity.setProperty("buildTypeId", buildTypeId);
    entity.setProperty("buildId", buildId);
    entity.setProperty("buildDate", buildDate);
    entity.setProperty("buildDuration", buildDuration);
    entity.setProperty("numberOfPassedTests", numberOfPassedTests);
    entity.setProperty("numberOfIgnoredTests", numberOfIgnoredTests);
    entity.setProperty("numberOfFailedTests", numberOfFailedTests);

    final JSONArray jsonArrayFailedTests = new JSONArray();
    for (Test oneFailingTest : failedTests) {
      jsonArrayFailedTests.put(oneFailingTest.asJson());
    }
    entity.setProperty("failedTests", new Text(jsonArrayFailedTests.toString()));

    final JSONArray jsonArrayIgnoredTests = new JSONArray();
    for (Test oneIgnoredTest : ignoredTests) {
      jsonArrayIgnoredTests.put(oneIgnoredTest.asJson());
    }
    entity.setProperty("ignoredTests", new Text(jsonArrayIgnoredTests.toString()));

    final DatastoreService datastoreService = reports.getDatastoreService();
    datastoreService.put(entity);

    final MemcacheService memcacheService = reports.getMemcacheService();
    memcacheService.delete(buildTypeId); // invalidate cache
  }
  @InSequence(10)
  @Test
  @OperateOnDeployment("dep1")
  public void insertIntoBlobstoreOnDep1() throws Exception {
    BlobstoreService service = BlobstoreServiceFactory.getBlobstoreService();

    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile file = fileService.createNewBlobFile("text/plain", "uploadedText.txt");
    FileWriteChannel channel = fileService.openWriteChannel(file, true);
    try {
      channel.write(ByteBuffer.wrap(TEXT.getBytes()));
    } finally {
      channel.closeFinally();
    }

    waitForSync();
    BlobKey blobKey = fileService.getBlobKey(file);
    System.out.println("Blob key: " + blobKey);
    byte[] bytes = service.fetchData(blobKey, 0, Long.MAX_VALUE);

    Assert.assertEquals(TEXT, new String(bytes));

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Entity dsBK = new Entity("blobTestId", 1);
    dsBK.setProperty("blogId", blobKey.getKeyString());
    ds.put(dsBK);
    waitForSync();
  }
  /**
   * This method is used for updating an existing entity. If the entity does not exist in the
   * datastore, an exception is thrown. It uses HTTP PUT method.
   *
   * @param store the entity to be updated.
   * @return The updated entity.
   * @throws UnauthorizedException
   */
  @ApiMethod(
      name = "modify",
      scopes = {Config.EMAIL_SCOPE},
      clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID})
  public ServiceResponse modify(
      @Named("_name") String _name, @Named("_id") Long _id, ServiceRequest req, User user)
      throws UnauthorizedException {
    if (user == null) {
      throw new UnauthorizedException("UnauthorizedException # User is Null.");
    }
    Key key = KeyFactory.createKey(_name, _id);
    Date currentDate = new Date();
    String userEmail = user.getEmail();

    DatastoreService dsService = DatastoreServiceFactory.getDatastoreService();
    ServiceResponse res = new ServiceResponse();
    try {
      Entity entity = dsService.get(key);

      entity.setProperty(_updatedAt, currentDate);
      entity.setProperty(_updatedBy, userEmail);

      entity.setUnindexedProperty(data, new Text(req.getData()));

      dsService.put(entity);

      res.set_id(entity.getKey().getId());
    } catch (com.google.appengine.api.datastore.EntityNotFoundException e) {
      throw new EntityNotFoundException("Object does not exist.");
    }

    return res;
  }
  @Override
  public Datastore.Stats getStats(boolean useCache) {
    if (useCache) {
      try {
        Stats cachedStats = (Stats) STATS_CACHE.get(STATS_CACHE_KEY);
        if (cachedStats != null) {
          return cachedStats;
        }
        logger.info("Stats not in cache, re-computing");
      } catch (InvalidValueException err) {
        logger.log(Level.WARNING, "Could not load data from memcache", err);
      }
    }

    Stats ret = new Stats();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery pq =
        datastore.prepare(new com.google.appengine.api.datastore.Query("__Stat_Kind__"));
    for (Entity kindStat : pq.asIterable()) {
      String kind = (String) kindStat.getProperty("kind_name");
      if ("Channel".equals(kind)) {
        ret.numChannels = ((Long) kindStat.getProperty("count")).intValue();
        ret.timestamp = (Date) kindStat.getProperty("timestamp");
      }
    }

    ret.numUsers = countUsersActiveInLastNDays(datastore, -1);
    ret.oneDayActiveUsers = countUsersActiveInLastNDays(datastore, 1);
    ret.sevenDayActiveUsers = countUsersActiveInLastNDays(datastore, 7);
    ret.thirtyDayActiveUsers = countUsersActiveInLastNDays(datastore, 30);

    STATS_CACHE.put(STATS_CACHE_KEY, ret);

    return ret;
  }
Beispiel #11
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;
  }
Beispiel #12
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    long time_start, time_end;

    DatastoreService datastore = DSF.getDatastoreService();
    Query query = new Query("GeoPos");
    time_start = System.currentTimeMillis();
    PreparedQuery pq = datastore.prepare(query);
    // List<Entity> result = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
    for (Entity geopos : pq.asIterable()) {
      // RTree.insert(new float[] {Float.parseFloat(geopos.getProperty("latitude").toString()),
      // Float.parseFloat(geopos.getProperty("longitude").toString())}, new float[] {0.0f, 0.0f},
      // geopos);
      // resp.getWriter().println(geopos.getProperty("name"));
      // resp.getWriter().println(geopos.getProperty("latitude"));
      // resp.getWriter().println(geopos.getProperty("longitude"));
      RTree.insert(
          new float[] {
            Float.parseFloat(geopos.getProperty("latitude").toString()),
            Float.parseFloat(geopos.getProperty("longitude").toString())
          },
          new float[] {0.0f, 0.0f},
          geopos);
    }
    time_end = System.currentTimeMillis();
    resp.getWriter().println((time_end - time_start));

    // resp.sendRedirect("/rtree.jsp");
  }
Beispiel #13
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>");
  }
  public void create(ContactForm cf) {

    Entity e = Util.contactFormToEntity(cf);
    txn = ds.beginTransaction();
    ds.put(e);
    txn.commit();
  }
 @SuppressWarnings("unchecked")
 @Override
 protected Response findPizzaComponents(String token) {
   if (token == null) {
     return RestResponse.FORBIDDEN();
   }
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
   Key key = KeyFactory.createKey("PizzaFactory", token);
   List<PizzaCrust> components = null;
   try {
     Entity pizzaFactory = datastore.get(key);
     List<EmbeddedEntity> list = (List<EmbeddedEntity>) pizzaFactory.getProperty(type);
     components = new ArrayList<PizzaCrust>();
     if (list != null) {
       for (EmbeddedEntity e : list) {
         PizzaCrust component = PizzaCrustResource.entityToObject(e);
         components.add(component);
       }
     }
     GenericEntity<List<PizzaCrust>> lists = new GenericEntity<List<PizzaCrust>>(components) {};
     response = RestResponse.OK(lists);
   } catch (EntityNotFoundException e) {
     response = RestResponse.NOT_FOUND();
   }
   return response;
 }
Beispiel #16
0
  @Override
  public List<DataObj> getAllDataObj(String deviceId) {
    ArrayList<DataObj> list = new ArrayList<DataObj>();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    // The Query interface assembles a query
    Query q = new Query("DataObj");
    q.addFilter("deviceId", Query.FilterOperator.EQUAL, deviceId);
    // q.addSort("score", SortDirection.DESCENDING);

    // PreparedQuery contains the methods for fetching query results
    // from the datastore
    PreparedQuery pq = datastore.prepare(q);

    for (Entity result : pq.asIterable()) {
      double longCord = (double) result.getProperty("longCord");
      double latCord = (double) result.getProperty("latCord");
      double value = (double) result.getProperty("value");
      long time = (Long) result.getProperty("time");

      list.add(new DataObj(deviceId, longCord, latCord, value, time));
    }

    return list;
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // super.doPost(req, resp);

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Gson gson = new Gson();
    Plan pl = gson.fromJson(req.getParameter("PARAM"), Plan.class);
    Entity plan = new Entity("Plan");

    plan.setProperty("title", pl.getTitle());
    plan.setProperty("description", pl.getDesc());
    plan.setProperty("domain", pl.getDomain());
    plan.setProperty("totalLength", pl.getTotalTime());
    System.out.println(pl.getTotalTime());

    Key planKey = datastore.put(plan);

    List<Exercise> listEx = pl.getExercises();
    Entity exercise;

    for (Exercise ex : listEx) {
      exercise = new Entity("Exercise", planKey);
      exercise.setProperty("title", ex.getTitle());
      exercise.setProperty("description", ex.getDesc());
      String length = ex.getLength();
      String[] splitStr = length.split(":");
      Integer seconds = Integer.parseInt(splitStr[0]) * 60 + Integer.parseInt(splitStr[1]);
      exercise.setProperty("length", seconds);
      exercise.setProperty("row", ex.getRow());
      datastore.put(exercise);
    }
  }
 @PUT
 @Consumes(MediaType.APPLICATION_XML)
 public Response putTaskData(String value) {
   Response res = null;
   // add your code here
   // first check if the Entity exists in the datastore
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
   MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
   syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
   Key entKey = KeyFactory.createKey("TaskData", keyname);
   Date date = new Date();
   try {
     // if it is, signal that we updated the entity
     Entity ts = datastore.get(entKey);
     ts.setProperty("value", value);
     ts.setProperty("date", date);
     datastore.put(ts);
     res = Response.noContent().build();
   } catch (EntityNotFoundException e) {
     // if it is not, create it and
     // signal that we created the entity in the datastore
     Entity taskdata = new Entity("TaskData", keyname);
     taskdata.setProperty("value", value);
     taskdata.setProperty("date", date);
     datastore.put(taskdata);
     res = Response.created(uriInfo.getAbsolutePath()).build();
   }
   TaskData td = new TaskData(keyname, value, date);
   syncCache.put(keyname, td);
   return res;
 }
Beispiel #19
0
 public static String verifyToken(String token) {
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
   Transaction txn = datastore.beginTransaction();
   try {
     Query searchToken = new Query("Token").addFilter("token", FilterOperator.EQUAL, token);
     Entity tokenEntity = datastore.prepare(searchToken).asSingleEntity();
     if (null == tokenEntity) {
       log.warn("Token {} not found - error", token);
       return null;
     }
     log.info("Updating token");
     tokenEntity.setProperty("accessed", new Date().getTime());
     datastore.put(txn, tokenEntity);
     txn.commit();
     log.info("Token OK");
     Entity userEntity = datastore.get((Key) tokenEntity.getProperty("user"));
     return (String) userEntity.getProperty("username");
   } catch (Exception e) {
     log.error("Token error", e);
     return null;
   } finally {
     if (txn.isActive()) {
       txn.rollback();
     }
   }
 }
  @SuppressWarnings("deprecation")
  @GET
  @Path("/list/")
  @Produces("application/json")
  public JSONArray doGet(@QueryParam("ids") String paramIds) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    String[] ids = paramIds.split(",");

    JSONArray jsonMovies = new JSONArray();
    for (String id : ids) {
      Entity movieEntity;
      JSONObject movieToAdd = null;
      Query query = new Query("Movie").addFilter("redboxid", Query.FilterOperator.EQUAL, id);
      List<Entity> movieEntitiesArray =
          datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
      if (movieEntitiesArray.size() == 0) {
        // need to get the movie from the Redbox and then add to db
        movieEntity = getRedboxInfoAndAdd();
      } else {
        movieEntity = movieEntitiesArray.get(0);
      }

      try {
        // todo put the movie properties here
        movieToAdd.put("title", movieEntity.getProperty("title"));
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return jsonMovies;
  }
Beispiel #21
0
  @SuppressWarnings("deprecation")
  public static Entity getEntity(String id) {
    Entity entity = null;
    if (syncCache.contains(id)) {
      entity = (Entity) syncCache.get(id);
    }
    if (entity == null) {
      Query q = new Query("storedString");
      //			q.setFilter(new Query.FilterPredicate("id", Query.FilterOperator.EQUAL, id));
      q.addFilter("id", Query.FilterOperator.EQUAL, id);
      PreparedQuery pq = datastore.prepare(q);
      try {
        entity = pq.asSingleEntity();
      } catch (PreparedQuery.TooManyResultsException e) {
        Iterator<Entity> iter = pq.asIterator();
        while (iter.hasNext()) {
          Entity ent = iter.next();
          if (entity == null) {
            entity = ent;
          } else {
            datastore.delete(ent.getKey());
          }
        }
      }
      if (entity != null) {
        // log.warning("store (because found in datastore) :"+id+" : "+entity.getKey());
        syncCache.put(id, entity);
      }
    }
    // log.warning("return :"+id+" : "+(entity!=null?entity.getKey():""));

    return entity;
  }
  private ServiceResponse updateStatus(String _name, Long _id, String _status, User user)
      throws UnauthorizedException {
    if (user == null) {
      throw new UnauthorizedException("UnauthorizedException # User is Null.");
    }
    Key key = KeyFactory.createKey(_name, _id);
    Date currentDate = new Date();
    String userEmail = user.getEmail();

    DatastoreService dsService = DatastoreServiceFactory.getDatastoreService();
    ServiceResponse res = new ServiceResponse();
    try {
      Entity entity = dsService.get(key);

      entity.setProperty(_updatedAt, currentDate);
      entity.setProperty(_updatedBy, userEmail);

      entity.setProperty(_status, _status);

      dsService.put(entity);

      res.set_id(entity.getKey().getId());

    } catch (com.google.appengine.api.datastore.EntityNotFoundException e) {
      throw new EntityNotFoundException("Object does not exist");
    }
    return res;
  }
Beispiel #23
0
  /**
   * 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;
  }
  private void doRecordAction(JsonValues values, PrintWriter writer) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Gson gson = new Gson();

    // First try to see if we've seen this deck before
    Filter keyFilter =
        new FilterPredicate(
            Entity.KEY_RESERVED_PROPERTY,
            FilterOperator.EQUAL,
            KeyFactory.createKey("Record", gson.toJson(values.deck)));
    Query q = new Query("Record").setFilter(keyFilter);
    PreparedQuery pq = datastore.prepare(q);

    int count = pq.countEntities(FetchOptions.Builder.withDefaults());
    if (count == 0) {
      // First time we've seen this deck
      datastore.put(jsonValuesToEntity(values));
    } else if (count == 1) {
      // We've seen this deck before
      Entity record = pq.asIterable().iterator().next();
      String ratingKey = getRatingKey(values);
      long ratingValue = 1;
      if (record.hasProperty(ratingKey)) {
        ratingValue = (long) record.getProperty(ratingKey) + 1;
      }
      record.setProperty(ratingKey, ratingValue);
      datastore.put(record);
    } else {
      throw new RuntimeException("deck present in store multiple times!");
    }

    writer.println("SUCCESS!");
  }
  /**
   * This method gets the entity having primary key id. It uses HTTP GET method.
   *
   * @param id the primary key of the java bean.
   * @return The entity with primary key id.
   * @throws UnauthorizedException
   */
  @ApiMethod(
      name = "findById",
      scopes = {Config.EMAIL_SCOPE},
      clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID})
  public ServiceResponse findById(@Named("_name") String _name, @Named("_id") Long _id, User user)
      throws UnauthorizedException {
    if (user == null) {
      throw new UnauthorizedException("UnauthorizedException # User is Null.");
    }
    Key key = KeyFactory.createKey(_name, _id);

    DatastoreService dsService = DatastoreServiceFactory.getDatastoreService();
    ServiceResponse res = new ServiceResponse();
    try {
      Entity entity = dsService.get(key);
      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());

    } catch (com.google.appengine.api.datastore.EntityNotFoundException e) {
      throw new EntityNotFoundException("Object does not exist.");
    }

    return res;
  }
 private Entity getEntity(BlobKey blobKey) throws FileNotFoundException {
   DatastoreService datastore = getDatastoreService();
   try {
     return datastore.get(getMetadataKeyForBlobKey(blobKey));
   } catch (EntityNotFoundException ex) {
     throw new FileNotFoundException();
   }
 }
 public Entity getEprSpectrEntityById(String loc, String id) {
   DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
   Query query = new Query(loc + EprSpectr.class.getSimpleName());
   query = query.addFilter(EprSpectr.ID, Query.FilterOperator.EQUAL, id);
   for (Entity anekEntity : datastoreService.prepare(query).asIterable()) {
     return anekEntity;
   }
   return null;
 }
  @SuppressWarnings("unchecked")
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    List<String> errors = new ArrayList<String>();
    PersistenceManager pm = getPersistenceManager();
    String username = req.getParameter("username");
    String password = req.getParameter("password");

    if (username.isEmpty()) {
      errors.add("Username is required.");
    }
    if (password.isEmpty()) {
      errors.add("Password is required.");
    }

    try {
      req.setAttribute("errors", errors);
      List<Admin> us = (List<Admin>) pm.newQuery(Admin.class).execute();

      resp.setContentType("text/html");

      DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
      Query q = new Query("Admin");
      q.setFilter(
          Query.CompositeFilterOperator.and(
              new Query.FilterPredicate("username", Query.FilterOperator.EQUAL, username),
              new Query.FilterPredicate("password", Query.FilterOperator.EQUAL, password)));
      List<Entity> entities = ds.prepare(q).asList(FetchOptions.Builder.withDefaults());
      if (entities.size() == 0) {
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
      }
      // if(entities.size()>0){
      if (us.size() > 0) {
        /*for(int i = 0; i < us.size(); i++){
        	if(us.get(i).getPassword().equals(password) && us.get(i).getUsername().equals(username) && us.get(i).getUser_type() == 0){
        		resp.sendRedirect("/AdminHome");
        	}
        	if(us.get(i).getPassword().equals(password) && us.get(i).getUsername().equals(username) && us.get(i).getUser_type() == 1){
        		resp.sendRedirect("/login.jsp");
        	}
        	if(us.get(i).getPassword().equals(password) && us.get(i).getUsername().equals(username) && us.get(i).getUser_type() == 2){
        		resp.sendRedirect("/login.jsp");
        	}
        }
        //resp.sendRedirect("/login.jsp");
         *
         */
        //	}
      }
    } catch (ServletException e) {
      e.printStackTrace();
    } finally {
      pm.close();
    }
  }
  public static Key save(File f, Owner owner) {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Entity entity = new Entity("File", PathHelper.getStorageKey(f.getPath(), owner));

    entity = ReflectionHelper.setPropertiesToEntity(File.class, f, entity);

    Key k = ds.put(entity);

    return k;
  }
Beispiel #30
0
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key appHubKey = KeyFactory.createKey("AppHub", "apphub");
    Query query = new Query("AppHub", appHubKey).addSort("date", Query.SortDirection.DESCENDING);
    List<Entity> apps = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(25));
    Gson gson = new Gson();
    String json = gson.toJson(apps);
    res.getWriter().println(json);
  }