Пример #1
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;
  }
Пример #2
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>");
  }
Пример #3
0
  public String getResultado2() throws EntityNotFoundException {
    Query q = new Query("Relationship");
    UserService userService = ServiceLocator.getUserService();
    q.addFilter(
        "user", Query.FilterOperator.EQUAL, ServiceLocator.getUserService().getCurrentUser());

    StringBuffer resultado = new StringBuffer();
    Iterator<Entity> iterator = ServiceLocator.getPersistenceService().queryIterator(q);
    if (!iterator.hasNext()) {
      resultado.append("\nNo records found.");
    } else {
      while (iterator.hasNext()) {
        Entity record = iterator.next();
        resultado.append("\n" + record.getKey());

        List children = (List) record.getProperty("children");
        for (Iterator iterator2 = children.iterator(); iterator2.hasNext(); ) {
          Key k = (Key) iterator2.next();
          Entity child = ServiceLocator.getPersistenceService().load(k);
          resultado.append("\nXXXX" + child.getProperties() + "YYYY");
        }

        // String recordString = printEntity(record);
      }
    }

    return resultado.toString();
  }
  /** Create a PreparedQuery that fetches keys only, relevant to our current state. */
  private PreparedQuery prepareKeysOnly() {
    // Can't modify the query, we might need to use it again
    com.google.appengine.api.datastore.Query cloned = this.cloneRawQuery(this.actual);
    cloned.setKeysOnly();

    return this.ofy.getDatastore().prepare(this.ofy.getTxn(), cloned);
  }
Пример #5
0
 public static Entity getWeekMeasureForDataChannel(
     DatastoreService datastore, String dataChannel) {
   Query query = new Query(Entities.EntityKind.WeekMeasures.getKindName());
   query.addFilter("DChoofdmeting", FilterOperator.EQUAL, dataChannel);
   PreparedQuery prepared = datastore.prepare(query);
   return prepared.asSingleEntity();
 }
Пример #6
0
  /**
   * Returns the Account key associated with the specified authorization key.
   *
   * @param pm reference to the persistence manager
   * @param authorizationKey authorization key to return the account key for
   * @return the Account key associated with the specified authorization key; or <code>null</code>
   *     if the authorization key is invalid
   */
  public static Key getAccountKeyByAuthKey(
      final PersistenceManager pm, final String authorizationKey) {
    final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey;
    final String accountKeyString = (String) memcacheService.get(memcacheKey);
    if (accountKeyString != null) return KeyFactory.stringToKey(accountKeyString);

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

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

    return accountKey;
  }
Пример #7
0
 public List<Entry<String, Entity>> scan(
     String start, String end, int max, SortDirection direction, boolean keysOnly) {
   Preconditions.checkNotNull(start);
   Preconditions.checkNotNull(end);
   Preconditions.checkArgument(max > -1);
   if (max == 0) {
     return Lists.newArrayList();
   }
   Query query = new Query(kind);
   query.addFilter(
       "__key__", FilterOperator.GREATER_THAN_OR_EQUAL, KeyFactory.createKey(kind, escape(start)));
   query.addFilter("__key__", FilterOperator.LESS_THAN, KeyFactory.createKey(kind, escape(end)));
   query.addSort("__key__", direction);
   if (keysOnly) {
     query.setKeysOnly();
   }
   PreparedQuery preparedQuery = service.prepare(query);
   List<Entry<String, Entity>> result = Lists.newArrayList();
   for (Entity entity : preparedQuery.asIterable(FetchOptions.Builder.withLimit(max))) {
     if (keysOnly) {
       result.add(Maps.immutableEntry(unescape(entity.getKey().getName()), (Entity) null));
     } else {
       result.add(Maps.immutableEntry(unescape(entity.getKey().getName()), entity));
     }
   }
   return result;
 }
Пример #8
0
  @Override
  public List<Integer> years() {
    List<Integer> years = new ArrayList<Integer>();

    Query q = new Query(sitemapEntity.getKind());
    q.addSort(sitemapEntity.getCreatedDateProperty(), SortDirection.ASCENDING);
    List<Entity> e = ds.prepare(q).asList(FetchOptions.Builder.withLimit(1));
    int start;
    if (e.size() == 1) {
      start =
          DateUtils.getYear((Date) e.get(0).getProperty(sitemapEntity.getCreatedDateProperty()));
    } else {
      return years;
    }

    q = new Query(sitemapEntity.getKind());
    q.addSort(sitemapEntity.getCreatedDateProperty(), SortDirection.DESCENDING);
    e = ds.prepare(q).asList(FetchOptions.Builder.withLimit(1));

    int end =
        DateUtils.getYear((Date) e.get(0).getProperty(sitemapEntity.getCreatedDateProperty()));

    for (int i = start; i <= end; i++) {
      years.add(i);
    }
    return years;
  }
Пример #9
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;
  }
Пример #10
0
 /**
  * @param kind
  * @param ancestor
  * @return
  */
 public static Iterable<Entity> listChildKeys(String kind, Key ancestor) {
   logger.log(Level.INFO, "Search entities based on parent");
   Query q = new Query(kind);
   q.setAncestor(ancestor).setKeysOnly();
   q.addFilter(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, ancestor);
   PreparedQuery pq = datastore.prepare(q);
   return pq.asIterable();
 }
Пример #11
0
 public Entity getEprSpectrEntityById(String loc, String id) {
   DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
   Query query = new Query(loc + EprSpectr.class.getSimpleName());
   query = query.addFilter(EprSpectr.ID, Query.FilterOperator.EQUAL, id);
   for (Entity anekEntity : datastoreService.prepare(query).asIterable()) {
     return anekEntity;
   }
   return null;
 }
Пример #12
0
 /**
  * * Search entities based on search criteria
  *
  * @param kind
  * @param searchBy : Searching Criteria (Property)
  * @param searchFor : Searching Value (Property Value)
  * @return List all entities of a kind from the cache or datastore (if not in cache) with the
  *     specified properties
  */
 public static Iterable<Entity> listEntities(String kind, String searchBy, String searchFor) {
   logger.log(Level.INFO, "Search entities based on search criteria");
   Query q = new Query(kind);
   if (searchFor != null && !"".equals(searchFor)) {
     q.addFilter(searchBy, FilterOperator.EQUAL, searchFor);
   }
   PreparedQuery pq = datastore.prepare(q);
   return pq.asIterable();
 }
Пример #13
0
  @SuppressWarnings("unchecked")
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    List<String> errors = new ArrayList<String>();
    PersistenceManager pm = getPersistenceManager();
    String username = req.getParameter("username");
    String password = req.getParameter("password");

    if (username.isEmpty()) {
      errors.add("Username is required.");
    }
    if (password.isEmpty()) {
      errors.add("Password is required.");
    }

    try {
      req.setAttribute("errors", errors);
      List<Admin> us = (List<Admin>) pm.newQuery(Admin.class).execute();

      resp.setContentType("text/html");

      DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
      Query q = new Query("Admin");
      q.setFilter(
          Query.CompositeFilterOperator.and(
              new Query.FilterPredicate("username", Query.FilterOperator.EQUAL, username),
              new Query.FilterPredicate("password", Query.FilterOperator.EQUAL, password)));
      List<Entity> entities = ds.prepare(q).asList(FetchOptions.Builder.withDefaults());
      if (entities.size() == 0) {
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
      }
      // if(entities.size()>0){
      if (us.size() > 0) {
        /*for(int i = 0; i < us.size(); i++){
        	if(us.get(i).getPassword().equals(password) && us.get(i).getUsername().equals(username) && us.get(i).getUser_type() == 0){
        		resp.sendRedirect("/AdminHome");
        	}
        	if(us.get(i).getPassword().equals(password) && us.get(i).getUsername().equals(username) && us.get(i).getUser_type() == 1){
        		resp.sendRedirect("/login.jsp");
        	}
        	if(us.get(i).getPassword().equals(password) && us.get(i).getUsername().equals(username) && us.get(i).getUser_type() == 2){
        		resp.sendRedirect("/login.jsp");
        	}
        }
        //resp.sendRedirect("/login.jsp");
         *
         */
        //	}
      }
    } catch (ServletException e) {
      e.printStackTrace();
    } finally {
      pm.close();
    }
  }
Пример #14
0
  /**
   * This method lists all the entities inserted in datastore. It uses HTTP GET method and paging
   * support.
   *
   * @return A CollectionResponse class containing the list of all entities persisted and a cursor
   *     to the next page.
   * @throws UnauthorizedException
   */
  @ApiMethod(
      name = "findAll",
      scopes = {Config.EMAIL_SCOPE},
      clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID})
  public CollectionResponse<ServiceResponse> findAll(
      @Named("_name") String _name,
      @Nullable @Named("cursor") String cursorString,
      @Nullable @Named("limit") Integer limit,
      User user)
      throws UnauthorizedException {
    if (user == null) {
      throw new UnauthorizedException("UnauthorizedException # User is Null.");
    }
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    if (limit == null) {
      limit = 10;
    }
    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(limit);
    if (cursorString != null) {
      fetchOptions.startCursor(Cursor.fromWebSafeString(cursorString));
    }
    Query q = new Query(_name);
    q.addSort("_updatedAt", SortDirection.DESCENDING);
    PreparedQuery pq = datastore.prepare(q);
    QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);

    List<ServiceResponse> responses = new ArrayList<ServiceResponse>();
    ServiceResponse res = null;
    for (Entity entity : results) {
      res = new ServiceResponse();
      // TODO add properties from entity to service response
      res.set_id(entity.getKey().getId());

      res.set_createdAt((Date) entity.getProperty(_createdAt));
      res.set_createdBy((String) entity.getProperty(_createdBy));

      res.set_upatedAt((Date) entity.getProperty(_updatedAt));
      res.set_updatedBy((String) entity.getProperty(_updatedBy));

      res.set_status((String) entity.getProperty(_status));

      Text dataText = (Text) entity.getProperty(data);
      res.setData(dataText.getValue());

      responses.add(res);
    }

    cursorString = results.getCursor().toWebSafeString();

    return CollectionResponse.<ServiceResponse>builder()
        .setItems(responses)
        .setNextPageToken(cursorString)
        .build();
  }
  /**
   * Counts the rows of the specified table
   *
   * @param searchIn the kind of entity (table) to search in
   * @param parent search for all entities with this parent
   * @param filters all properties to search for
   * @return number of rows
   */
  public static int count(String searchIn, Key parent, FilterWrapper... filters) {
    Query query = new Query(searchIn);
    query.setKeysOnly();

    if (parent != null) {
      query.setAncestor(parent);
    }

    setFilterProperties(query, filters);

    PreparedQuery preparedQuery = mDatastore.prepare(query);
    return preparedQuery.countEntities(FetchOptions.Builder.withDefaults());
  }
Пример #16
0
 @Override
 public Iterator<String> getAllEntityKeys(Class<?> entityClass, String lastKey) {
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
   com.google.appengine.api.datastore.Query q =
       new com.google.appengine.api.datastore.Query(entityClass.getName());
   q.setKeysOnly();
   if (lastKey != null) {
     q.addFilter("name", FilterOperator.GREATER_THAN, lastKey);
   }
   PreparedQuery pq = datastore.prepare(q);
   FetchOptions fetchOptions = FetchOptions.Builder.withOffset(0);
   return new ExtractingKeyIterable(pq.asIterator(fetchOptions));
 }
Пример #17
0
 @Test
 public void testStrFilter() {
   Query q = new Query(kindName);
   q.setAncestor(rootKey);
   Query.Filter filter =
       Query.CompositeFilterOperator.and(
           new FilterPredicate("stringData", Query.FilterOperator.LESS_THAN, "qqq"),
           new FilterPredicate("stringData", Query.FilterOperator.GREATER_THAN, "mmm"));
   q.setFilter(filter);
   q.addSort("stringData", Query.SortDirection.ASCENDING);
   assertEquals(2, service.prepare(q).countEntities(fo));
   List<Entity> elist = service.prepare(q).asList(fo);
   assertEquals(Arrays.asList("abc", "xyz", "mno"), elist.get(0).getProperty("stringData"));
   assertEquals(Arrays.asList("ppp", "iii", "ddd"), elist.get(1).getProperty("stringData"));
 }
Пример #18
0
 /** Google issueId:1458158 */
 @Test
 public void testIntFilter() {
   Query q = new Query(kindName);
   Query.Filter filter =
       Query.CompositeFilterOperator.and(
           new FilterPredicate("intData1", Query.FilterOperator.LESS_THAN, 20),
           new FilterPredicate("intData1", Query.FilterOperator.GREATER_THAN, 1),
           new FilterPredicate("intData1", Query.FilterOperator.EQUAL, null));
   q.setFilter(filter);
   q.addSort("intData1", Query.SortDirection.ASCENDING);
   q.setAncestor(rootKey);
   assertEquals(1, service.prepare(q).countEntities(fo));
   List<Entity> elist = service.prepare(q).asList(fo);
   assertEquals(Arrays.asList(1L, 10L, null), elist.get(0).getProperty("intData1"));
 }
  /**
   * Get all entities with the specified parent and properties
   *
   * @param searchIn what kind of entity (table) to search in
   * @param parent search for all entities with this parent
   * @param filters all properties to search for
   * @return an iterable of all found entities with the specified parent
   */
  public static Iterable<Entity> getEntities(
      String searchIn, Key parent, FilterWrapper... filters) {
    Query query = new Query(searchIn);

    // Parent
    if (parent != null) {
      query.setAncestor(parent);
    }

    setFilterProperties(query, filters);

    PreparedQuery preparedQuery = mDatastore.prepare(query);

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

      Transaction txn = datastore.beginTransaction();

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

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

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

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

        String dire = "http://mentoriasetsit.appspot.com?action=activate";
        resp.sendRedirect(dire);
      }
    } catch (Exception e) {
      LOG.warning("Exception in ActivateAccount: " + e.getMessage());
      e.printStackTrace();
    }
  }
  @Test
  public void testOrderOfReturnedResultsIsSameAsOrderOfElementsInInStatementWhenUsingKeysOnly()
      throws Exception {
    Entity b = createEntity("Product", 1).withProperty("name", "b").store();

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

    Query query =
        new Query("Product")
            .setKeysOnly()
            .setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("a", "b")));
    assertResultsInOrder(query, a, b);

    query = query.setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("b", "a")));
    assertResultsInOrder(query, b, a);
  }
  public List<EventTemplate> getAllEventTemplatesKeys() {
    Query q = new Query("EventTemplate");
    q.addSort("name");
    PreparedQuery pq = ds.prepare(q);

    List<EventTemplate> temps = new ArrayList<EventTemplate>();
    String name = null;
    String id = null;
    for (Entity result : pq.asIterable()) {
      name = (String) result.getProperty("name");
      id = result.getKey().getName();
      EventTemplate et = new EventTemplate(id);
      et.setName(name);
      temps.add(et);
      et = null;
    }
    return temps;
  }
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    System.out.println("Frontend started!");

    ServletOutputStream os = res.getOutputStream();

    Object masterSeedObject = req.getParameter("masterSeed");
    if (masterSeedObject == null) {
      os.print("No masterSeed specified!");
      return;
    }
    int masterSeed = (Integer.parseInt(masterSeedObject.toString()));

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query q = new Query("Decision");
    q.addFilter("masterSeed", Query.FilterOperator.EQUAL, masterSeed);
    PreparedQuery pq = datastore.prepare(q);
    ArrayList<String> clazzes = new ArrayList<String>();
    ArrayList<Float> decisions = new ArrayList<Float>();
    boolean firstTime = true;
    int index = 0;
    for (Entity entity : pq.asIterable()) {
      String[] pairs = ((Text) entity.getProperty("decision")).getValue().split("\n");
      for (String pair : pairs) {
        String[] s = pair.split(",");
        if (firstTime) {
          clazzes.add(s[0]);
          decisions.add(Float.parseFloat(s[1]));
        } else {
          decisions.set(index, Float.parseFloat(s[1]) + decisions.get(index));
        }
      }
      ++index;
      firstTime = false;
    }

    // output the data
    int length = clazzes.size();
    for (int i = 0; i < length; ++i) {
      os.print(clazzes.get(i) + "," + decisions.get(i) + "\n");
    }
    System.out.println("Frontend terminating!");
  }
  /** Make a new Query object that is exactly like the old. Too bad Query isn't Cloneable. */
  protected com.google.appengine.api.datastore.Query cloneRawQuery(
      com.google.appengine.api.datastore.Query orig) {
    com.google.appengine.api.datastore.Query copy =
        new com.google.appengine.api.datastore.Query(orig.getKind(), orig.getAncestor());

    for (FilterPredicate filter : orig.getFilterPredicates())
      copy.addFilter(filter.getPropertyName(), filter.getOperator(), filter.getValue());

    for (SortPredicate sort : orig.getSortPredicates())
      copy.addSort(sort.getPropertyName(), sort.getDirection());

    // This should be impossible but who knows what might happen in the future
    if (orig.isKeysOnly()) copy.setKeysOnly();

    return copy;
  }
Пример #25
0
  public String getResultado() throws EntityNotFoundException {
    Query q = new Query("Person");
    UserService userService = ServiceLocator.getUserService();
    q.addFilter(
        "user", Query.FilterOperator.EQUAL, ServiceLocator.getUserService().getCurrentUser());

    StringBuffer resultado = new StringBuffer();
    Iterator<Entity> iterator = ServiceLocator.getPersistenceService().queryIterator(q);
    if (!iterator.hasNext()) {
      resultado.append("\nNo records found.");
    } else {
      while (iterator.hasNext()) {
        Entity record = iterator.next();

        resultado.append("\n" + record.getProperties());
      }
    }

    return resultado.toString();
  }
  /**
   * Searches for an existing entity
   *
   * @param searchIn what kind of entity to search in
   * @param parent the parent of the entity to find, set to null to skip
   * @param onlyKeys will only retrieve keys for the found entity
   * @param filters property name and values to search for
   * @return found entity, null if none or more than 1 was found
   */
  private static Entity getSingleEntity(
      String searchIn, Key parent, boolean onlyKeys, FilterWrapper... filters) {
    Query query = new Query(searchIn);

    if (onlyKeys) {
      query.setKeysOnly();
    }

    setFilterProperties(query, filters);

    if (parent != null) {
      query.setAncestor(parent);
    }

    try {
      return mDatastore.prepare(query).asSingleEntity();
    } catch (TooManyResultsException e) {
      // Does nothing
    }
    return null;
  }
Пример #27
0
  public Object process(
      JSONObject server_jso, String method_name, JSONObject client_jso, JSONObject return_jso)
      throws aMethodException, JSONException {
    String why = "";
    boolean valid = true;
    JSONObject arg = client_jso.getJSONObject("arg");
    String county_code = arg.optString("county_code");
    JSONObject divs = new JSONObject();
    return_jso.put("county_code", county_code).put("divs", divs);

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Query q = new Query("div");
    q.setFilter(new Query.FilterPredicate("county_code", Query.FilterOperator.EQUAL, county_code));

    for (Entity found : ds.prepare(q).asIterable()) {
      JSONObject div = new JSONObject();
      xUtility.EntityToJSO(found, div);
      divs.put((String) found.getProperty("ncode"), div);
    }
    return_jso.put("valid", valid).put("why", why);
    return this.getServiceContext().doNextProcess();
  }
  /**
   * Get all entities (with only keys) with the specified parent and properties
   *
   * @param searchIn what kind of entity (table) to search in
   * @param parent search for all entities with this parent
   * @param filters all properties to search for
   * @return an array list of all found entities with the specified parent
   */
  public static List<Key> getKeys(String searchIn, Key parent, FilterWrapper... filters) {
    Query query = new Query(searchIn);

    query.setKeysOnly();

    // Parent
    if (parent != null) {
      query.setAncestor(parent);
    }

    // Search by properties
    setFilterProperties(query, filters);

    PreparedQuery preparedQuery = mDatastore.prepare(query);

    ArrayList<Key> keys = new ArrayList<>();
    for (Entity entity : preparedQuery.asIterable()) {
      keys.add(entity.getKey());
    }

    return keys;
  }
Пример #29
0
  public static List<StorageNode> getStorageNodesInFolder(String path, Owner owner) {

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

    ArrayList<StorageNode> nodes = new ArrayList<StorageNode>();

    String folderPath = PathHelper.getFolderpath(path);

    // Read folders
    Query q = new Query("Folder");
    q.addFilter("path", FilterOperator.GREATER_THAN_OR_EQUAL, path);
    q.addFilter("path", FilterOperator.LESS_THAN, path + "\ufffd");
    q.addFilter("ownerId", FilterOperator.EQUAL, owner.getId());

    PreparedQuery pq = ds.prepare(q);
    List<Entity> results = pq.asList(FetchOptions.Builder.withLimit(99999));
    for (Entity e : results) {
      Folder f = new Folder();
      ReflectionHelper.setPropertiesFromEntity(Folder.class, f, e);

      log.debug("Folder compare: {} =?= {}", PathHelper.getFolderpath(f.getPath()), folderPath);
      if (PathHelper.getFolderpath(f.getPath()).equals(folderPath)) {
        nodes.add(f);
      }
    }

    // Read files
    Query q2 = new Query("File");
    q2.addFilter("path", FilterOperator.GREATER_THAN_OR_EQUAL, path);
    q2.addFilter("path", FilterOperator.LESS_THAN, path + "\ufffd");
    q2.addFilter("ownerId", FilterOperator.EQUAL, owner.getId());

    PreparedQuery pq2 = ds.prepare(q);
    List<Entity> results2 = pq2.asList(FetchOptions.Builder.withLimit(99999));
    for (Entity e : results2) {
      File f = new File();
      ReflectionHelper.setPropertiesFromEntity(File.class, f, e);

      log.debug("File compare: {} =?= {}", PathHelper.getFolderpath(f.getPath()), folderPath);
      if (PathHelper.getFolderpath(f.getPath()).equals(folderPath)) {

        nodes.add(f);
      }
    }

    return nodes;
  }
Пример #30
0
 @Override
 public List<EprSpectrModel> getEprSpectrs(QueryEsrSpectrModel q) {
   ArrayList<EprSpectrModel> vRet = new ArrayList<EprSpectrModel>();
   DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
   Query query = new Query(q.loc + EprSpectrModel.class.getSimpleName());
   // if (q.bDate) {
   if (q.bAsc) {
     query = query.addSort(EprSpectr.DATE, Query.SortDirection.ASCENDING);
   } else {
     query = query.addSort(EprSpectr.DATE, Query.SortDirection.DESCENDING);
   }
   int count = q.skip + 1;
   for (Entity esrSpecEntity :
       datastoreService
           .prepare(query)
           .asIterable(FetchOptions.Builder.withLimit(q.limit).offset(q.skip))) {
     EprSpectr anek = new EprSpectr(esrSpecEntity);
     EprSpectrModel anekModel = anek.getEprSpectrModel();
     // anekModel.num = count++;
     vRet.add(anekModel);
   }
   // }
   return vRet;
 }