@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"))));
  }
  @Test
  public void testProjectionOfCollectionProperties() throws Exception {
    Entity e =
        createEntity("test", 1)
            .withProperty("prop", Arrays.asList("bbb", "ccc", "aaa"))
            .withProperty("prop2", Arrays.asList("xxx", "yyy"))
            .store();

    Query query =
        new Query("test")
            .addProjection(new PropertyProjection("prop", String.class))
            .addSort("prop");

    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> results = preparedQuery.asList(withDefaults());
    assertEquals(3, results.size());

    Entity firstResult = results.get(0);
    Entity secondResult = results.get(1);
    Entity thirdResult = results.get(2);

    assertEquals(e.getKey(), firstResult.getKey());
    assertEquals(e.getKey(), secondResult.getKey());
    assertEquals(e.getKey(), thirdResult.getKey());
    assertEquals("aaa", firstResult.getProperty("prop"));
    assertEquals("bbb", secondResult.getProperty("prop"));
    assertEquals("ccc", thirdResult.getProperty("prop"));
  }
  public List<AudioClip> getAudioClipsByUser(String userId) throws BadRequestException {
    List<AudioClip> audioClipList = new ArrayList<AudioClip>();

    // verify userId
    validateUserExistance(userId); // throws bad request exception of user doesn't exist
    Filter userFilter =
        new FilterPredicate(TuneInConstants.AUDIO_CLIP_OWNER_ID, FilterOperator.EQUAL, userId);
    Query q =
        new Query(TuneInConstants.AUDIO_CLIP_TYPE)
            .setFilter(userFilter)
            .addSort(TuneInConstants.AUDIO_CLIP_DATE, SortDirection.ASCENDING);
    PreparedQuery pq = datastore.prepare(q);
    AudioClip audioClip;
    for (Entity result : pq.asIterable()) {
      audioClip =
          new AudioClip(
              KeyFactory.keyToString(result.getKey()),
              (String) result.getProperty(TuneInConstants.AUDIO_CLIP_TITLE),
              (String) result.getProperty(TuneInConstants.AUDIO_CLIP_OWNER_ID),
              (String) result.getProperty(TuneInConstants.AUDIO_CLIP_AUDIO_ID),
              (String) result.getProperty(TuneInConstants.AUDIO_CLIP_IMAGE_ID),
              (Date) result.getProperty(TuneInConstants.AUDIO_CLIP_DATE));
      audioClipList.add(audioClip);
    }
    return audioClipList;
  }
  @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 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>");
  }
Beispiel #6
0
  @Test
  public void testMarshall_Embedded() {
    RootEntity rootObject = new RootEntity(); // one entity
    ChildEntity childObject = new ChildEntity("Test City");
    ChildEntity embeddedObject = new ChildEntity("Old Test City");
    embeddedObject.setId(1L);
    embeddedObject.setType("EmbeddedType");
    rootObject.setId("TestUser");
    rootObject.setCount(25);
    childObject.setParent(rootObject);
    rootObject.setNewChildEntity(childObject); // one entity
    rootObject.setEmbeddedEntity(embeddedObject); // not included, @Embedded

    IdentityHashMap<Object, Entity> stack = testMarshaller.marshall(null, rootObject);

    Entity rootObjectEntity = stack.get(rootObject);
    Entity childObjectEntity = stack.get(childObject);

    EmbeddedEntity ee = (EmbeddedEntity) rootObjectEntity.getProperty("embeddedEntity");
    Key childKey = (Key) rootObjectEntity.getProperty("newChildEntity");
    Key parentKey = childKey.getParent();

    assertEquals(2, stack.size());
    assertNotNull(parentKey);
    assertEquals(EmbeddedEntity.class, ee.getClass());
    assertTrue(childKey instanceof Key);
    assertEquals(rootObjectEntity.getKey().getId(), parentKey.getId());
    assertEquals(rootObjectEntity.getKey().getName(), parentKey.getName());

    assertEquals(1L, ee.getProperties().get("id"));
    assertEquals("EmbeddedType", ee.getProperties().get("type"));
  }
  @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 #8
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");
  }
 public void remove(Key requirementVersionKey) {
   LogEntityManager logEntityManager = new LogEntityManager();
   Transaction txn = datastore.beginTransaction();
   try {
     Entity artifactVersion = this.find(requirementVersionKey);
     Entity artifact = this.find(artifactVersion.getParent());
     Entity project = this.find(artifact.getParent());
     logEntityManager.persist(
         project.getKey(),
         new Date(),
         "O usu�rio "
             + artifact.getProperty(Artifact.CREATOR_ID)
             + " removeu o requisito "
             + artifact.getProperty(Artifact.NUMBER)
             + ": "
             + artifact.getProperty(Artifact.TITLE)
             + " do projeto "
             + project.getProperty(Project.PROJECT_NAME));
     super.remove(requirementVersionKey);
     txn.commit();
   } finally {
     if (txn.isActive()) {
       txn.rollback();
       throw new TransactionException();
     }
   }
 }
Beispiel #10
0
  // Factory methods:
  public static MemoStorable load(Entity ent) {
    //		long start = System.currentTimeMillis();
    byte[] result;
    Key key = ent.getKey();
    int size = 0;
    long spread = 0;
    //		int count=0;
    try {
      Blob blob = (Blob) ent.getProperty("payload");
      size = (int) ((Long) ent.getProperty("size") % Integer.MAX_VALUE);
      spread = ((Long) ent.getProperty("spread"));

      byte[] data = blob.getBytes();
      result = Arrays.copyOf(data, data.length);
      //			count++;
      while (ent.hasProperty("next")) {
        // Expensive, should not be used too much!
        Key next = (Key) ent.getProperty("next");
        ent = datastore.get(next);
        blob = (Blob) ent.getProperty("payload");
        data = blob.getBytes();
        result = concat(data, result); // Add to front of result, due to
        //				count++;						// the storing order
      }

    } catch (EntityNotFoundException e) {
      e.printStackTrace();
      return null;
    }
    MemoStorable res = _unserialize(result, size);
    res.spread = spread;
    res.storedSize = result.length;
    if (res != null) res.myKey = key;
    return res;
  }
  public void testSimpleSerializeWithoutTxns() throws Exception {
    switchDatasource(PersistenceManagerFactoryName.nontransactional);
    pm.setDetachAllOnCommit(true);
    DetachableJDO pojo = new DetachableJDO();
    pojo.setVal("yar");
    Date now = new Date();
    pojo.setDate(now);
    pm.makePersistent(pojo);

    // DN3 changes this from P_NEW to DETACHED_CLEAN since detachAllOnCommit
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));

    pm.close();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    assertEquals(Date.class, pojo.getDate().getClass());
    pm = pmf.getPersistenceManager();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));

    pojo = toBytesAndBack(pojo);

    assertEquals("yar", pojo.getVal());
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    pojo.setVal("not yar");
    Date newDate = new Date(pojo.getDate().getTime() + 1);
    pojo.getDate().setTime(newDate.getTime());
    assertEquals(ObjectState.DETACHED_DIRTY, JDOHelper.getObjectState(pojo));
    pm.makePersistent(pojo);
    pm.close();
    Entity e = ds.get(KeyFactory.createKey(DetachableJDO.class.getSimpleName(), pojo.getId()));
    assertEquals("not yar", e.getProperty("val"));
    assertEquals(newDate, e.getProperty("date"));
  }
  /**
   * Retrieve
   *
   * @throws IOException
   * @throws IllegalArgumentException
   * @throws NoSuchProviderException
   * @throws NoSuchAlgorithmException
   */
  private long computeAndReturnTime(
      long remainTime, List<Entity> works, List<PlayWorkBean> playWorks)
      throws NoSuchAlgorithmException, NoSuchProviderException, IllegalArgumentException,
          IOException {

    int sortedSize = works.size();

    // randomize for getting work in the list
    int randomId = Random.getInstance().getNumericRandomInt(sortedSize);
    // get work
    Entity currentWork = works.remove(randomId);
    long randomWorkTime = 0;
    // music case
    if (WorkTypeEnum.MUSIC.name().equals(currentWork.getProperty("type"))) {
      Long musicTime = (Long) currentWork.getProperty("time");
      randomWorkTime = musicTime.longValue();
    } else {
      // randomize for work time displaying
      randomWorkTime = minWorkTime + Random.getInstance().getNumericRandomInt(maxWorkTime);
    }
    // avoid randomWorkTime to be superior at remain time
    if (remainTime < randomWorkTime) {
      randomWorkTime = remainTime;
    }

    playWorks.add(new PlayWorkBean(Long.valueOf(randomWorkTime), currentWork.getKey()));

    return randomWorkTime;
  }
  public void testSimpleSerializeWithTxns()
      throws IOException, ClassNotFoundException, EntityNotFoundException {
    pm.setDetachAllOnCommit(true);
    beginTxn();
    DetachableJDO pojo = new DetachableJDO();
    pojo.setVal("yar");
    Date now = new Date();
    pojo.setDate(now);
    pm.makePersistent(pojo);
    commitTxn();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    assertEquals(Date.class, pojo.getDate().getClass());
    pm.close();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    pm = pmf.getPersistenceManager();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));

    pojo = toBytesAndBack(pojo);

    assertEquals("yar", pojo.getVal());
    assertEquals(now, pojo.getDate());
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    beginTxn();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    pojo.setVal("not yar");
    Date newDate = new Date(pojo.getDate().getTime() + 1);
    pojo.getDate().setTime(newDate.getTime());
    assertEquals(ObjectState.DETACHED_DIRTY, JDOHelper.getObjectState(pojo));
    pm.makePersistent(pojo);
    commitTxn();
    Entity e = ds.get(KeyFactory.createKey(DetachableJDO.class.getSimpleName(), pojo.getId()));
    assertEquals("not yar", e.getProperty("val"));
    assertEquals(newDate, e.getProperty("date"));
  }
  public void testSerializeWithMultiValueProps() throws Exception {
    pm.setDetachAllOnCommit(true);
    beginTxn();
    DetachableWithMultiValuePropsJDO pojo = new DetachableWithMultiValuePropsJDO();
    pojo.setStrList(Utils.newArrayList("c", "d"));
    pm.makePersistent(pojo);
    commitTxn();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    pm.close();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    pm = pmf.getPersistenceManager();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));

    pojo = toBytesAndBack(pojo);

    assertEquals(Utils.newArrayList("c", "d"), pojo.getStrList());
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    beginTxn();
    assertEquals(ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(pojo));
    // reattach to the pm - this turns our regular list field into a managed
    // list field
    pojo = pm.makePersistent(pojo);
    assertEquals(ObjectState.PERSISTENT_CLEAN, JDOHelper.getObjectState(pojo));
    pojo.getStrList().add("e");
    commitTxn();
    Entity e =
        ds.get(
            KeyFactory.createKey(
                DetachableWithMultiValuePropsJDO.class.getSimpleName(), pojo.getId()));
    assertEquals(3, ((List<String>) e.getProperty("strList")).size());
    assertEquals(Utils.newArrayList("c", "d", "e"), e.getProperty("strList"));
  }
Beispiel #15
0
  /**
   * Convenience function to extend this MarkerObj with another MarkerObj. Normally used when
   * updating the database. entityMe param makes sure that the current user has permission to update
   * some properties.
   */
  public void extend(MarkerObj other, Entity entityMe) {
    lat = other.lat;
    lng = other.lng;
    cat = other.cat;
    near = other.near;
    info = other.info;
    privacy = other.privacy;
    updatedDate = new Date().getTime();

    String myName = (String) entityMe.getProperty("name");
    String myPrivileges = (String) entityMe.getProperty("privileges");

    if (myPrivileges.equals("random")) {
      title = myName;
    } else {
      if (other.title != null) title = other.title;
    }

    if (myPrivileges.equals("admin")) {
      if (other.type != null) type = other.type;
      if (other.author != null) author = other.author;
      if (other.creationDate != null) creationDate = other.creationDate;
    }

    // TODO: Remove properties that do not apply anymore if the type was changed (not important, low
    // priority).
  }
Beispiel #16
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();
     }
   }
 }
Beispiel #17
0
  @Test
  public void testeToEntity() {
    Unidade unidade = new Unidade("campinas");
    Entity unidadeEntity = unidade.toEntity();

    Assert.assertEquals(unidade.getId(), unidadeEntity.getProperty(UnidadeFields.id.name()));
    Assert.assertEquals(unidade.getNome(), unidadeEntity.getProperty(UnidadeFields.nome.name()));
  }
Beispiel #18
0
  @Test
  public void testeConstrutor() {
    Entity unidadeEntity = new Unidade("campinas").toEntity();
    Unidade unidade = new Unidade(unidadeEntity);

    Assert.assertEquals(unidadeEntity.getProperty(UnidadeFields.id.name()), unidade.getId());
    Assert.assertEquals(unidadeEntity.getProperty(UnidadeFields.nome.name()), unidade.getNome());
  }
Beispiel #19
0
 @Override
 public slim3.demo.model.Blog entityToModel(com.google.appengine.api.datastore.Entity entity) {
   slim3.demo.model.Blog model = new slim3.demo.model.Blog();
   model.setContent((java.lang.String) entity.getProperty("content"));
   model.setKey(entity.getKey());
   model.setTitle((java.lang.String) entity.getProperty("title"));
   model.setVersion((java.lang.Long) entity.getProperty("version"));
   return model;
 }
Beispiel #20
0
 @Override
 public com.xhills.golf_party.model.course.Area entityToModel(
     com.google.appengine.api.datastore.Entity entity) {
   com.xhills.golf_party.model.course.Area model = new com.xhills.golf_party.model.course.Area();
   model.setKey(entity.getKey());
   model.setName((java.lang.String) entity.getProperty("name"));
   model.setVersion((java.lang.Long) entity.getProperty("version"));
   return model;
 }
Beispiel #21
0
  public static Question GetQuestion(Entity entity) {
    Question q = new Question();
    q.key = KeyFactory.keyToString(entity.getKey());
    q.questionText = (String) entity.getProperty("Text");
    q.rating = (Long) entity.getProperty("Rating");
    q.datePosted = (Date) entity.getProperty("DatePosted");

    return q;
  }
  @Test
  public void testProjections() throws Exception {
    Entity e =
        createEntity("Product", 1)
            .withProperty("price", 123L)
            .withProperty("percent", 0.123)
            .withProperty("x", -0.321)
            .withProperty("diff", -5L)
            .withProperty("weight", 10L)
            .store();

    Query query =
        new Query("Product")
            .addProjection(new PropertyProjection("price", Long.class))
            .addProjection(new PropertyProjection("percent", Double.class))
            .addProjection(new PropertyProjection("x", Double.class))
            .addProjection(new PropertyProjection("diff", Long.class));

    PreparedQuery preparedQuery = service.prepare(query);
    Entity result = preparedQuery.asSingleEntity();
    assertEquals(e.getKey(), result.getKey());
    assertEquals(e.getProperty("price"), result.getProperty("price"));
    assertEquals(e.getProperty("percent"), result.getProperty("percent"));
    assertEquals(e.getProperty("x"), result.getProperty("x"));
    assertEquals(e.getProperty("diff"), result.getProperty("diff"));
    assertNull(result.getProperty("weight"));
  }
Beispiel #23
0
 @Override
 public tutorial.global.cool.model.BaseFormObject entityToModel(
     com.google.appengine.api.datastore.Entity entity) {
   tutorial.global.cool.model.BaseFormObject model =
       new tutorial.global.cool.model.BaseFormObject();
   model.setEmail((java.lang.String) entity.getProperty("email"));
   model.setInsertDate((java.lang.String) entity.getProperty("insertDate"));
   model.setKey(entity.getKey());
   model.setUpdateDate((java.lang.String) entity.getProperty("updateDate"));
   model.setUserId((java.lang.String) entity.getProperty("userId"));
   model.setVersion((java.lang.Long) entity.getProperty("version"));
   return model;
 }
Beispiel #24
0
 private void retrieveCoordinates(ModelMap map, HttpServletRequest request)
     throws URISyntaxException {
   Query coordinateQuery = new Query("Coordinate");
   List<Entity> entities =
       datastore.prepare(coordinateQuery).asList(FetchOptions.Builder.withLimit(500));
   Coordinates coordinates = new Coordinates();
   coordinates.setUri(new URI(request.getRequestURI()));
   for (Entity entity : entities) {
     coordinates.addCoordinate(
         new Coordinate(
             (String) entity.getProperty("latitude"), (String) entity.getProperty("longitude")));
   }
   map.addAttribute(coordinates);
 }
Beispiel #25
0
 public List<Statistic> fromEntity(Collection<Entity> col) {
   List<Statistic> list = new ArrayList<Statistic>();
   Statistic st;
   for (Entity e : col) {
     st = new Statistic();
     //			st.setName((String) e.getProperty("name"));
     //			st.setMomin((String) e.getProperty("momin"));
     st.setKey((String) e.getProperty("key"));
     st.setSerializedData((String) e.getProperty("serializedData"));
     list.add(st);
     st.getSerializedData().length();
   }
   return list;
 }
 private void sendMail(
     HttpServletRequest request, BlogAuthor blogAuthor, Entity blog, Settings settings)
     throws IOException {
   if (settings.dontSendEmail()) {
     return;
   }
   try {
     String digest = DS.getBlogDigest(blog);
     MailService mailService = MailServiceFactory.getMailService();
     Message reply = new Message();
     reply.setSender(blogAuthor.toString());
     Email sender = (Email) blog.getProperty(SenderProperty);
     reply.setTo(sender.getEmail());
     String subject = (String) blog.getProperty(SubjectProperty);
     reply.setSubject("Blog: " + subject + " received");
     StringBuilder sb = new StringBuilder();
     URI reqUri = new URI(request.getScheme(), NamespaceManager.get(), "", "");
     if (!settings.isPublishImmediately()) {
       sb.append("<div>");
       sb.append(
           "<p>Blog is not yet published because it was sent from untrusted email address "
               + sender.getEmail()
               + ". </p>");
       URI publishUri =
           reqUri.resolve(
               "/blog?action=publish&blog="
                   + KeyFactory.keyToString(blog.getKey())
                   + "&auth="
                   + digest);
       sb.append("<a href=\"" + publishUri.toASCIIString() + "\">Publish Blog</a>");
       sb.append("</div>");
     }
     sb.append("<div>");
     sb.append("<p>If blog is not ok, you can delete and then resend it.</p>");
     URI deleteUri =
         reqUri.resolve(
             "/blog?action=remove&blog="
                 + KeyFactory.keyToString(blog.getKey())
                 + "&auth="
                 + digest);
     sb.append("<a href=\"" + deleteUri.toASCIIString() + "\">Delete Blog</a>");
     sb.append("</div>");
     reply.setHtmlBody(sb.toString());
     mailService.send(reply);
   } catch (URISyntaxException ex) {
     throw new IOException(ex);
   }
 }
  @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");
  }
  @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;
  }
  /**
   * Get a UUID property from an entity
   *
   * @param entity the entity to get the UUID from
   * @param propertyName name of the property
   * @return Stored UUID, null if it doesn't exist
   */
  public static UUID getPropertyUuid(Entity entity, String propertyName) {
    if (entity.hasProperty(propertyName)) {
      return UUID.fromString((String) entity.getProperty(propertyName));
    }

    return null;
  }
 @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;
 }