示例#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();
      }
    }
  }
示例#2
0
  public static List<Reward> execute(Long aSurveyId) {
    PersistenceManager pm = null;
    List<Reward> results = null;
    try {
      pm = PMF.get().getPersistenceManager();
      Query query = null;
      try {
        query = pm.newQuery(Reward.class);
        query.setFilter("surveyId==surveyIdParam");
        query.declareParameters("long surveyIdParam");

        query.setOrdering("used ASC");

        results = (List<Reward>) query.execute(aSurveyId);

        // Touch object to get data.  Size method triggers the underlying database call.
        results.size();
      } finally {
        if (query != null) {
          query.closeAll();
        }
      }
    } finally {
      if (pm != null) {
        pm.close();
      }
    }
    return results;
  }
示例#3
0
  /**
   * searches for users that match the non-null params
   *
   * @return
   */
  @SuppressWarnings("unchecked")
  public List<User> searchUser(
      String username,
      String emailAddress,
      String orderByField,
      String orderByDir,
      String cursorString) {
    PersistenceManager pm = PersistenceFilter.getManager();
    javax.jdo.Query query = pm.newQuery(User.class);
    StringBuilder filterString = new StringBuilder();
    StringBuilder paramString = new StringBuilder();
    Map<String, Object> paramMap = null;
    paramMap = new HashMap<String, Object>();

    appendNonNullParam("userName", filterString, paramString, "String", username, paramMap);
    appendNonNullParam("emailAddress", filterString, paramString, "String", emailAddress, paramMap);

    if (orderByField != null) {
      String ordering = orderByDir;
      if (ordering == null) {
        ordering = "asc";
      }
      query.setOrdering(orderByField + " " + ordering);
    }
    if (filterString.length() > 0) {
      query.setFilter(filterString.toString());
      query.declareParameters(paramString.toString());
    }

    prepareCursor(cursorString, query);
    List<User> results = (List<User>) query.executeWithMap(paramMap);
    return results;
  }
示例#4
0
文件: DB.java 项目: ander1dw/blog
 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();
 }
示例#5
0
 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   HttpSession session = req.getSession();
   PersistenceManager p = PMF.get().getPersistenceManager();
   String date = req.getParameter("Value");
   Query q1 = p.newQuery(Schedule.class);
   q1.setFilter("email == '" + session.getAttribute("emailid") + "' &&date == '" + date + "'");
   q1.setOrdering("listName asc");
   // System.out.println(session.getAttribute("emailid"));
   List<Schedule> schedule = (List<Schedule>) q1.execute();
   /*String json = new Gson().toJson(contents);*/
   ObjectMapper n = new ObjectMapper();
   String json = n.writeValueAsString(schedule);
   System.out.println(json);
   resp.setContentType("application/json");
   resp.setCharacterEncoding("UTF-8");
   resp.getWriter().write(json.toString());
   /*resp.getWriter().write(contents.toString());*/
   /*if (!contents.isEmpty()) {
       for (Content cont : contents) {
   	    String listname = cont.getListname();
   	    String listcontent = cont.getContent();
   	    String listdate = cont.getDate();
   	    resp.getWriter().write(listname);
   	    resp.getWriter().write(listcontent);
       }
   }*/
 }
示例#6
0
  public static String getUpdatesSince(long sinceId) {
    // First try to pull the response from the cache.
    @SuppressWarnings("unchecked")
    Map<Long, String> cachedQueries = (Map<Long, String>) cache.get(CACHED_QUERIES_KEY);
    Long sinceIdObj = Long.valueOf(sinceId);

    if (cachedQueries == null) {
      cachedQueries = new HashMap<Long, String>();
    } else if (cachedQueries.containsKey(sinceIdObj)) {
      log.info("Found query in the cache: " + sinceId);
      return cachedQueries.get(sinceIdObj);
    }

    // If we haven't cached this response, we must query for it.
    PersistenceManager pm = PMF.get().getPersistenceManager();
    JSONArray resultArray = new JSONArray();

    try {
      Query query = pm.newQuery(TrainUpdate.class);
      query.setOrdering("twitterId ASC");

      if (sinceId >= 0) {
        query.setFilter("twitterId > " + sinceId);
      }

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

      for (TrainUpdate update : updates) {
        JSONObject updateJson = update.getJSON();
        resultArray.put(updateJson);
      }

      // Append any updates that are stored in the cache to this result.
      @SuppressWarnings("unchecked")
      List<TrainUpdate> cachedUpdates = (List<TrainUpdate>) cache.get(CACHED_UPDATES_KEY);

      if (cachedUpdates != null) {
        log.info("Fetched cache with size of : " + cachedUpdates.size());

        for (TrainUpdate update : cachedUpdates) {
          if (update.getTwitterId() > sinceId) {
            JSONObject updateJson = update.getJSON();
            resultArray.put(updateJson);
          }
        }
      }
    } finally {
      pm.close();
    }

    // Finally cache the response.
    String result = resultArray.toString();
    cachedQueries.put(sinceIdObj, result);
    cache.put(CACHED_QUERIES_KEY, cachedQueries);

    return result;
  }
示例#7
0
  /**
   * Gets {@link Key}s of all the {@link Review}s for a {@link Dish}
   *
   * @param dishKey {@link Key} of the {@link Dish}
   * @return {@link Collection} of {@link Key} objects sorted from newest to oldest
   */
  @SuppressWarnings("unchecked")
  public static Collection<Key> getReviewKeysByDish(Key dishKey) {
    String query = "select key from " + Review.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setFilter("dish == :param");
    q.setOrdering("dateCreated desc");

    return (Collection<Key>) q.execute(dishKey);
  }
示例#8
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());
  }
示例#9
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;
  }
示例#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;
  }
示例#11
0
 @Override
 @SuppressWarnings("unchecked")
 public List<DictionaryEntry> getEntries() throws NotLoggedInException {
   checkLoggedIn();
   PersistenceManager pm = getPersistenceManager();
   try {
     Query query = pm.newQuery(PersistentDictionaryEntry.class, "user == u");
     query.declareParameters("com.google.appengine.api.users.User u");
     query.setOrdering("word");
     return convertToClientEntries((List<PersistentDictionaryEntry>) query.execute(getUser()));
   } finally {
     pm.close();
   }
 }
 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";
 }
示例#13
0
 @SuppressWarnings("unchecked")
 public List<Paciente> listAll() {
   List<Paciente> pacientes = new ArrayList<Paciente>();
   PersistenceManager pm = PMF.get().getPersistenceManager();
   Query q = pm.newQuery(Paciente.class);
   q.setOrdering("nome asc");
   try {
     List<Paciente> result = (List<Paciente>) q.execute();
     pacientes.addAll(result);
   } finally {
     pm.close();
   }
   return pacientes;
 }
示例#14
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;
    }
  }
示例#15
0
  public List<OGRFeature> listByExtentTypeCountry(
      Double x1,
      Double y1,
      String countryCode,
      String orderByCol,
      String orderByDirection,
      String cursorString) {
    PersistenceManager pm = PersistenceFilter.getManager();
    javax.jdo.Query query = pm.newQuery(OGRFeature.class);
    StringBuilder filterString = new StringBuilder();
    StringBuilder paramString = new StringBuilder();
    Map<String, Object> paramMap = null;
    paramMap = new HashMap<String, Object>();

    appendNonNullParam("x1", filterString, paramString, "Double", x1, paramMap, LTE_OP);
    appendNonNullParam(
        "featureType",
        filterString,
        paramString,
        "String",
        FeatureType.SUB_COUNTRY_OTHER,
        paramMap,
        EQ_OP);
    appendNonNullParam(
        "countryCode", filterString, paramString, "String", countryCode, paramMap, EQ_OP);

    query.setFilter(filterString.toString());
    query.declareParameters(paramString.toString());

    if (orderByCol != null && orderByDirection != null)
      query.setOrdering(orderByCol + " " + orderByDirection);

    prepareCursor(cursorString, query);
    @SuppressWarnings("unchecked")
    List<OGRFeature> resultsGTE = (List<OGRFeature>) query.executeWithMap(paramMap);
    List<OGRFeature> results = new ArrayList<OGRFeature>();
    for (OGRFeature item : resultsGTE) {
      Double[] boundingBox = item.getBoundingBox();
      if (boundingBox[0] < x1
          && boundingBox[1] > y1
          && boundingBox[2] > x1
          && boundingBox[3] < y1) {
        results.add(item);
      }
    }

    return results;
  }
示例#16
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;
    }
  }
示例#17
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;
    }
  }
示例#18
0
 public String[] getStocks() throws NotLoggedInException {
   checkLoggedIn();
   PersistenceManager pm = getPersistenceManager();
   List<String> symbols = new ArrayList<String>();
   try {
     Query q = pm.newQuery(Stock.class, "user == u");
     q.declareParameters("com.google.appengine.api.users.User u");
     q.setOrdering("createDate");
     List<Stock> stocks = (List<Stock>) q.execute(getUser());
     for (Stock stock : stocks) {
       symbols.add(stock.getSymbol());
     }
   } finally {
     pm.close();
   }
   return (String[]) symbols.toArray(new String[0]);
 }
示例#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;
  }
示例#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);
 }
  public ServiceResult<List<Page>> getListPageFromUsername(String username) {
    username = DatabaseUtils.preventSQLInjection(username);
    ServiceResult<List<Page>> result = new ServiceResult<List<Page>>();
    PersistenceManager pm = PMF.get().getPersistenceManager();

    if (username == null || username.equals("")) {
      result.setMessage(Global.messages.getString("cannot_handle_with_null"));
      return result;
    }
    boolean isNotFound = false;
    UserInfo userInfo = null;
    try {
      userInfo = pm.getObjectById(UserInfo.class, username);
    } catch (JDOObjectNotFoundException e) {
      isNotFound = true;
    } catch (NucleusObjectNotFoundException e) {
      isNotFound = true;
    }

    if (isNotFound || userInfo == null) {
      // Not found userinfo
      result.setMessage(Global.messages.getString("not_found") + " " + username);
    } else {
      Query query = pm.newQuery(Page.class);
      query.setFilter("username == us");
      query.declareParameters("String us");
      query.setOrdering("date_post DESC");
      List<Page> listPages = (List<Page>) query.execute(username);

      if (listPages.size() > 0) {
        result.setOK(true);
        result.setMessage(
            String.format(
                Global.messages.getString("get_pages_by_username_successfully"), username));
        result.setResult(listPages);
      } else {
        result.setOK(false);
        result.setMessage(
            String.format(Global.messages.getString("get_pages_by_username_fail"), username));
      }
    }
    pm.close();
    return result;
  }
  /** @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;
    }
  }
示例#23
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();
 }