Example #1
1
  /**
   * Retrieves the access token used for interacting with Twitter.
   *
   * @return
   */
  public static AccessToken getAccessToken() {
    // Try to grab the token from the cache.
    StoredAccessToken storedToken = (StoredAccessToken) cache.get(ACCESS_TOKEN_KEY);

    if (storedToken != null) {
      return storedToken.getAccessToken();
    }

    // Now try to grab it from the datastore
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Extent<StoredAccessToken> extent = pm.getExtent(StoredAccessToken.class, false);

    try {
      Iterator<StoredAccessToken> itr = extent.iterator();
      storedToken = itr.next();

      // If the token was found, cache it and return.
      if (storedToken != null) {
        cache.put(ACCESS_TOKEN_KEY, storedToken);
        return storedToken.getAccessToken();
      }
    } finally {
      extent.closeAll();
      pm.close();
    }

    return null;
  }
Example #2
0
  private void persistNewsData(NodeList titles, NodeList links, NodeList descriptions) {
    // Persists news data feed.
    // Also clears out previously persisted news feed data

    PersistenceManager pm = PMF.get().getPersistenceManager();
    javax.jdo.Query query = pm.newQuery(NewsItem.class);
    Long res = query.deletePersistentAll();

    System.out.println("Datastore deleted  " + res + "records");

    pm = PMF.get().getPersistenceManager();

    try {
      for (int i = 1; i < titles.getLength(); i++) {
        NewsItem ni = new NewsItem();
        ni.setTitle(titles.item(i).getTextContent());
        ni.setLink(links.item(i).getTextContent());
        if (descriptions.item(i) != null) {
          ni.setDescription(new Text(descriptions.item(i).getTextContent()));
        }
        pm.makePersistent(ni);
      }
    } finally {
      pm.close();
    }
  }
Example #3
0
 @SuppressWarnings("unchecked")
 public static List<Access> getAccesses() {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   String query = "select from " + Access.class.getName();
   List<Access> accesses = (List<Access>) pm.newQuery(query).execute();
   return accesses;
 }
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String email = req.getParameter("email");
    String name = req.getParameter("name");
    String pwd = req.getParameter("pwd");
    String repwd = req.getParameter("repwd");
    PersistenceManager p = PMF.get().getPersistenceManager();
    Query q = p.newQuery(Users.class);
    q.setFilter("email == '" + email + "'");
    //	q.setFilter("email == '"+uname+"' && password == '"+passwd+"'");

    List<Users> exists = (List<Users>) q.execute();
    if (exists.isEmpty()) {
      try {
        System.out.println("inside try");

        /*req.getRequestDispatcher("/signup").forward(req, resp);*/
        resp.getWriter().write("sucess");
      } catch (Exception e) {
        System.out.println(e);
      }
    } else {
      System.out.println("inside else");
      System.out.println(email);
      resp.getWriter().write(email);
    }
  }
 public ServiceResult<Page> findPage(Long id, boolean isIncreaseView) {
   ServiceResult<Page> result = new ServiceResult<Page>();
   Page page = null;
   PersistenceManager pm = null;
   try {
     pm = PMF.get().getPersistenceManager();
     page = pm.getObjectById(Page.class, id);
     if (page == null) {
       result.setOK(false);
       result.setMessage(Global.messages.getString("no_page_found"));
     } else {
       result.setMessage(Global.messages.getString("page_found"));
       result.setOK(true);
       result.setResult(page);
       if (isIncreaseView) {
         page.setPage_view(page.getPage_view() + 1);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     result.setMessage(Global.messages.getString("find_page_fail"));
   } finally {
     try {
       pm.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return result;
 }
Example #6
0
  protected static StorageStats getStorageStats() {
    // Try to grab the token from the cache.
    StorageStats stats = (StorageStats) cache.get(STORAGE_STATS_KEY);

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

    // Now try to grab it from the datastore
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Extent<StorageStats> extent = pm.getExtent(StorageStats.class, false);

    try {
      Iterator<StorageStats> itr = extent.iterator();

      if (itr.hasNext()) {
        stats = itr.next();
      } else {
        stats = new StorageStats();
        pm.makePersistent(stats);
      }

      return stats;
    } finally {
      extent.closeAll();
      pm.close();

      cache.put(STORAGE_STATS_KEY, stats);
    }
  }
 public ServiceResult<Long> insertPage(Page page) {
   // updateFTSStuffForPage(page);
   page.updateFTS();
   ServiceResult<Long> result = new ServiceResult<Long>();
   PersistenceManager pm = PMF.get().getPersistenceManager();
   try {
     page = pm.makePersistent(page);
     if (page == null) {
       result.setMessage(Global.messages.getString("insert_page_fail"));
     } else {
       result.setResult(page.getId());
       result.setMessage(Global.messages.getString("insert_page_successfully"));
       result.setOK(true);
     }
   } catch (Exception e) {
     e.printStackTrace();
     result.setMessage(Global.messages.getString("insert_page_fail"));
   } finally {
     try {
       pm.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return result;
 }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String button = req.getParameter("id");
    System.out.println("Funtion Comes inside fetch servlet of AnswerConnect");
    resp.setContentType("text/json");
    PrintWriter out = resp.getWriter();
    PersistenceManager pmf = PMF.get().getPersistenceManager();
    /*Query q = pmf.newQuery(Fullclient.class);
    q.setFilter("ID==clickedId");
    q.declareParameters("String clickedId");*/
    System.out.println("data value is setted");
    try {
      AnswerConnect results = (AnswerConnect) pmf.getObjectById(AnswerConnect.class, button);
      System.out.println(results);
      System.out.println("query successfull");
      ObjectWriter objectwriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
      String json = objectwriter.writeValueAsString(results);
      System.out.println(json);
      out.print(json);
    } catch (JDOObjectNotFoundException e) {

    } finally {
      pmf.close();
      out.flush();
      System.out.println("AnswerConnect function closes here");
    }
  }
Example #9
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    PrintWriter out = resp.getWriter();

    String nombre = req.getParameter("nombre");
    String apellido = req.getParameter("apellido");
    String especie = req.getParameter("especie");
    int edad = Integer.parseInt(req.getParameter("edad"));
    String sexo = req.getParameter("sexo");
    String descripcion = req.getParameter("descripcion");
    String mensaje = req.getParameter("mensaje");

    Adopcion p = new Adopcion(nombre, apellido, especie, edad, sexo, descripcion, mensaje);
    PersistenceManager pm = PMF.get().getPersistenceManager();

    try {
      pm.makePersistent(p);
      (getServletContext().getRequestDispatcher("/WEB-INF/jspUsuario/confirmar.jsp"))
          .forward(req, resp);

    } catch (Exception e) {
      System.out.println(e);
      resp.getWriter().println("Ocurrió un error, <a href='index07.html'>vuelva a intentarlo</a>");
    } finally {
      pm.close();
    }
  }
public class BibleDaoProvider {
  private static final IBibleDao dao = new BibleDao(PMF.get(), new VerseQueryFactory());

  public static IBibleDao getBibleDao() {
    return dao;
  }
}
Example #11
0
  public static Admin getByUserId(String aUserId, long surveyId) {
    PersistenceManager pm = null;
    Admin result = null;
    List<Admin> results = null;
    try {
      pm = PMF.get().getPersistenceManager();
      Query query = null;
      try {
        query = pm.newQuery(Admin.class);
        query.setFilter("userIdLowerCase==userIdLowerCaseParam && surveyId==surveyIdParam");
        query.declareParameters("String userIdLowerCaseParam, Long surveyIdParam");

        results = (List<Admin>) query.execute(aUserId.toLowerCase(), surveyId);

        // 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();
      }
    }

    if (results != null && !results.isEmpty()) {
      result = results.get(0);
    }

    return result;
  }
Example #12
0
  /**
   * Searches for {@link Dish}es belonging to a {@link Restauarnt} using the supplied search terms
   *
   * @param queryWords terms to search with
   * @param restKey {@link Key} to the {@link Restaurant} to search within
   * @param maxResults maximum number of results to return
   * @return {@link Collection} of {@link Dish}es
   */
  @SuppressWarnings("unchecked")
  public static Set<Dish> searchDishesByRestaurant(
      String[] queryWords, Key restKey, int maxResults) {
    List<Object> paramList = null;
    String paramS = "";
    String queryS = "";
    final String queryString = "SELECT key FROM " + Dish.class.getName();
    final Query q = PMF.get().getPersistenceManager().newQuery(queryString);

    if (queryWords.length > 0) {
      paramList = new ArrayList<Object>();
      queryS += "restaurant == restParam";
      paramS = Key.class.getName() + " restParam";
      paramList.add(restKey);

      for (int i = 0; i < queryWords.length; i++) {
        queryS += " && searchTerms.contains(s" + i + ")";
        paramS += ", String s" + i;
        paramList.add(queryWords[i]);
      }

      q.setFilter(queryS);
      q.declareParameters(paramS);

      return Datastore.get(new HashSet<Key>((List<Key>) q.executeWithArray(paramList.toArray())));
    }

    return new HashSet<Dish>();
  }
public class ConnectionProvider implements DaoServiceLoader {

  PersistenceManagerFactory presistenceManagerFactory = PMF.get();
  PersistenceManager persistenceManager = presistenceManagerFactory.getPersistenceManager();

  public void savePojo(UserDetails user) {
    persistenceManager.makePersistent(user);
  }

  @SuppressWarnings("unchecked")
  public List<UserDetails> getPojo(String facebookId) {
    Query query =
        persistenceManager.newQuery(UserDetails.class, "facebookId == '" + facebookId + "'");
    return (List<UserDetails>) query.execute();
  }

  @SuppressWarnings("unchecked")
  public List<UserDetails> getPojoByField(String field, String fieldValue) {
    Query query =
        persistenceManager.newQuery(UserDetails.class, field + " == '" + fieldValue + "'");
    return (List<UserDetails>) query.execute();
  }
  /*@SuppressWarnings("unchecked")
  public List<UserDetails> changePassword(String username,String old_Password) {
  	// TODO Auto-generated method stub
  	Query query=persistenceManager.newQuery(UserDetails.class,"user_Name== '"+username+"' && passWord== '"+old_Password+"'");
  	return (List<UserDetails>)query.execute();
  	}*/
  @SuppressWarnings("unchecked")
  public List<UserDetails> getAll() {
    Query query = persistenceManager.newQuery(UserDetails.class);
    return (List<UserDetails>) query.execute();
  }
}
Example #14
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;
    }
  }
Example #15
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);
       }
   }*/
 }
Example #16
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;
  }
Example #17
0
  public static List<Producto> mostrarsegunNombre(String name) {
    final PersistenceManager pm = PMF.get().getPersistenceManager();
    String query = " select from " + Producto.class.getName() + " where nombre == '" + name + "'";
    List<Producto> producto = (List<Producto>) pm.newQuery(query).execute();

    return (producto);
  }
Example #18
0
  public static int addAndGet(String name, int delta) {
    PersistenceManager pm = PMF.get().getPersistenceManager();

    NamedCounter counter = null;

    try {
      // Detach the persisted objects after changes are commited since we
      // access members after the transaction is commited. Without this
      // setting, the counter members could be wiped after the transaction
      // is
      // closed.
      pm.setDetachAllOnCommit(true);
      pm.currentTransaction().begin();
      try {
        counter = pm.getObjectById(NamedCounter.class, KeyFactory.keyToString(getKeyForName(name)));
        counter.add(delta);
      } catch (JDOObjectNotFoundException e) {
        counter = new NamedCounter(name);
        // Only need this make persistent call here, since any counter
        // already retrieved using JDO will be marked as persistent once
        // we increment the counter; JDO will automatically write it to
        // the Datastore on commit.
        counter.add(delta);
        pm.makePersistent(counter);
      }
      pm.currentTransaction().commit();
    } finally {
      if (pm.currentTransaction().isActive()) {
        pm.currentTransaction().rollback();
      }
    }
    return counter.getCount();
  }
 private String searchAndReturnDatainJSONFormat(String zipCodeArray[], String stateCode) {
   String query = "";
   String retValue = "[";
   PersistenceManager pm = PMF.get().getPersistenceManager();
   for (String zipCode : zipCodeArray) {
     if (zipCode != null && zipCode.length() > 0) {
       query =
           "select from "
               + EPAToxicDataBean.class.getName()
               + " where LocationZIPCode =='"
               + zipCode
               + "'";
     }
     // Adding this here to keep the compiler happy
     @SuppressWarnings("unchecked")
     List<EPAToxicDataBean> xmlDataList = (List<EPAToxicDataBean>) pm.newQuery(query).execute();
     int beanCounter = 1;
     if (xmlDataList != null) {
       for (EPAToxicDataBean rec : xmlDataList) {
         org.json.JSONObject jsonObject = new org.json.JSONObject(rec);
         retValue += jsonObject.toString();
         if (xmlDataList.size() > 1 && beanCounter != xmlDataList.size()) {
           retValue += ",";
         }
         ++beanCounter;
       }
     }
     retValue += "]";
   }
   return retValue;
 }
 public ServiceResult<Void> updatePage(Page editPage) {
   ServiceResult<Void> result = new ServiceResult<Void>();
   Page page = null;
   PersistenceManager pm = null;
   try {
     pm = PMF.get().getPersistenceManager();
     page = pm.getObjectById(Page.class, editPage.getId());
     if (page == null) {
       result.setOK(false);
       result.setMessage(Global.messages.getString("no_page_found"));
     } else {
       page.setContent(editPage.getContent());
       page.setDate_post(editPage.getDate_post());
       page.setLast_modified(editPage.getLast_modified());
       page.setLink_thumbnail(editPage.getLink_thumbnail());
       page.setName(editPage.getName());
       page.setPage_view(editPage.getPage_view());
       page.setSetCategoryKeys(editPage.getSetCategoryKeys());
       page.setSetProduct(editPage.getSetProduct());
       result.setOK(true);
       result.setMessage(Global.messages.getString("update_page_successfully"));
     }
   } catch (Exception e) {
     result.setMessage(Global.messages.getString("update_page_fail"));
     result.setOK(false);
     e.printStackTrace();
   } finally {
     try {
       pm.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return result;
 }
Example #21
0
 public static void deleteAllAccesses(List<Access> list) {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   try {
     pm.deletePersistentAll(list);
   } finally {
     pm.close();
   }
 }
 @Override
 public Set<EventCalendar> getOwnedItems(String id) {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   User user = (User) pm.getObjectById(User.class, id);
   Set<EventCalendar> result = user.getOwnedCalendars();
   pm.close();
   return result;
 }
Example #23
0
  /**
   * Gets {@link Key}s of all the {@link Dish}es at a {@link Restaurant}
   *
   * @param restKey {@link Key} of the {@link Restaurant}
   * @return {@link Collection} of {@link Key} objects
   */
  @SuppressWarnings("unchecked")
  public static Collection<Key> getDishKeysByRestaurant(Key restKey) {
    String query = "SELECT key FROM " + Dish.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setFilter("restaurant == :param");

    return (Collection<Key>) q.execute(restKey);
  }
Example #24
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;
  }
Example #25
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);
  }
Example #26
0
 public static void writeAcces(String ipAddress, Date date, String urlRequest) {
   Access a = new Access(ipAddress, date, urlRequest);
   PersistenceManager pm = PMF.get().getPersistenceManager();
   try {
     pm.makePersistent(a);
   } finally {
     pm.close();
   }
 }
Example #27
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());
  }
Example #28
0
  /**
   * Get the {@link Key}s of all of the {@link Review}s created by a {@link TDUser}
   *
   * @param userKey {@link Key} of the {@link TDUser}
   * @return {@link List} of {@link Key} objects sorted from newest to oldest
   */
  @SuppressWarnings("unchecked")
  public static Set<Key> getReviewKeysByUser(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");

    return (Set<Key>) q.execute(userKey);
  }
 public EventCalendar removeItem(String id, String itemId) {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   User user = pm.getObjectById(User.class, id);
   EventCalendarDao calDao = new EventCalendarDaoImpl();
   EventCalendar cal = calDao.get(itemId);
   user.removeCalendar(cal);
   pm.makePersistent(user);
   pm.close();
   return cal;
 }
Example #30
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())));
  }