Ejemplo n.º 1
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    final PersistenceManager pm = PMF.get().getPersistenceManager();
    final Query q = pm.newQuery(User.class);

    if (req.getParameter("dni") != null) {

      String dni = req.getParameter("dni");
      q.setOrdering("key descending");
      q.setRange(0, 10);

      try {

        @SuppressWarnings("unchecked")
        List<User> usuarios = (List<User>) q.execute(dni);
        req.setAttribute("user", usuarios);
        RequestDispatcher rd =
            getServletContext().getRequestDispatcher("/WEB-INF/jsp/verUsuarios.jsp");
        rd.forward(req, resp);

      } catch (Exception e) {
        System.out.println(e);
      } finally {
        q.closeAll();
        pm.close();
      }

    } else {
      q.setOrdering("key descending");
      q.setRange(0, 10);

      try {
        @SuppressWarnings("unchecked")
        List<User> usuarios = (List<User>) q.execute();
        req.setAttribute("user", usuarios);
        RequestDispatcher rd =
            getServletContext().getRequestDispatcher("/WEB-INF/jsp/verUsuarios.jsp");
        rd.forward(req, resp);
      } catch (Exception e) {
        System.out.println(e);
      } finally {
        q.closeAll();
        pm.close();
      }
    }
  }
Ejemplo n.º 2
0
  /**
   * Get a User {@link Key} for a facebook id
   *
   * @param facebookId
   * @return the user {@link Key} or null
   */
  @SuppressWarnings("unchecked")
  public static Key getUserForFacebookId(String facebookId) {

    // check if APIKey -> TDUser Key found in cache
    if (MemcacheServiceFactory.getMemcacheService().contains(facebookId)) {
      // if so, return from cache
      return (Key) MemcacheServiceFactory.getMemcacheService().get(facebookId);
    } else {
      // query for matching user
      final String queryString = "SELECT key FROM " + TDUser.class.getName();
      final Query q = PMF.get().getPersistenceManager().newQuery(queryString);
      q.setFilter("facebookId == :p");
      q.setRange("0,1");

      final List<Key> keys = (List<Key>) q.execute(facebookId);

      final Key result = (keys.size() > 0 ? keys.get(0) : null);

      if (null != result) {
        // put ApiKey -> TDUser Key map in cache
        MemcacheServiceFactory.getMemcacheService().put(facebookId, result);
      }

      // return the found key
      return result;
    }
  }
Ejemplo n.º 3
0
  /**
   * Demonstrates how to use the cursor to be able to pass over an complete set of data
   *
   * @param pm Persistence manager instance to use - let open at the end to allow possible object
   *     updates later
   * @param cursorString Representation of a cursor, to be used to get the next set of data to
   *     process
   * @param range Number of data to process at this particular stage
   * @param defaultSource Value to apply to any Demand instance without a default value
   * @return New representation of the cursor, ready for a next process call
   */
  @SuppressWarnings("unchecked")
  public static String updateSource(
      PersistenceManager pm, String cursorString, int range, Source defaultSource) {

    Query query = null;
    try {
      query = pm.newQuery(Demand.class);
      if (cursorString != null) {
        Map<String, Object> extensionMap = new HashMap<String, Object>();
        extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, Cursor.fromWebSafeString(cursorString));
        query.setExtensions(extensionMap);
      }
      query.setRange(0, range);
      List<Demand> results = (List<Demand>) query.execute();
      if (results.iterator().hasNext()) {
        for (Demand demand : results) {
          // Initialize the new field if necessary. By checking first that the field is null, we
          // allow this migration to be safely run multiple times.
          if (demand.getSource() == null) {
            demand.setSource(defaultSource);
            pm.makePersistent(demand);
          }
        }
        cursorString = JDOCursorHelper.getCursor(results).toWebSafeString();
      } else {
        // no results
        cursorString = null;
      }
    } finally {
      query.closeAll();
    }
    return cursorString;
  }
Ejemplo n.º 4
0
  /**
   * Gives friend (friendid) permission to given target to user's (uid) data
   *
   * @param pm
   * @param uid
   * @param friendid
   * @param target
   * @return
   */
  @SuppressWarnings("unchecked")
  public static boolean addUserToCircle(
      PersistenceManager pm, String uid, String friendid, int target) {

    if (logger.isLoggable(Level.FINER)) {
      logger.log(
          Level.FINER,
          "Adding user to circle: uid=" + uid + ", friendid=" + friendid + ", target=" + target);
    }

    boolean ok = true;

    // check if permission already found
    Query q = pm.newQuery(Circle.class);
    q.setFilter("openId == openIdParam && friendId == friendIdParam && target == targetParam");
    q.declareParameters(
        "java.lang.String openIdParam, java.lang.String friendIdParam, java.lang.Integer targetParam");
    q.setRange(0, 1);
    List<Circle> list = (List<Circle>) q.execute(uid, friendid, target);

    // if no previous permissions found
    if (list.size() != 0) {
      pm.deletePersistent(list.get(0));
      ok = true;
    }

    // remove users from cache
    // TODO needs improving
    WeekCache cache = new WeekCache();
    cache.removeUsers();

    return ok;
  }
Ejemplo n.º 5
0
 public static List<?> getList(
     Class<?> cls, String ordering, int start, int stop, PersistenceManager pm) {
   Query query = pm.newQuery(cls);
   query.setOrdering(ordering);
   query.setRange(start, stop);
   return (List<?>) query.execute();
 }
Ejemplo n.º 6
0
  /**
   * Returns the most recent <code>numDishes</code> {@link Dish}es added
   *
   * @param numDishes number of {@link Dish}es to return
   * @return {@link List} of {@link Dish}es ordered from newest to oldest
   */
  @SuppressWarnings("unchecked")
  public static Set<Dish> getNewestDishes(int numDishes) {
    final String query = "SELECT key FROM " + Dish.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setOrdering("dateCreated desc");
    q.setRange("0, " + numDishes);

    return Datastore.get((Collection<Key>) q.execute());
  }
Ejemplo n.º 7
0
  /**
   * Find {@link Source}s by name with a limit
   *
   * @param name - the source's name
   * @param limit - limit results
   * @return a {@link Set} of related {@link Source}s
   */
  @SuppressWarnings("unchecked")
  public static Set<Source> searchSourcebyName(String name, int limit) {

    final String queryString = "SELECT key FROM " + Source.class.getName();
    final Query q = PMF.get().getPersistenceManager().newQuery(queryString);
    q.setFilter("name == :p");
    q.setRange("0, " + limit);

    return Datastore.get(new HashSet<Key>((List<Key>) q.execute(name.toLowerCase())));
  }
Ejemplo n.º 8
0
  public static Query setRange(Query query, int iterTotal, int highCount, int lowCount) {

    if (iterTotal > 10) {

      // handle the normal situation first
      if ((lowCount > 0) && (lowCount <= highCount)) {
        if (highCount - lowCount > 50) {
          query.setRange((lowCount - 1), (lowCount + 50));
        } else {
          query.setRange(lowCount - 1, highCount);
        }
      } else {
        query.setRange(0, 10);
      }

    } else {
      query.setRange(0, iterTotal);
    }
    return query;
  }
Ejemplo n.º 9
0
  /**
   * Search tags by name and types
   *
   * @param stringTag name of a single tag
   * @param types {@link Set} of tag types
   * @param limit maximum number of results
   * @return {@link Set} of {@link Tag}s
   */
  @SuppressWarnings("unchecked")
  public static Set<Tag> searchTagsByNameType(String stringTag, Set<Integer> types, int limit) {

    final String queryString = "SELECT key FROM " + Tag.class.getName();
    final Query q = PMF.get().getPersistenceManager().newQuery(queryString);
    q.setFilter("searchTerms.contains(:searchTerm) && :typeParam.contains(type)");
    q.setRange("0, " + limit);

    return Datastore.get(
        new HashSet<Key>((Collection<Key>) q.execute(stringTag.toLowerCase(), types)));
  }
Ejemplo n.º 10
0
  /**
   * Gets the top <code>numDishes</code> {@link Dish}es ranked from most to least positive reviews
   *
   * @param numDishes number of {@link Dish}es to return
   * @return {@link List} of {@link Dish}es
   */
  @SuppressWarnings("unchecked")
  public static List<Dish> getTopDishes(int numDishes) {
    final String query = "SELECT key FROM " + Dish.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setOrdering("posReviews desc");
    q.setRange("0," + numDishes);

    final Set<Dish> results = Datastore.get((Collection<Key>) q.execute());
    final List<Dish> toReturn = new ArrayList<Dish>(results);
    Collections.sort(toReturn, new DishPosReviewsComparator());

    return toReturn;
  }
Ejemplo n.º 11
0
  /**
   * Gets the top <code>numUsers</code> sorted by most to least ratings.
   *
   * @param numUsers number of {@link TDUser}s to return
   * @return {@link List} of {@link TDUser}s
   */
  @SuppressWarnings("unchecked")
  public static List<TDUser> getTopUsers(int numUsers) {
    final String query = "SELECT key FROM " + TDUser.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setOrdering("numReviews desc");
    q.setRange("0, " + numUsers);

    final Set<TDUser> results = Datastore.get((Collection<Key>) q.execute());
    final List<TDUser> toReturn = new ArrayList<TDUser>(results);
    // Collections.sort(toReturn, )

    return toReturn;
  }
Ejemplo n.º 12
0
  /**
   * Get a {@link Key} of a {@link TDUser} given the {@link User} ID.
   *
   * @param userId the user ID from a {@link User} object.
   * @return the {@link Key} of this {@link TDUser}.
   */
  @SuppressWarnings("unchecked")
  public static Key getUserKeyByUserId(String userId) {
    final String queryString = "SELECT key FROM " + TDUser.class.getName();
    final Query query = PMF.get().getPersistenceManager().newQuery(queryString);
    query.setFilter("userID == :param");
    query.setRange("0, 1");

    final Set<Key> results = new HashSet<Key>((List<Key>) query.execute(userId));

    if (null != results && !results.isEmpty()) {
      return results.iterator().next();
    }
    return null;
  }
 public String execute(Map context, HttpServletRequest req, HttpServletResponse resp)
     throws Exception {
   PersistenceManager pm = PersistenceManagerContextHolder.get();
   long pageId = Long.parseLong(req.getParameter("id"));
   context.put("page", pm.getObjectById(Page.class, pageId));
   Query query = pm.newQuery(DataPoint.class);
   query.setFilter("pageId == pageIdParam");
   query.setOrdering("date desc");
   query.declareParameters("Long pageIdParam");
   query.setRange(0, 200);
   List<DataPoint> points = (List<DataPoint>) query.execute(pageId);
   context.put("points", points);
   return "list_top_data_points";
 }
Ejemplo n.º 14
0
  /**
   * Gets the top <code>numRestaurantss</code> {@link Restaurant}s ranked from most to least
   * positive reviews <br>
   * <b>Note: this does not actually return the top X restaurants, just a random X restaurants!</b>
   *
   * @param numRestaurants number of {@link Restaurant}s to return
   * @return {@link List} of {@link Restaurant}s
   */
  @SuppressWarnings("unchecked")
  public static List<Restaurant> getTopRestaurants(int numRestaurants) {
    final String query = "SELECT key FROM " + Restaurant.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    // TODO: return a query that actually chooses the X highest rated
    // restaurants
    // q.setOrdering("posReviews desc");
    q.setRange("0," + numRestaurants);

    final Set<Restaurant> results = Datastore.get((Collection<Key>) q.execute());
    final List<Restaurant> toReturn = new ArrayList<Restaurant>(results);
    Collections.sort(toReturn, new RestaurantPosReviewsComparator());

    return toReturn;
  }
Ejemplo n.º 15
0
  /**
   * Gets the latest {@link Review} {@link Key} for a given {@link TDUser} {@link Key} and {@link
   * Dish} {@link Key}.
   *
   * @param userKey {@link Key} of the {@link TDUser}
   * @param dishKey {@link Key} of the {@link Dish}
   * @return {@link Key} of the {@link Review} or <code>null</code> if none found.
   */
  @SuppressWarnings("unchecked")
  public static Key getLatestReviewKeyByUserDish(Key userKey, Key dishKey) {
    final String queryString = "SELECT key FROM " + Review.class.getName();
    final Query q = PMF.get().getPersistenceManager().newQuery(queryString);
    q.setFilter("dish == :dishKeyParam && creator == :userKeyParam");
    q.setOrdering("dateCreated desc"); // sort newest to oldest
    q.setRange("0,1"); // only the newest one review
    final Set<Key> revKeys = new HashSet<Key>((Collection<Key>) q.execute(dishKey, userKey));

    if (!revKeys.isEmpty()) {
      return revKeys.iterator().next();
    } else {
      return null;
    }
  }
Ejemplo n.º 16
0
  /**
   * Gets the {@link Key} of the latest {@link Review} submitted by a {@link TDUser} .
   *
   * @param userKey {@link Key} of the {@link TDUser}
   * @return {@link Key} of the {@link Review}
   */
  @SuppressWarnings("unchecked")
  public static Key getLatestReviewKeyByUser(Key userKey) {
    String query = "select key from " + Review.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setFilter("creator == :param");
    q.setOrdering("dateCreated desc");
    q.setRange("0,1");

    List<Key> results = (List<Key>) q.execute(userKey);

    if (!results.isEmpty()) {
      return results.get(0);
    } else {
      return null;
    }
  }
Ejemplo n.º 17
0
  /**
   * Search through all {@link Tag}s given an array of {@link String} search terms
   *
   * @param queryWords array of {@link String} terms to search with
   * @param maxResults maximum number of results
   * @return list of Tags matching the search terms
   */
  @SuppressWarnings("unchecked")
  public static Set<Tag> searchTags(String[] queryWords, int maxResults) {
    // TODO: can this be replaced by a generic searchItems somehow?
    // Using a TDSearchable Interface would work

    final String queryString = "SELECT key FROM " + Tag.class.getName();
    final Query query = PMF.get().getPersistenceManager().newQuery(queryString);
    query.setFilter("searchTerms.contains(:searchParam)");
    query.setRange(0, maxResults);

    if (queryWords.length > 0) {
      return Datastore.get((Collection<Key>) query.execute(Arrays.asList(queryWords)));
    }

    return new HashSet<Tag>();
  }
Ejemplo n.º 18
0
  /**
   * Get the {@link Key} of the first {@link Review} written about a {@link Dish}.
   *
   * @param dishKey {@link Key} of the {@link Dish}
   * @return {@link Key} of the {@link Review}
   */
  @SuppressWarnings("unchecked")
  public static Key getFirstReviewKeyByDish(Key dishKey) {
    String query = "SELECT key FROM " + Review.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setFilter("dish == :param");
    q.setOrdering("dateCreated asc");
    q.setRange("0,1");

    List<Key> results = (List<Key>) q.execute(dishKey);

    if (!results.isEmpty()) {
      return results.get(0);
    } else {
      return null;
    }
  }
Ejemplo n.º 19
0
  /**
   * Gets the ID of the last pulled train update.
   *
   * @return the ID or -1 if there aren't any stored IDs.
   */
  public static long getLatestUpdateId() {
    StorageStats stats = getStorageStats();

    if (stats != null) {
      return stats.getLatestUpdateId();
    }

    // TODO: will stats ever be null?

    // TODO:  We should store the latest ID instead of querying for it.
    // That way we don't run into a situation where the data store gets cleared and we end up
    // pulling 200 updates.

    // Attempt to just pull the value out of the cache.
    // We assume that the latest updates will always live here.
    @SuppressWarnings("unchecked")
    List<TrainUpdate> cachedUpdates = (List<TrainUpdate>) cache.get(CACHED_UPDATES_KEY);

    if (cachedUpdates != null && !cachedUpdates.isEmpty()) {
      log.info("Fetched cache with size of : " + cachedUpdates.size());
      return cachedUpdates.get(cachedUpdates.size() - 1).getTwitterId();
    }

    // If no cached updates were found, we must query the datastore.

    long sinceId = -1;
    PersistenceManager pm = PMF.get().getPersistenceManager();

    try {
      Query query = pm.newQuery(TrainUpdate.class);
      query.setOrdering("date DESC");
      query.setRange(0, 1);

      @SuppressWarnings("unchecked")
      List<TrainUpdate> oldUpdates = (List<TrainUpdate>) query.execute();

      if (oldUpdates.size() > 0) {
        sinceId = oldUpdates.get(0).getTwitterId();
      }
    } finally {
      pm.close();
    }

    return sinceId;
  }
Ejemplo n.º 20
0
 private Collection<Tag> getTagCloud(PersistenceManager pm) {
   Query q = pm.newQuery(Tag.class, "count > 0");
   q.setOrdering("count desc");
   q.setRange(0, 15);
   List<Tag> tags = (List<Tag>) q.execute();
   if (tags.size() > 0) {
     long max = tags.get(0).getCount();
     float min = tags.get(tags.size() - 1).getCount();
     for (Tag t : tags) {
       // if all tags have same count, avoid divide-by-zero
       // Create a float scale between 1 and 1.8
       double scale = (max - min == 0 ? 1 : (t.getCount() - min) / (max - min) * .8 + 1);
       t.setScale(String.format("%.1fem", scale));
     }
   }
   // reorder tags alphabetically.
   return new TreeSet<Tag>(tags);
 }
Ejemplo n.º 21
0
  /** @return List of Public Places */
  @SuppressWarnings("unchecked")
  public List<Place> getPlacesPublic(Account account, String createdorder) {

    PersistenceManager pm = PMUtils.getPersistenceManager();
    try {

      // prepare query
      Query q = pm.newQuery(Place.class);
      q.setOrdering("type desc, createdOrder desc");
      q.setRange(0, account != null ? account.getFetchRows() : 20);
      q.declareImports("import com.hotf.server.model.Location.Type");

      List<Place> list;
      if (createdorder != null && createdorder.length() > 0) {

        // execute with filter
        q.declareParameters("String p_createdOrder");
        q.setFilter("type != null && type != 'START' && createdOrder >= p_createdOrder");
        String n = createdorder.toUpperCase();
        log.info("Getting more public places from the Datastore");
        list = (List<Place>) q.execute(n);

      } else {

        // execute without filter
        q.setFilter("type != null && type != 'START'");
        log.info("Getting public places from the Datastore");
        list = (List<Place>) q.execute();
      }

      return list;

    } catch (RuntimeException t) {

      log.severe(t.getMessage());

      // roll-back transactions and re-throw
      if (pm.currentTransaction().isActive()) {
        pm.currentTransaction().rollback();
      }

      throw t;
    }
  }
Ejemplo n.º 22
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.
   */
  @SuppressWarnings({"unchecked", "unused"})
  @ApiMethod(name = "listUser")
  public CollectionResponse<User> listUser(
      @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

    PersistenceManager mgr = null;
    Cursor cursor = null;
    List<User> execute = null;

    try {
      mgr = getPersistenceManager();
      Query query = mgr.newQuery(User.class);
      if (cursorString != null && cursorString != "") {
        cursor = Cursor.fromWebSafeString(cursorString);
        HashMap<String, Object> extensionMap = new HashMap<String, Object>();
        extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
        query.setExtensions(extensionMap);
      }

      if (limit != null) {
        query.setRange(0, limit);
      }

      execute = (List<User>) query.execute();
      cursor = JDOCursorHelper.getCursor(execute);
      if (cursor != null) cursorString = cursor.toWebSafeString();

      // Tight loop for fetching all entities from datastore and accomodate
      // for lazy fetch.
      for (User obj : execute) ;
    } finally {
      mgr.close();
    }

    return CollectionResponse.<User>builder()
        .setItems(execute)
        .setNextPageToken(cursorString)
        .build();
  }
Ejemplo n.º 23
0
  /**
   * Method to get the "default" user to use as an object's creator.
   *
   * @return {@link Key} of the "default" user
   */
  @SuppressWarnings("unchecked")
  public static Key getDefaultUser() {
    if (MemcacheServiceFactory.getMemcacheService().contains(UserConstants.DEFAULT_USER_EMAIL)) {
      return (Key)
          MemcacheServiceFactory.getMemcacheService().get(UserConstants.DEFAULT_USER_EMAIL);
    } else {
      final String queryString = "SELECT key FROM " + TDUser.class.getName();
      final Query q = PMF.get().getPersistenceManager().newQuery(queryString);
      q.setFilter("email == :p");
      q.setRange("0,1");

      final List<Key> keys = (List<Key>) q.execute(UserConstants.DEFAULT_USER_EMAIL);

      if (null != keys && !keys.isEmpty()) {

        final Key result = (Key) keys.get(0);
        MemcacheServiceFactory.getMemcacheService().put(UserConstants.DEFAULT_USER_EMAIL, result);

        return result;
      }
      return null;
    }
  }
Ejemplo n.º 24
0
 // TODO memcache!
 private List<Script> getRecentScripts(PersistenceManager pm) {
   Query query = pm.newQuery(Script.class);
   query.setOrdering("created desc");
   query.setRange(0, 10);
   return (List<Script>) query.execute();
 }
Ejemplo n.º 25
0
 public Object service() {
   List<JsonResult> matches = new ArrayList<JsonResult>();
   if (type.equals("ANY") || type.equals("ARTIST")) {
     this.term = this.term.toLowerCase().trim();
     List<Artist> artistResults = this.artistDao.getArtistsThatStartWith(term);
     for (Artist a : artistResults) {
       matches.add(
           new JsonResult(
               a.getKey(), "ARTIST", a.getName(), null, null, a.getArtistArtKey(), null, null));
     }
   }
   if (type.equals("ANY") || type.equals("ALBUM")) {
     this.term = this.term.toLowerCase().trim();
     List<GaeAlbumImpl> albumResults = null;
     PersistenceManager pm = GAEModel.get().getPersistenceManager();
     try {
       Query q = pm.newQuery(GaeAlbumImpl.class);
       try {
         q.setFilter("name >= beginsWithParam && name < beginsWithMaxParam");
         q.setRange(0, 5);
         q.declareParameters("String beginsWithParam, String beginsWithMaxParam");
         albumResults = (List<GaeAlbumImpl>) q.execute(term, term + "\ufffd");
         pm.detachCopyAll(albumResults);
       } finally {
         q.closeAll();
       }
     } finally {
       pm.close();
     }
     for (GaeAlbumImpl a : albumResults) {
       matches.add(
           new JsonResult(
               a.getKey(),
               "ALBUM",
               a.getArtistName(),
               a.getName(),
               null,
               a.getAlbumArtKey(),
               null,
               null));
     }
   }
   if (type.equals("ANY") || type.equals("TRACK")) {
     this.term = this.term.toLowerCase().trim();
     List<GaeTrackImpl> trackResults = null;
     PersistenceManager pm = GAEModel.get().getPersistenceManager();
     try {
       Query q = pm.newQuery(GaeTrackImpl.class);
       try {
         q.setRange(0, 10);
         q.setFilter("title >= beginsWithParam && title < beginsWithMaxParam");
         q.declareParameters("String beginsWithParam, String beginsWithMaxParam");
         trackResults = (List<GaeTrackImpl>) q.execute(term, term + "\ufffd");
         pm.detachCopyAll(trackResults);
       } finally {
         q.closeAll();
       }
     } finally {
       pm.close();
     }
     for (GaeTrackImpl t : trackResults) {
       matches.add(
           new JsonResult(
               t.getKey(),
               "TRACK",
               t.getArtistName(),
               t.getAlbumName(),
               t.getTitle(),
               null,
               t.getYoutubeLocation(),
               Integer.toString(t.getTrackNumber())));
     }
   }
   return matches;
 }