Beispiel #1
1
  /**
   * List the entities in JSON format
   *
   * @param entities entities to return as JSON strings
   */
  public static String writeJSON(Iterable<Entity> entities) {
    logger.log(Level.INFO, "creating JSON format object");
    StringBuilder sb = new StringBuilder();

    int i = 0;
    sb.append("{\"data\": [");
    for (Entity result : entities) {
      Map<String, Object> properties = result.getProperties();
      sb.append("{");
      if (result.getKey().getName() == null)
        sb.append("\"name\" : \"" + result.getKey().getId() + "\",");
      else sb.append("\"name\" : \"" + result.getKey().getName() + "\",");

      for (String key : properties.keySet()) {
        Object object = properties.get(key);
        if (object instanceof Text) {
          Text value = (Text) properties.get(key);
          sb.append("\"" + key + "\" : \"" + value.getValue() + "\",");
          // logger.info(value.getValue());//debug;
        } else {
          sb.append("\"" + key + "\" : \"" + properties.get(key) + "\",");
        }
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append("},");
      i++;
    }
    if (i > 0) {
      sb.deleteCharAt(sb.lastIndexOf(","));
    }
    sb.append("]}");
    return sb.toString();
  }
  @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");
  }
  @Test
  public void testEntityOnlyContainsProjectedProperties() throws Exception {
    Entity a =
        createEntity("Product", 1).withProperty("name", "b").withProperty("price", 1L).store();

    Entity b =
        createEntity("Product", 2).withProperty("name", "a").withProperty("price", 2L).store();

    Query query =
        new Query("Product")
            .addProjection(new PropertyProjection("price", Long.class))
            .setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("a", "b")));
    Entity firstResult = service.prepare(query).asList(FetchOptions.Builder.withDefaults()).get(0);

    assertEquals(1, firstResult.getProperties().size());
    assertEquals("price", firstResult.getProperties().keySet().iterator().next());

    query =
        new Query("Product")
            .setKeysOnly()
            .setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("a", "b")));
    firstResult = service.prepare(query).asList(FetchOptions.Builder.withDefaults()).get(0);

    assertEquals(0, firstResult.getProperties().size());
  }
  @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;
  }
 public Entity implement(Key requirementVersionKey, Key contentVersionKey) {
   Entity requirementVersion = this.find(requirementVersionKey);
   requirementVersion.setProperty(
       RequirementVersion.CONTENT_KEY_STRING, KeyFactory.keyToString(contentVersionKey));
   this.merge(requirementVersion);
   return requirementVersion;
 }
  /**
   * 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;
  }
 /**
  * Searches for an existing entity
  *
  * @param searchIn what kind of entity to search in
  * @param parent the parent for the entity, set to null to skip using
  * @param filters the values to search for
  * @return found key for entity
  */
 public static Key getSingleKey(String searchIn, Key parent, FilterWrapper... filters) {
   Entity foundEntity = getSingleEntity(searchIn, parent, true, filters);
   if (foundEntity != null) {
     return foundEntity.getKey();
   }
   return null;
 }
  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"));
  }
Beispiel #9
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 testSerializeWithOneToMany_AddChildToReattached() throws Exception {
    pm.setDetachAllOnCommit(true);
    beginTxn();
    HasOneToManyListJDO pojo = new HasOneToManyListJDO();
    pojo.setVal("yar");
    BidirectionalChildListJDO bidir = new BidirectionalChildListJDO();
    bidir.setChildVal("yar2");
    pojo.addBidirChild(bidir);
    pm.makePersistent(pojo);
    commitTxn();
    pm.close();
    pm = pmf.getPersistenceManager();

    pojo = toBytesAndBack(pojo);
    assertEquals("yar", pojo.getVal());
    assertEquals(1, pojo.getBidirChildren().size());
    beginTxn();
    pojo = pm.makePersistent(pojo);
    BidirectionalChildListJDO bidir2 = new BidirectionalChildListJDO();
    bidir.setChildVal("yar3");
    pojo.addBidirChild(bidir2);
    bidir2.setParent(pojo);
    commitTxn();
    Entity e = ds.get(KeyFactory.stringToKey(bidir2.getId()));
    assertEquals(KeyFactory.stringToKey(pojo.getId()), e.getKey().getParent());
  }
  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 testSerializeWithOneToMany_AddUnidirectionalChildToDetached() throws Exception {
    pm.setDetachAllOnCommit(true);
    beginTxn();
    HasOneToManyListJDO pojo = new HasOneToManyListJDO();
    pojo.setVal("yar");
    Flight flight = new Flight();
    flight.setName("harry");
    pojo.addFlight(flight);
    pm.makePersistent(pojo);
    commitTxn();
    pm.close();
    pm = pmf.getPersistenceManager();

    pojo = toBytesAndBack(pojo);
    assertEquals("yar", pojo.getVal());
    assertEquals(1, pojo.getFlights().size());
    Flight flight2 = new Flight();
    flight2.setName("not harry");
    pojo.addFlight(flight2);
    beginTxn();
    pojo = pm.makePersistent(pojo);
    commitTxn();
    Entity e = ds.get(KeyFactory.stringToKey(flight2.getId()));
    assertEquals(KeyFactory.stringToKey(pojo.getId()), e.getKey().getParent());
  }
  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 #14
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 #15
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;
  }
  @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();
  }
  @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);
    }
  }
  @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;
  }
 @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;
 }
  /**
   * 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;
  }
  /**
   * 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;
  }
  private ServiceResponse updateStatus(String _name, Long _id, String _status, User user)
      throws UnauthorizedException {
    if (user == null) {
      throw new UnauthorizedException("UnauthorizedException # User is Null.");
    }
    Key key = KeyFactory.createKey(_name, _id);
    Date currentDate = new Date();
    String userEmail = user.getEmail();

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

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

      entity.setProperty(_status, _status);

      dsService.put(entity);

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

    } catch (com.google.appengine.api.datastore.EntityNotFoundException e) {
      throw new EntityNotFoundException("Object does not exist");
    }
    return res;
  }
Beispiel #23
0
  /**
   * 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
  }
Beispiel #24
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String source = req.getParameter("source");
    ImagesService imagesService = ImagesServiceFactory.getImagesService();

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    List<Filter> filters = new ArrayList<Filter>();
    Query query = new Query(GAEFeedRepository.FEED_ITEM_KIND);
    filters.add(new Query.FilterPredicate("source", FilterOperator.EQUAL, source));
    filters.add(new Query.FilterPredicate("img1A", FilterOperator.EQUAL, 1));
    filters.add(new Query.FilterPredicate("img2A", FilterOperator.EQUAL, 1));

    query.setFilter(CompositeFilterOperator.and(filters));

    query.addSort("publishedDate", SortDirection.DESCENDING);
    PreparedQuery pq = datastore.prepare(query);
    int pageSize = 30;

    resp.setContentType("text/html");
    resp.getWriter().println(" <ul>");

    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);
    String startCursor = req.getParameter("cursor");

    // If this servlet is passed a cursor parameter, let's use it
    if (startCursor != null) {
      fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
    }

    QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
    for (Entity entity : results) {
      resp.getWriter()
          .println(
              "<li>"
                  + entity.getProperty("imageLink")
                  + " / "
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + " / <img height=40 width=40 src=\""
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + "\" />");
    }

    resp.getWriter().println("</li>  </entity></ul>  ");

    String cursor = results.getCursor().toWebSafeString();

    // Assuming this servlet lives at '/people'
    resp.getWriter()
        .println(
            "<a href=\"/p8admin/ListFeedItems?cursor="
                + cursor
                + "&source="
                + source
                + "\">Next page</a>");
  }
 public void 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 #26
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;
  }
  @Test
  public void testProjectionOfCollectionPropertyWithFilterOnCollectionProperty() throws Exception {
    Entity e =
        createEntity("Product", 1)
            .withProperty("name", Arrays.asList("aaa", "bbb"))
            .withProperty("price", Arrays.asList(10L, 20L))
            .store();

    Query query =
        new Query("Product")
            .addProjection(new PropertyProjection("name", String.class))
            .setFilter(new Query.FilterPredicate("price", GREATER_THAN, 0L))
            .addSort("price")
            .addSort("name");

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

    assertEquals(e.getKey(), results.get(0).getKey());
    assertEquals(e.getKey(), results.get(1).getKey());
    assertEquals(e.getKey(), results.get(2).getKey());
    assertEquals(e.getKey(), results.get(3).getKey());

    assertEquals("aaa", results.get(0).getProperty("name"));
    assertEquals("bbb", results.get(1).getProperty("name"));
    assertEquals("aaa", results.get(2).getProperty("name"));
    assertEquals("bbb", results.get(3).getProperty("name"));
  }
Beispiel #28
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 #29
0
 /** @throws Exception */
 @Test(expected = IllegalArgumentException.class)
 public void getModelMetaWithEntityForIllegalClass() throws Exception {
   AaaMeta aaaMeta = new AaaMeta();
   Entity entity = new Entity("Aaa");
   entity.setProperty(aaaMeta.getClassHierarchyListName(), Arrays.asList(Bbb.class.getName()));
   DatastoreUtil.getModelMeta(meta, entity);
 }
  @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();
  }