Esempio n. 1
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);
  }
Esempio n. 2
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;
  }
Esempio n. 3
0
 /**
  * Delete list of entities given their keys
  *
  * @param keys
  */
 public static void deleteEntity(final List<Key> keys) {
   datastore.delete(
       new Iterable<Key>() {
         public Iterator<Key> iterator() {
           return keys.iterator();
         }
       });
 }
Esempio n. 4
0
  public static boolean deleteEntity(Key key) {

    try {
      ds.delete(key);

      return true;
    } catch (Exception e) {
      return false;
    }
  }
Esempio n. 5
0
 public static boolean dropEntity(String id) {
   Entity entity = getEntity(id);
   if (entity != null) {
     // log.warning("drop :"+id+ " : "+ entity.getKey());
     datastore.delete(entity.getKey());
     syncCache.delete(id);
     return true;
   }
   return false;
 }
Esempio n. 6
0
 /**
  * Deletes a persistent record with the devices to be notified using a multicast message.
  *
  * @param encodedKey encoded key for the persistent record.
  */
 public static void deleteMulticast(String encodedKey) {
   Transaction txn = datastore.beginTransaction();
   try {
     Key key = KeyFactory.stringToKey(encodedKey);
     datastore.delete(key);
     txn.commit();
   } finally {
     if (txn.isActive()) {
       txn.rollback();
     }
   }
 }
 public Object process() throws xMethodException {
   boolean valid = true;
   String why = "";
   String id = this.getArguments("id");
   try {
     DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
     ds.delete(KeyFactory.stringToKey(id));
   } catch (Exception e) {
   }
   setReturnArguments("valid", String.valueOf(valid));
   setReturnArguments("why", why);
   return getServiceContext().doNextProcess();
 }
  public void deleteAudioClip(String audioClipId) throws BadRequestException {
    AudioClip audioClip = getAudioClipById(audioClipId);
    datastore.delete(KeyFactory.stringToKey(audioClipId));

    // task queue to delete the associated audio and image blobs
    Queue queue = QueueFactory.getDefaultQueue();
    queue.add(
        TaskOptions.Builder.withUrl("/rest/users/" + audioClip.getOwnerId() + "/audioClips/audio")
            .method(TaskOptions.Method.DELETE)
            .param("blobkey", audioClip.getAudioId()));
    queue.add(
        TaskOptions.Builder.withUrl("/rest/users/" + audioClip.getOwnerId() + "/audioClips/image")
            .method(TaskOptions.Method.DELETE)
            .param("blobkey", audioClip.getImageId()));
  }
 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   Transaction tx = datastore.beginTransaction();
   try {
     Key playerKey = KeyFactory.createKey("JoinGameKey", "PlayerList");
     Query query = new Query("JoinGame", playerKey);
     List<Entity> playerList =
         datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
     for (Entity e : playerList) datastore.delete(e.getKey());
     tx.commit();
   } catch (Exception e) {
     if (tx.isActive()) tx.rollback();
     ExceptionStringify es = new ExceptionStringify(e);
     resp.getWriter().print(es.run());
   }
   resp.getWriter().println("{'result':'Deleted players'}");
 }
  /**
   * This method removes the entity with primary key id. It uses HTTP DELETE method.
   *
   * @param id the primary key of the entity to be deleted.
   * @throws UnauthorizedException
   */
  @ApiMethod(
      name = "remove",
      scopes = {Config.EMAIL_SCOPE},
      clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID})
  public ServiceResponse remove(@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();
    dsService.delete(key);

    ServiceResponse res = new ServiceResponse();
    res.set_id(_id);
    return res;
  }
Esempio n. 11
0
 /**
  * Unregisters a device.
  *
  * @param regId device's registration id.
  */
 public static void unregister(String regId) {
   logger.info("Unregistering " + regId);
   Transaction txn = datastore.beginTransaction();
   try {
     Entity entity = findDeviceByRegId(regId);
     if (entity == null) {
       logger.warning("Device " + regId + " already unregistered");
     } else {
       Key key = entity.getKey();
       datastore.delete(key);
     }
     txn.commit();
   } finally {
     if (txn.isActive()) {
       txn.rollback();
     }
   }
 }
 @ApiMethod(name = "clearTasks")
 public void clearTasks() {
   DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
   Transaction txn = datastoreService.beginTransaction();
   try {
     Key taskBeanParentKey = KeyFactory.createKey("TaskBeanParent", "todo.txt");
     Query query = new Query(taskBeanParentKey);
     List<Entity> results =
         datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
     for (Entity result : results) {
       datastoreService.delete(result.getKey());
     }
     txn.commit();
   } finally {
     if (txn.isActive()) {
       txn.rollback();
     }
   }
 }
Esempio n. 13
0
 public void delete(Key key) {
   if (deletedCache.getIfPresent(key) != null) return;
   if (myKey.equals(key)) {
     deletedCache.put(key, this);
   }
   try {
     Entity ent = datastore.get(key);
     if (ent.hasProperty("next")) {
       delete((Key) ent.getProperty("next")); // recurse
     }
     datastore.delete(key);
     try {
       datastore.get(myKey);
     } catch (EntityNotFoundException e) {
     }
   } catch (Exception e) {
     // e.printStackTrace();
   }
 }
Esempio n. 14
0
  @DELETE
  public void deleteIt() {

    // delete an entity from the datastore
    // just print a message upon exception (don't throw)
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    if (syncCache.get(keyname) != null) {
      syncCache.delete(keyname);
    }
    Key entKey = KeyFactory.createKey("TaskData", keyname);
    try {
      Entity ent = datastore.get(entKey);
      datastore.delete(entKey);
      System.err.println("TaskData deleted in Datastore");
    } catch (EntityNotFoundException e) {
      System.err.println("TaskData not found in Datastore");
    }
  }
Esempio n. 15
0
 private void remove(String encoded, HttpServletResponse response) throws IOException {
   BlobstoreService blobstore = BlobstoreServiceFactory.getBlobstoreService();
   DatastoreService datastore = DS.get();
   Key key = KeyFactory.stringToKey(encoded);
   Transaction tr = datastore.beginTransaction();
   try {
     Entity blog = datastore.get(key);
     datastore.delete(key);
     response.setContentType("text/plain");
     PrintWriter writer = response.getWriter();
     writer.println("Deleted blog: " + blog.getProperty("Subject"));
     tr.commit();
   } catch (EntityNotFoundException ex) {
     throw new IOException(ex);
   } finally {
     if (tr.isActive()) {
       tr.rollback();
     }
   }
 }
Esempio n. 16
0
 /**
  * One specialty compared to the other stores is that the incoming entity is never null. The user
  * of this persistence needs therefore to somehow determine if the entity is persistent or not,
  * e.g. through the lack of a particular attribute. It also means that the return value of the
  * function is slightly less meaningful, since the entity is manipulated in place. Exception:
  * returning null will still delete the entity.
  */
 @Override
 public Entity mutate(String key, Function<? super Entity, ? extends Entity> mutator) {
   Preconditions.checkNotNull(key);
   Preconditions.checkNotNull(mutator);
   Key dbKey = KeyFactory.createKey(kind, escape(key));
   Exception lastException = null;
   for (int i = 0; i < NUM_RETRIES; i++) {
     Transaction t = service.beginTransaction();
     boolean success = false;
     Entity entity;
     try {
       entity = service.get(t, dbKey);
     } catch (EntityNotFoundException e) {
       entity = new Entity(kind, escape(key));
     }
     Entity data = mutator.apply(entity);
     try {
       if (data != null) {
         service.put(t, data);
       } else {
         service.delete(t, dbKey);
       }
       t.commit();
       success = true;
     } catch (ConcurrentModificationException e) {
       success = false;
       lastException = e;
     } catch (DatastoreFailureException e) {
       success = false;
       lastException = e;
     } finally {
       if (!success) {
         t.rollback();
       } else {
         return data;
       }
     }
   }
   throw new StoreException("Could not store data for key " + key, lastException);
 }
Esempio n. 17
0
  public static void delete(String path, Owner owner) {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Key k = PathHelper.getStorageKey("File", path, owner);

    ds.delete(k);
  }
Esempio n. 18
0
 /**
  * Delete the entity from persistent store represented by the key
  *
  * @param key : key to delete the entity from the persistent store
  */
 public static void deleteEntity(Key key) {
   logger.log(Level.INFO, "Deleting entity");
   datastore.delete(key);
 }
Esempio n. 19
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Action ac = null;
    try {
      ac = Action.valueOf(req.getParameter("action"));
    } catch (Exception e) {
      resp.sendError(
          400, "'action' parameter required, can be " + Arrays.toString(Action.values()));
      return;
    }
    // okay, we now know what we want to do
    switch (ac) {
      case submit:
        // 1st: validate inputs
        String email = req.getParameter("email");
        String url = req.getParameter("url");
        String intervalStr = req.getParameter("interval");

        if (!Utils.isValidEmailAddress(email)) {
          resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'email' parameter");
          return;
        }
        if (!Utils.isValidUrl(url)) {
          resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'url' parameter");
          return;
        }
        if (!Utils.isValidInterval(intervalStr, intervals)) {
          resp.sendError(
              HttpServletResponse.SC_BAD_REQUEST,
              "invalid 'interval' parameter, can be " + intervals.toString());
          return;
        }

        // 2nd: put our task in the data store, but not enable it yet
        Entity job = new Entity("Job");
        job.setProperty("url", url);
        job.setProperty("intervalSeconds", Integer.parseInt(intervalStr));
        job.setProperty("email", email);
        job.setProperty("enabled", false);
        String id = UUID.randomUUID().toString();
        job.setProperty("id", id);

        datastore.put(job);

        log.info(
            "New request: url="
                + url
                + ",email="
                + email
                + ",interval="
                + intervalStr
                + ",id="
                + id);

        // 3rd: send email to admin asking to confirm
        String confirmUrl = "http://" + Utils.HOSTNAME + "/pmc?action=enable&id=" + id;

        Utils.sendMail(
            email,
            "Hello.\n\nThis is the \"Poor Man's cron service\" at "
                + Utils.HOSTNAME
                + ".\nI have been asked (probably by you) to send a request to the URL "
                + url
                + " every "
                + intervalStr
                + " seconds.\nIf you think that's okay, please visit the following URL: "
                + confirmUrl
                + "\n\nBest, PMC");

        // 4th: display some message on response stream.
        resp.getWriter()
            .write(
                "Okay, I have received your job. Please check your eMail for further instructions. ");
        resp.getWriter().close();
        break;
      case enable:
        String enableid = req.getParameter("id");
        // 1st: validate inputs

        if (!Utils.isValidId(enableid)) {
          resp.sendError(
              HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter, should be a UUID");
          return;
        }

        // 2nd: look if we know a job with that id
        List<Entity> jobs =
            datastore
                .prepare(
                    new Query("Job")
                        .setFilter(new FilterPredicate("id", FilterOperator.EQUAL, enableid)))
                .asList(withLimit(1));
        if (jobs.size() < 1) {
          resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter");
          return;
        }
        // 3rd: set job to be enabled
        Entity enableJob = jobs.get(0);
        enableJob.setProperty("enabled", true);
        datastore.put(enableJob);

        log.info("Enabled: id=" + enableid);

        // 4th: send confirmation mail
        String deleteLink = "http://" + Utils.HOSTNAME + "/pmc?action=delete&id=" + enableid;

        String viewLink = "http://" + Utils.HOSTNAME + "/pmc?action=view&id=" + enableid;
        Utils.sendMail(
            (String) enableJob.getProperty("email"),
            "Hello again!\n\nThis is the \"Poor Man's cron service\" at "
                + Utils.HOSTNAME
                + ".\nI have enabled your job to send a request to the URL "
                + enableJob.getProperty("url")
                + " every "
                + enableJob.getProperty("intervalSeconds")
                + " seconds.\nIf you want to see how your job is doing, and what your URL has to say, visit this page: "
                + viewLink
                + "\n\nIf you want to cancel this job again, please click on the following link: "
                + deleteLink
                + "\n\nIt would be advisable to keep this message, as it would otherwise be hard to stop me from accessing your URL.\n\nBest, PMC");

        // 5th: display some message on response stream.
        resp.getWriter()
            .write(
                "Okay, I have enabled your job. Please check your eMail for further instructions. ");
        resp.getWriter().close();
        break;
      case view:
        // TODO: implement me, pleaaase
        resp.getWriter().write("Not Implemented Yet.");
        resp.getWriter().close();
        break;

      case delete:
        String deleteid = req.getParameter("id");
        // 1st: validate inputs

        if (!Utils.isValidId(deleteid)) {
          resp.sendError(
              HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter, should be a UUID");
          return;
        }

        // 2nd: look if we know a job with that id
        List<Entity> jobsd =
            datastore
                .prepare(
                    new Query("Job")
                        .setFilter(new FilterPredicate("id", FilterOperator.EQUAL, deleteid)))
                .asList(withLimit(1));
        if (jobsd.size() < 1) {
          resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter");
          return;
        }

        // 3rd: delete job
        datastore.delete(jobsd.get(0).getKey());

        log.info("Deleted: id=" + deleteid);

        // 4th: display some message on response stream.
        resp.getWriter().write("Okay, I have deleted your job. Bye! ");
        resp.getWriter().close();
        break;
    }
  }