Example #1
0
  public static void iterate(
      Query q, long maxElements, int batchSize, Cursor startCursor, Callback callback) {

    batchSize = (int) Math.min(Math.min(maxElements, batchSize), 1000);

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery pq = ds.prepare(q);

    QueryResultList<Entity> list = null;
    if (startCursor == null) {
      list = pq.asQueryResultList(withLimit(batchSize));
    } else {
      list = pq.asQueryResultList(withLimit(batchSize).startCursor(startCursor));
    }

    long totalElements = 0;

    Cursor cursor = list.getCursor();

    while (totalElements < maxElements && list.size() > 0) {
      for (Entity entity : list) {
        totalElements++;
        try {
          callback.withEntity(
              entity,
              DatastoreServiceFactory.getDatastoreService(),
              list.getCursor(),
              totalElements);
        } catch (Exception e) {
          System.err.println(e.getMessage());
          e.printStackTrace();
          break;
        }
        if (totalElements >= maxElements) break;
      }

      if (totalElements >= maxElements) break;

      // wait before fetching new data
      try {
        Thread.sleep(WAIT);
      } catch (InterruptedException e) {
        System.err.println(e.getMessage());
      }

      list =
          pq.asQueryResultList(
              withLimit((int) Math.min(batchSize, maxElements - totalElements))
                  .startCursor(cursor));
      cursor = list.getCursor();
    }
  }
  @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);
    }
  }
  /**
   * 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 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;
  }
  /**
   * 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;
  }
  /**
   * 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;
  }
Example #7
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");
  }
  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!");
  }
Example #9
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>");
  }
 @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;
 }
 @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;
 }
  @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();
  }
Example #13
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;
  }
Example #14
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();
     }
   }
 }
  @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");
  }
Example #16
0
  /**
   * Returns the Account key associated with the specified authorization key.
   *
   * @param pm reference to the persistence manager
   * @param authorizationKey authorization key to return the account key for
   * @return the Account key associated with the specified authorization key; or <code>null</code>
   *     if the authorization key is invalid
   */
  public static Key getAccountKeyByAuthKey(
      final PersistenceManager pm, final String authorizationKey) {
    final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey;
    final String accountKeyString = (String) memcacheService.get(memcacheKey);
    if (accountKeyString != null) return KeyFactory.stringToKey(accountKeyString);

    final Query q = new Query(Account.class.getSimpleName());
    q.setFilter(new FilterPredicate("authorizationKey", FilterOperator.EQUAL, authorizationKey));
    q.setKeysOnly();
    final List<Entity> entityList =
        DatastoreServiceFactory.getDatastoreService()
            .prepare(q)
            .asList(FetchOptions.Builder.withDefaults());
    if (entityList.isEmpty()) return null;

    final Key accountKey = entityList.get(0).getKey();
    try {
      memcacheService.put(memcacheKey, KeyFactory.keyToString(accountKey));
    } catch (final MemcacheServiceException mse) {
      LOGGER.log(Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse);
      // Ignore memcache errors, do not prevent serving user request
    }

    return accountKey;
  }
  @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
  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;
  }
  @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;
  }
 /**
  * Constructor.
  *
  * @param serviceOrNull a DatastoreService to use. If left null, the constructor fetch its own
  *     service
  * @param partition determines what &quot;partition&quot; to store the data in. Different stores
  *     must use different partitions, or unspecified behavior will occur.
  */
 public EntityBasedPersistence(DatastoreService serviceOrNull, String partition) {
   Preconditions.checkNotNull(partition);
   if (serviceOrNull == null) {
     serviceOrNull = DatastoreServiceFactory.getDatastoreService();
   }
   this.service = serviceOrNull;
   this.kind = PREFIX + partition;
 }
 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;
 }
Example #22
0
  @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();
    }
  }
/**
 * Clase ActivateAccount - Activa una cuenta recién registrada
 *
 * @author nachomv
 */
public class ActivateAccount extends HttpServlet {

  private static final long serialVersionUID = 1L;
  private static final Logger LOG = Logger.getLogger(AccountServiceImpl.class.getName());
  private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  /** Busca en la base de datos la cuenta y la activa - */
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
      String activateID = req.getParameter("activateID");
      resp.setContentType("text/plain");

      Transaction txn = datastore.beginTransaction();

      Query q = new Query("Account");
      q.addFilter("tempRId", Query.FilterOperator.EQUAL, activateID);
      q.addFilter("isActivated", Query.FilterOperator.EQUAL, false);
      List<Entity> pq = datastore.prepare(q).asList(withLimit(1));
      if (pq.isEmpty()) {
        String dire = "http://mentoriasetsit.appspot.com?action=errorActivation";
        resp.sendRedirect(dire);

      } else {
        Date dateOfCreation = (Date) pq.get(0).getProperty("dateCreate");
        Date actualDate = new Date();
        // La activación expira a los dos días
        if ((actualDate.getTime() - dateOfCreation.getTime()) > 48 * 60 * 60 * 1000) {
          String dire = "http://mentoriasetsit.appspot.com?action=activationOutOfDate";
          resp.sendRedirect(dire);
        }

        pq.get(0).setProperty("isActivated", true);
        datastore.put(pq.get(0));
        txn.commit();

        String name = (String) pq.get(0).getProperty("name");
        String surname = (String) pq.get(0).getProperty("surname");
        String userName = (String) pq.get(0).getProperty("userName");
        String answer =
            "Hola "
                + name
                + " "
                + surname
                + " tu cuenta ha sido activada y tu username es: "
                + userName;
        resp.getWriter().println(answer);

        String dire = "http://mentoriasetsit.appspot.com?action=activate";
        resp.sendRedirect(dire);
      }
    } catch (Exception e) {
      LOG.warning("Exception in ActivateAccount: " + e.getMessage());
      e.printStackTrace();
    }
  }
}
 public Mixin() {
   datastore = DatastoreServiceFactory.getDatastoreService();
   range =
       new ThreadLocal<Iterator<Key>>() {
         @Override
         protected Iterator<Key> initialValue() {
           return datastore.allocateIds("qi4j", 100).iterator();
         }
       };
 }
Example #25
0
  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;
  }
Example #26
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);
  }
Example #27
0
  @Override
  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Query q = new Query("Member").addSort("name", SortDirection.DESCENDING);
    List<Entity> ents = ds.prepare(q).asList(FetchOptions.Builder.withLimit(10));

    if (ents.size() < 1) { // 若無紀錄,則先
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    UserPermissionsBean userPermissionsBean =
        (UserPermissionsBean) req.getAttribute(AuthRequestAttribute.USER_PERMISSIONS.getName());

    if (userPermissionsBean.getViewSessions() && userPermissionsBean.getViewSessionPermissions()) {

      if (userPermissionsBean.getChangeSessionPermissions()) {
        long sessionPermissionsCode = 0;
        if (req.getParameter(HtmlVariable.VIEW_SESSIONS.getName()) != null)
          sessionPermissionsCode =
              sessionPermissionsCode + SessionPermissions.VIEW_SESSIONS.getCode();
        if (req.getParameter(HtmlVariable.DISCONNECT_SESSIONS.getName()) != null)
          sessionPermissionsCode =
              sessionPermissionsCode + SessionPermissions.DISCONNECT_SESSIONS.getCode();
        if (req.getParameter(HtmlVariable.VIEW_SESSION_PERMISSIONS.getName()) != null)
          sessionPermissionsCode =
              sessionPermissionsCode + SessionPermissions.VIEW_SESSION_PERMISSIONS.getCode();
        if (req.getParameter(HtmlVariable.CHANGE_SESSION_PERMISSIONS.getName()) != null)
          sessionPermissionsCode =
              sessionPermissionsCode + SessionPermissions.CHANGE_SESSION_PERMISSIONS.getCode();

        Error error = Error.NONE;
        UserBean userBean = (UserBean) req.getAttribute(AuthRequestAttribute.USER.getName());
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
        User user = UserFactory.getByKey(datastore, txn, userBean.getKey());
        UserPermissions userPermissions = null;
        if (user == null) error = Error.NON_EXISTENT_USER;
        else if ((userPermissions =
                PermissionsFactory.getUserPermissionsByUserId(datastore, txn, user.getUserId()))
            == null) error = Error.NO_PERMISSIONS;
        else
          try {
            userPermissions.setSessionPermissions(sessionPermissionsCode);
            PermissionsFactory.updateUserPermissions(datastore, txn, userPermissions);
            txn.commit();
            userPermissionsBean = new UserPermissionsBean(userPermissions);
            req.setAttribute(AuthRequestAttribute.USER_PERMISSIONS.getName(), userPermissionsBean);
          } catch (ConcurrentModificationException e) {
            error = Error.ERROR_IN_SESSION_PERMISSIONS;
          }

        if (error != Error.NONE && txn.isActive()) txn.rollback();

        if (userPermissionsBean.getViewSessions()
            && userPermissionsBean.getViewSessionPermissions()) {
          req.setAttribute(HtmlVariable.ERROR.getName(), error.toString());
          req.getRequestDispatcher("/WEB-INF/auth/session-permissions.jsp").forward(req, resp);
        } else resp.sendRedirect("/auth/settings");
      } else req.getRequestDispatcher("/WEB-INF/auth/session-permissions.jsp").forward(req, resp);
    } else resp.sendRedirect("/auth/settings");
  }
 @RequestMapping(value = "/mobileform/{id}", method = RequestMethod.GET)
 public Entity getMobileFormById(@PathVariable String id) throws EntityNotFoundException {
   UserService userService = UserServiceFactory.getUserService();
   User user = userService.getCurrentUser();
   if (user != null) {
     DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
     Key key = KeyFactory.createKey("MobileForm", id);
     Entity result = datastore.get(key);
     return result;
   } else return null;
 }
  /**
   * 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();
  }