Пример #1
0
  /**
   * 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;
  }
Пример #2
0
  /**
   * 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;
  }
Пример #3
0
 @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;
 }
Пример #4
0
  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;
  }
Пример #5
0
  @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"))));
  }
Пример #6
0
  @Test
  public void transactionsOnVariusTypesOfEntities() throws EntityNotFoundException {

    Entity person = new Entity("Person", "tom");
    datastore.put(person);

    // Transaction on root entities
    Transaction transaction = datastore.beginTransaction();

    Entity tom = datastore.get(person.getKey());
    tom.setProperty("age", 40);
    datastore.put(tom);
    transaction.commit();

    // Transaction on child entities
    transaction = datastore.beginTransaction();
    tom = datastore.get(person.getKey());

    // Create a Photo entity that is a child of Person entity named "tom"
    Entity photo = new Entity("Photo", tom.getKey());
    photo.setProperty("photoUrl", "images/photo");
    datastore.put(photo);
    transaction.commit();

    // Transaction on entities in different entity groups
    transaction = datastore.beginTransaction();

    Entity photoNotChild = new Entity("Photo");
    photoNotChild.setProperty("photoUrl", "images/photo");
    datastore.put(photoNotChild);
    transaction.commit();
  }
Пример #7
0
  @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);
  }
Пример #8
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");
  }
 public static void employeeAddress(Employee employee) {
   Entity addressEntity = new Entity("Address", employee.getEmployeeId());
   addressEntity.setProperty("EmployeeId", employee.getEmployeeId());
   addressEntity.setProperty("Email", employee.getEmail());
   addressEntity.setProperty("City", employee.getAddress().getCity());
   addressEntity.setProperty("State", employee.getAddress().getState());
   datastore.put(addressEntity);
 }
  public static void employeeLogin(Employee employee) {
    Entity loginEntity = new Entity("Login", employee.getEmployeeId());
    loginEntity.setProperty("EmployeeId", employee.getEmployeeId());
    loginEntity.setProperty("UserName", employee.getEmail());
    loginEntity.setProperty("Password", employee.getFirstName() + 123);

    datastore.put(loginEntity);
  }
Пример #11
0
 public void saveUser(HttpServletRequest req) {
   Entity e = new Entity("User");
   e.setProperty("firstname", req.getParameter("fName"));
   e.setProperty("lastname", req.getParameter("lName"));
   e.setProperty("mail", req.getParameter("email"));
   e.setProperty("pass", req.getParameter("password"));
   e.setProperty("ph", req.getParameter("phone"));
   ds.put(e);
 }
Пример #12
0
  public static Entity GetEntity(String slideKey, String questionText, int rating) {

    Entity questionEntity = new Entity("Question", KeyFactory.stringToKey(slideKey));
    questionEntity.setProperty("Text", questionText);
    questionEntity.setProperty("Rating", rating);
    questionEntity.setProperty("DatePosted", new Date());

    return questionEntity;
  }
  public static void employeeLeave(Employee employee) {
    final int LOPDays = 0;
    Entity leaveEntity = new Entity("Leave", employee.getEmployeeId());
    leaveEntity.setProperty("EmployeeId", employee.getEmployeeId());
    leaveEntity.setProperty("Email", employee.getEmail());
    leaveEntity.setProperty("LeaveBalance", employee.getLeaveBalance());
    leaveEntity.setProperty("LOPDays", LOPDays);

    datastore.put(leaveEntity);
  }
Пример #14
0
 private static void generateScenery(
     String mapId, int x, int y, int nx, int ny, DatastoreService store) {
   if (x != nx && y != ny && x != y) { // Clear the diagonal line for escape
     Entity obstacle = new Entity(Transport.SCENERY);
     obstacle.setProperty("x", x);
     obstacle.setProperty("y", y);
     obstacle.setProperty("map", mapId);
     store.put(obstacle);
   }
 }
Пример #15
0
  /**
   * 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
  }
  private Entity jsonValuesToEntity(JsonValues values) {
    Gson gson = new Gson();
    Entity record = new Entity("Record", gson.toJson(values.deck));
    for (Expansion expansion : values.expansions) {
      record.setProperty(expansion.name, expansion.present);
    }
    record.setProperty(getRatingKey(values), 1);
    record.setProperty("random", getRandomLong());

    return record;
  }
  @Override
  public void save(Company company) {

    Entity companyEntity = new Entity(CompanyEntity.KIND);
    companyEntity.setProperty(CompanyEntity.NAME, company.getName());
    companyEntity.setProperty(CompanyEntity.ADDRESS, company.getAddress());
    companyEntity.setProperty(CompanyEntity.ACTIVITY, company.getActivity());
    companyEntity.setProperty(CompanyEntity.LOCATION, company.getLocation());
    companyEntity.setProperty(CompanyEntity.EMAIL, company.getEmail());
    service.put(companyEntity);
  }
 /**
  * Set a byte array property to an entity
  *
  * @param entity the entity to add the byte array to
  * @param propertyName name of the property
  * @param bytes the byte array to add to the entity
  */
 public static void setUnindexedProperty(Entity entity, String propertyName, byte[] bytes) {
   if (bytes != null) {
     if (bytes.length <= SHORT_BLOG_MAX_SIZE) {
       ShortBlob blob = new ShortBlob(bytes);
       entity.setProperty(propertyName, blob);
     } else {
       Blob blob = new Blob(bytes);
       entity.setProperty(propertyName, blob);
     }
   }
 }
Пример #19
0
 public static Entity createUser(String email, String necessidade, String token) {
   Entity user = getSingleUser(email);
   if (user == null) {
     user = new Entity(USER);
     user.setProperty(EMAIL, email);
     user.setProperty("necessidade", necessidade);
     user.setProperty("token", token);
     Util.persistEntity(user);
   }
   return user;
 }
Пример #20
0
  @Override
  public void addDataObj(DataObj dataObj) {

    Entity item = new Entity("DataObj");
    item.setProperty("deviceId", dataObj.getDeviceId());
    item.setProperty("longCord", dataObj.getLongCord());
    item.setProperty("latCord", dataObj.getLatCord());
    item.setProperty("value", dataObj.getValue());
    item.setProperty("time", dataObj.getTime());

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(item);
  }
Пример #21
0
 @RequestMapping(
     value = "/coordinates",
     method = RequestMethod.POST,
     consumes = "application/json",
     produces = "text/html")
 public String addCoordinate(
     @RequestBody Coordinate coordinate, ModelMap map, HttpServletRequest request)
     throws URISyntaxException {
   Entity coordinateEntity = new Entity("Coordinate");
   coordinateEntity.setProperty("latitude", coordinate.getLatitude());
   coordinateEntity.setProperty("longitude", coordinate.getLongitude());
   datastore.put(coordinateEntity);
   return getCoordinates(map, request);
 }
  @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);
    }
  }
Пример #23
0
 @Override
 public com.google.appengine.api.datastore.Entity modelToEntity(java.lang.Object model) {
   slim3.demo.model.Blog m = (slim3.demo.model.Blog) model;
   com.google.appengine.api.datastore.Entity entity = null;
   if (m.getKey() != null) {
     entity = new com.google.appengine.api.datastore.Entity(m.getKey());
   } else {
     entity = new com.google.appengine.api.datastore.Entity(kind);
   }
   entity.setProperty("content", m.getContent());
   entity.setProperty("title", m.getTitle());
   entity.setProperty("version", m.getVersion());
   return entity;
 }
  public String newAudioClip(String userId, String title, String audio, String image)
      throws BadRequestException {
    // validate existence of the user
    validateUserExistance(userId); // throws bad request exception of user doesn't exist

    Entity audioClip = new Entity(TuneInConstants.AUDIO_CLIP_TYPE);
    audioClip.setProperty(TuneInConstants.AUDIO_CLIP_TITLE, title);
    audioClip.setProperty(TuneInConstants.AUDIO_CLIP_AUDIO_ID, audio);
    audioClip.setProperty(TuneInConstants.AUDIO_CLIP_IMAGE_ID, image);
    audioClip.setProperty(TuneInConstants.AUDIO_CLIP_OWNER_ID, userId);
    audioClip.setProperty(TuneInConstants.AUDIO_CLIP_DATE, new Date());
    datastore.put(audioClip);
    return KeyFactory.keyToString(audioClip.getKey());
  }
Пример #25
0
 public static Entity create(
     HttpServletRequest request, HttpServletResponse response, String cookie_name) {
   DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
   Entity entity = new Entity("aToken");
   entity.setProperty("ip", request.getRemoteAddr());
   entity.setProperty("date", new Date());
   ds.put(entity);
   //
   Cookie cookie = new Cookie(cookie_name, KeyFactory.keyToString(entity.getKey()));
   cookie.setPath("/");
   cookie.setMaxAge(-1);
   response.addCookie(cookie);
   return entity;
 }
Пример #26
0
 @Override
 public com.google.appengine.api.datastore.Entity modelToEntity(java.lang.Object model) {
   com.xhills.golf_party.model.course.Area m = (com.xhills.golf_party.model.course.Area) model;
   com.google.appengine.api.datastore.Entity entity = null;
   if (m.getKey() != null) {
     entity = new com.google.appengine.api.datastore.Entity(m.getKey());
   } else {
     entity = new com.google.appengine.api.datastore.Entity(kind);
   }
   entity.setProperty("name", m.getName());
   entity.setProperty("version", m.getVersion());
   entity.setProperty("slim3.schemaVersion", 1);
   return entity;
 }
  // For created new nodo
  public TreeBranch(
      final String name,
      final String parent_id,
      final Long left,
      final Long right,
      Key parent_entity_key) {

    entity = new Entity(TREE_ENTITY, parent_entity_key);

    entity.setProperty(NAME, name);
    entity.setProperty(PARENT_ID, parent_id);
    entity.setProperty(LEFT, left);
    entity.setProperty(RIGHT, right);
  }
Пример #28
0
  public Key store(Key orig, String type, long storeDate) {
    //		long start = System.currentTimeMillis();
    final int MAXSIZE = 1000000;
    Entity ent;
    Key next = null;
    this.storeTime = storeDate;
    this.nanoTime = System.nanoTime();

    byte[] data = this.serialize();
    Integer length = data.length;
    int pointer = 0;
    //		int counter = 0;
    while (length - pointer >= MAXSIZE) {
      // Expensive, should not be used too much!
      ent = new Entity(type + "_fragment");
      ent.setUnindexedProperty(
          "payload", new Blob(Arrays.copyOfRange(data, pointer, pointer + MAXSIZE)));
      if (next != null) ent.setUnindexedProperty("next", next);
      datastore.put(ent);
      //			counter++;
      next = ent.getKey();
      pointer += MAXSIZE;
    }

    if (orig != null) {
      System.err.println(
          "Warning, storing storable twice! Strange, should not happen with our immutable structures.");
      ent = new Entity(orig);
    } else {
      ent = new Entity(type);
    }
    ent.setUnindexedProperty("payload", new Blob(Arrays.copyOfRange(data, pointer, length)));
    if (next != null) ent.setUnindexedProperty("next", next);
    ent.setProperty("timestamp", this.storeTime);
    ent.setProperty("size", length);
    ent.setProperty("spread", this.spread);
    datastore.put(ent);
    //		counter++;
    myKey = ent.getKey();
    // Try to force index writing
    try {
      datastore.get(myKey);
    } catch (EntityNotFoundException e) {
    }
    this.storedSize = length;
    // System.out.println("Just stored shard of "+length+ " bytes in "+counter+" fragments  in
    // "+(System.currentTimeMillis()-start)+" ms");
    return myKey;
  }
Пример #29
0
  /**
   * Handles message requests and determines the appropriate response.
   *
   * @param req The HttpServletRequest object from doGet/doPost
   * @param resp The HttpServletResponse object from doGet/doPost
   * @throws IOException
   */
  private void messageReceived(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    String username = req.getParameter("usr");
    String querytitle = req.getParameter("querytitle");

    // add the chat information to memcache
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    Entity entity;
    String cnt = "";

    // Check if the user is in room
    if (username == null) {
      resp.sendRedirect("/");
      return;
    }

    Message message;
    // Get the message type from the last part of the requested url
    String type = req.getPathInfo();
    Calendar now = Calendar.getInstance();
    int hours = now.get(Calendar.HOUR_OF_DAY);
    int minutes = now.get(Calendar.MINUTE);
    String time = hours + ":" + minutes;

    if (isMessage(type)) {
      message = new Message(CHAT_MESSAGE, username, req.getParameter("message"), time);
      if (syncCache.get(querytitle) == null) {
        entity = new Entity("Message", querytitle);
        entity.setProperty(
            "content", "[" + time + "] [" + username + "] " + req.getParameter("message") + "<br>");
        syncCache.put(querytitle, entity);
      } else {
        entity = (Entity) syncCache.get(querytitle);
        cnt = (String) entity.getProperty("content");
        cnt = cnt + "[" + time + "] [" + username + "] " + req.getParameter("message") + "<br>";
        entity.setProperty("content", cnt);
        syncCache.put(querytitle, entity);
        // System.out.println(cnt);
      }
      sendMessage(querytitle, message);
    } else if (isJoin(type)) {
      message = new Message(JOIN_MESSAGE, username, "", time);
      sendMessage(querytitle, message);
    } else if (isLeave(type)) {
      message = new Message(LEAVE_MESSAGE, username, "", time);
      req.getSession().removeAttribute(querytitle);
      sendMessage(querytitle, message);
    }
  }
Пример #30
0
 public void reset2() {
   entity.setProperty("defaultAction", "blog");
   entity.setProperty("allowComments", true);
   entity.setProperty(LIST_PREFIX + LIST_ADMIN_LHLINK, "Sites,Wiki,Files");
   entity.setProperty(LIST_PREFIX + LIST_ADMIN_FILES_LHLINK, "Files");
   entity.setProperty(LIST_PREFIX + LIST_ADMIN_ARTICLES_LHLINK, "Sites,Wiki");
   entity.setProperty(LIST_PREFIX + LIST_ADMIN_HLINK, "Blogroll");
   entity.setProperty(LIST_PREFIX + LIST_SITEBAR_LHLINK, "");
   entity.setProperty(LIST_PREFIX + LIST_SITEBAR_HLINK, "Blogroll");
   entity.setProperty(LIST_PREFIX + LIST_MENU_LHLINK, "Sites");
 }