Beispiel #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;
  }
Beispiel #2
0
  private void startIteration(String cursorString) {
    //        if (cursorString == null) {
    //            CSVEntry entry = CSVCache.getInstance().getCSV(csvId);
    //            if (entry != null) {
    //                if (entry.getStatus() == CSVEntry.BUILDING_STATUS) {
    //                    return;
    //                }
    //            }
    //        }
    CSVEntry entry = CSVCache.getInstance().getCSV(csvId);

    if (entry != null) {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
        ResponseList rl = ResponseManager.getResponse(runId, 0l, null, cursorString);
        entry = processResponses(pm, rl.getResponses());
        if (!(rl.getResponses().isEmpty() || rl.getResumptionToken() == null)) {
          new CSVGeneration(rl.getResumptionToken(), runId, csvId).scheduleTask();
        } else {
          entry.setStatus(CSVEntry.FINISHED_STATUS);
        }
        CSVCache.getInstance().putCSV(csvId, entry);
      } finally {
        pm.close();
      }
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // get the tickerStr
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    // get the user and check for non null
    if (user != null) {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      Collection<UserComparisonTickers> comparisonTickersCollection = null;
      try {
        comparisonTickersCollection =
            getComparisonTickersService().getComparisonTickers(user.getEmail());
      } catch (Exception e) {
        log.logp(
            Level.SEVERE,
            GetComparisonTickersServlet.class.getName(),
            "method",
            "UserComparisonTickers could not be fetched from persistence storage",
            e);
      } finally {
        pm.close();
      }
      if (comparisonTickersCollection != null) {
        resp.getWriter().write(getComparisonTickersService().getJson(comparisonTickersCollection));
      }
    }
  }
  private void initDevices(ServletContext ctx) {
    // Context-shared PMF.
    PersistenceManager pm = DBHelper.getPMF(ctx).getPersistenceManager();

    try {
      devices = DeviceInfo.getDeviceInfoForUserEmail(pm, userEmail);
      // cleanup for multi-device
      /*if (devices.size() > 1) {
      // Make sure there is no 'bare' registration
      // Keys are sorted - check the first
      DeviceInfo first = devices.get(0);
      Key oldKey = first.getKey();
      if (oldKey.toString().indexOf("#") < 0) {
          log.warning("Removing old-style key " + oldKey.toString());
          // multiple devices, first is old-style.
          devices.remove(0);
          pm.deletePersistent(first);
      }
         }*/
      log.log(
          Level.INFO,
          "RequestInfo:initDevices() : loading devices "
              + devices.size()
              + " for user = "******"RequestInfo:initDevices() : Error loading registrations ", e);
    } finally {
      pm.close();
    }
  }
 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 Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      // Invocation on PersistenceManagerFactory interface coming in...

      if (method.getName().equals("equals")) {
        // Only consider equal when proxies are identical.
        return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
      } else if (method.getName().equals("hashCode")) {
        // Use hashCode of PersistenceManagerFactory proxy.
        return new Integer(System.identityHashCode(proxy));
      } else if (method.getName().equals("getPersistenceManager")) {
        PersistenceManagerFactory target = getTargetPersistenceManagerFactory();
        PersistenceManager pm =
            PersistenceManagerFactoryUtils.doGetPersistenceManager(target, isAllowCreate());
        Class[] ifcs =
            ClassUtils.getAllInterfacesForClass(pm.getClass(), getClass().getClassLoader());
        return (PersistenceManager)
            Proxy.newProxyInstance(
                pm.getClass().getClassLoader(),
                ifcs,
                new TransactionAwareInvocationHandler(pm, target));
      }

      // Invoke method on target PersistenceManagerFactory.
      try {
        return method.invoke(getTargetPersistenceManagerFactory(), args);
      } catch (InvocationTargetException ex) {
        throw ex.getTargetException();
      }
    }
  @SuppressWarnings("unchecked")
  public List<OGRFeature> listByCountryAndType(
      String countryCode, FeatureType featureType, 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(
        "featureType", filterString, paramString, "String", featureType, paramMap, EQ_OP);
    appendNonNullParam(
        "countryCode", filterString, paramString, "String", countryCode, paramMap, EQ_OP);

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

    prepareCursor(cursorString, query);
    List<OGRFeature> results = (List<OGRFeature>) query.executeWithMap(paramMap);

    if (results != null && results.size() > 0) {
      return results;
    } else {
      return null;
    }
  }
  /** Used only internally by the cleaner daemon (run()). */
  private long remove(Long threshold) throws DAOException {
    PersistenceManager deleteManager = getManager();
    if (deleteManager == null) {
      return 0;
    }

    Transaction tx = deleteManager.currentTransaction();
    AlarmDAOFilter filter = AlarmJDOUtils.getDeleteBeforeFilter(threshold);
    try {
      tx.begin();
      long removed = AlarmJDOUtils.delete(deleteManager, filter);
      tx.commit();
      logger.debug("successfully removed {} entries", removed);
      return removed;
    } catch (Exception t) {
      String message = "remove: " + filter + ": " + t.getLocalizedMessage();
      throw new DAOException(message, t);
    } finally {
      try {
        rollbackIfActive(tx);
      } finally {
        deleteManager.close();
      }
    }
  }
  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);
  }
  @Override
  public Collection<LogEntry> get(AlarmDAOFilter filter) {
    PersistenceManager readManager = getManager();
    if (readManager == null) {
      return Collections.emptyList();
    }

    Transaction tx = readManager.currentTransaction();

    try {
      tx.begin();
      Collection<LogEntry> result = AlarmJDOUtils.execute(readManager, filter);

      logger.debug("got collection {}", result);
      Collection<LogEntry> detached = readManager.detachCopyAll(result);
      logger.debug("got detatched collection {}", detached);
      tx.commit();
      logger.debug("successfully executed get for filter {}", filter);
      return detached;
    } catch (JDOException t) {
      logJDOException("update", filter, t);
      return Collections.emptyList();
    } finally {
      try {
        rollbackIfActive(tx);
      } finally {
        readManager.close();
      }
    }
  }
  @Override
  public long remove(Collection<LogEntry> selected) {
    if (selected.isEmpty()) {
      return 0;
    }

    PersistenceManager deleteManager = getManager();
    if (deleteManager == null) {
      return 0;
    }

    Transaction tx = deleteManager.currentTransaction();
    AlarmDAOFilter filter = AlarmJDOUtils.getIdFilter(selected);

    try {
      tx.begin();
      long removed = AlarmJDOUtils.delete(deleteManager, filter);
      tx.commit();
      logger.debug("successfully removed {} entries", removed);
      return removed;
    } catch (JDOException t) {
      logJDOException("update", filter, t);
      return 0;
    } finally {
      try {
        rollbackIfActive(tx);
      } finally {
        deleteManager.close();
      }
    }
  }
Beispiel #12
0
  @Override
  public ArrayList<ProductDTO> getProducts() throws NotLoggedInException {
    List<Product> products = new ArrayList<Product>();
    ArrayList<ProductDTO> productsDTO = new ArrayList<ProductDTO>();

    PersistenceManager pm = getPersistenceManager();
    try {
      Query q = pm.newQuery(Product.class);
      products = (List<Product>) q.execute();
      for (Product productItem : products) {

        CategoryDTO categoryDTO = getCategoryForCombo(productItem.getCategoryid());

        ProductDTO productDTO =
            new ProductDTO(
                productItem.getId(),
                productItem.getName(),
                productItem.getPrice(),
                productItem.getDescription(),
                productItem.getDetalle(),
                productItem.getImage(),
                productItem.getImageCarrito(),
                categoryDTO);
        productsDTO.add(productDTO);
      }
    } finally {
      pm.close();
    }
    return productsDTO;
  }
  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");
    }
  }
 @RequestMapping(value = "/mobileform/{id}", method = RequestMethod.POST)
 public MobileForm saveMobileForm(@RequestBody MobileForm mht) throws IOException {
   UserService userService = UserServiceFactory.getUserService();
   User user = userService.getCurrentUser();
   if (userService.isUserLoggedIn()) {
     PersistenceManager pm = PMF.get().getPersistenceManager();
     try {
       Date now = new Date();
       if (mht.getId().equalsIgnoreCase("123")) {
         mht.setId(KeyFactory.keyToString(KeyFactory.createKey(user.getEmail(), now.getTime())));
         mht.setCreator(user.getEmail());
         MobileForm mt = pm.makePersistent(mht);
         return mt;
       } else {
         Key k = KeyFactory.createKey(MobileForm.class.getSimpleName(), mht.getId());
         MobileForm m = pm.getObjectById(MobileForm.class, k);
         m.setMethod(mht.getMethod());
         return pm.makePersistent(m);
       }
     } finally {
       pm.close();
     }
   }
   return null;
 }
Beispiel #15
0
 private User getUser(String login, String password) {
   PersistenceManager manager = null;
   Transaction transaction = null;
   List<User> users = null;
   try {
     manager = PMF.newInstance().getPersistenceManager();
     transaction = manager.currentTransaction();
     transaction.begin();
     Query query = manager.newQuery(User.class);
     users = (List<User>) query.execute();
     transaction.commit();
   } catch (Exception e) {
     if (transaction != null) {
       transaction.rollback();
     }
   } finally {
     manager.close();
   }
   if (users != null && !users.isEmpty()) {
     for (User u : users) {
       System.out.println(u.getLogin() + " : " + u.getPassword());
       if (login.equals(u.getLogin()) && password.equals(u.getPassword())) {
         System.out.println(u.getLogin() + " : " + u.getPassword());
         return u;
       }
     }
   }
   return null;
 }
  @Override
  public void onAddArticlesToDeliveryNote(
      User user, Store store, DeliveryNote deliveryNote, Collection<? extends Article> articles) {
    if (logger.isDebugEnabled())
      logger.debug(
          "onAddArticlesToDeliveryNote entered. organisationID="
              + getOrganisationID()
              + " deliveryNote="
              + deliveryNote.getPrimaryKey()
              + " articles.size()="
              + articles.size());

    //		super.onAddArticlesToDeliveryNote(user, store, deliveryNote, articles); // the super method
    // is a noop - at least now. Marco.
    PersistenceManager pm = getPersistenceManager();

    pm.getExtent(VoucherDeliveryNoteActionHandler.class);
    VoucherDeliveryNoteActionHandler deliveryNoteActionHandler =
        (VoucherDeliveryNoteActionHandler)
            pm.getObjectById(
                DeliveryNoteActionHandlerID.create(
                    Organisation.DEV_ORGANISATION_ID,
                    VoucherDeliveryNoteActionHandler.class.getName()));
    deliveryNote.getDeliveryNoteLocal().addDeliveryNoteActionHandler(deliveryNoteActionHandler);
  }
Beispiel #17
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;
  }
  public Object loadPojo(final TypedOid oid) {

    // REVIEW: does it make sense to get these directly?  not sure, so for now have decided to fail
    // fast.
    if (oid instanceof AggregatedOid) {
      throw new UnsupportedOperationException(
          "Cannot retrieve aggregated objects directly, oid: " + oid.enString(getOidMarshaller()));
    }

    final RootOid rootOid = (RootOid) oid;

    Object result = null;
    try {
      final Class<?> cls = clsOf(rootOid);
      final Object jdoObjectId = JdoObjectIdSerializer.toJdoObjectId(rootOid);
      final PersistenceManager pm = getPersistenceManager();
      FetchPlan fetchPlan = pm.getFetchPlan();
      fetchPlan.addGroup(FetchGroup.DEFAULT);
      result = pm.getObjectById(cls, jdoObjectId);
    } catch (final RuntimeException e) {
      throw e;
    }

    if (result == null) {
      throw new ObjectNotFoundException(oid);
    }
    return result;
  }
Beispiel #19
0
  @SuppressWarnings("unchecked")
  public List<OGRFeature> listBySubLevelCountry(
      String countryCode, Integer subLevel, 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(
        "countryCode", filterString, paramString, "String", countryCode, paramMap, EQ_OP);
    appendNonNullParam(
        "featureType",
        filterString,
        paramString,
        "String",
        FeatureType.SUB_COUNTRY_OTHER,
        paramMap,
        EQ_OP);
    appendNonNullParam(
        "sub" + (subLevel), filterString, paramString, "String", "null", paramMap, NOT_EQ_OP);
    appendNonNullParam(
        "sub" + (subLevel + 1), filterString, paramString, "String", "null", paramMap, EQ_OP);
    query.setFilter(filterString.toString());
    query.declareParameters(paramString.toString());

    prepareCursor(cursorString, query);

    List<OGRFeature> resultsGTE = (List<OGRFeature>) query.executeWithMap(paramMap);

    return resultsGTE;
  }
Beispiel #20
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);
       }
   }*/
 }
Beispiel #21
0
  public OGRFeature findByCountryTypeAndSub(
      String countryCode, String name, FeatureType featureType, ArrayList<String> subArray) {
    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(
        "featureType", filterString, paramString, "String", featureType, paramMap, EQ_OP);
    appendNonNullParam("name", filterString, paramString, "String", name, paramMap, EQ_OP);
    appendNonNullParam(
        "countryCode", filterString, paramString, "String", countryCode, paramMap, EQ_OP);
    for (int i = 1; i < subArray.size() + 1; i++) {
      appendNonNullParam(
          "sub" + i, filterString, paramString, "String", subArray.get(i - 1), paramMap, EQ_OP);
    }

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

    @SuppressWarnings("unchecked")
    List<OGRFeature> results = (List<OGRFeature>) query.executeWithMap(paramMap);
    if (results != null && results.size() > 0) return results.get(0);
    else return null;
  }
 @RequestMapping(value = "/resetforgotpassword", method = RequestMethod.POST)
 public String resetforgotPassword(HttpServletRequest request, ModelMap model) {
   String email = HtmlUtils.htmlEscape(request.getParameter("email"));
   if (email != null) {
     String userid = email;
     String password = HtmlUtils.htmlEscape(request.getParameter("password"));
     PersistenceManager pm = PMF.get().getPersistenceManager();
     Query q = pm.newQuery(User.class);
     q.setFilter("email==userid");
     q.declareParameters("String userid");
     List<User> result = (List<User>) q.execute(userid);
     try {
       User c = pm.getObjectById(User.class, result.get(0).getUserId());
       c.setPassword(password);
       model.addAttribute("registered", "Password reset successfully, Login now !!");
       model.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
     } finally {
       pm.close();
     }
     return "login";
   } else {
     model.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
     return "login";
   }
 }
  // We need to iterate again - can be avoided with a query.
  // delete will fail if the pm is different than the one used to
  // load the object - we must close the object when we're done
  public void deleteRegistration(String regId) {
    if (ctx == null) {
      return;
    }
    PersistenceManager pm = DBHelper.getPMF(ctx).getPersistenceManager();
    try {
      List<DeviceInfo> registrations = DeviceInfo.getDeviceInfoForUserEmail(pm, userEmail);
      for (int i = 0; i < registrations.size(); i++) {
        DeviceInfo deviceInfo = registrations.get(i);
        if (deviceInfo.getDeviceRegistrationID().equals(regId)) {
          pm.deletePersistent(deviceInfo);
          // Keep looping in case of duplicates

          log.log(
              Level.INFO,
              "RequestInfo:deleteRegistration() : deleted deviceInfo for "
                  + deviceInfo.getDeviceRegistrationID());
        }
      }
    } catch (JDOObjectNotFoundException e) {
      log.warning("RequestInfo:deleteRegistration() : User unknown");
    } catch (Exception e) {
      log.warning(
          "RequestInfo:deleteRegistration() : Error unregistering device: " + e.getMessage());
    } finally {
      pm.close();
    }
  }
Beispiel #24
0
  @SuppressWarnings("unchecked")
  @ApiMethod(name = "userinfos.phone.test", path = "user_info_phone_test", httpMethod = "post")
  public UserInfo phoneTest(UserInfo userInfo) {
    // check if there is another user using same phone number
    PersistenceManager pm = PMF.getPersistenceManagerSQL();
    Query query = pm.newQuery(UserInfo.class);
    query.setFilter("phone == thePhone");
    query.declareParameters("String thePhone");
    List<UserInfo> userInfos = (List<UserInfo>) pm.newQuery(query).execute(userInfo.getPhone());

    // phone number already taken
    if (!userInfos.isEmpty()) return userInfo;

    try {
      String verNumber = getVerNumberString();
      sendVerNumber(userInfo.getPhone(), verNumber);

      // save verification code and phone number in verCode field together
      userInfo.setVerificationCode(verNumber + userInfo.getPhone());
      userInfo.setPhone("");
      update(userInfo);

      // erase verCode field before send back to the user
      userInfo.setVerificationCode("");
    } catch (TwilioRestException e) { // failed to send code message
    }

    return userInfo;
  }
  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();
    }
  }
  /**
   * gets all translations for a given id and parentType combination. The map returned is keyed on
   * language code.
   *
   * @param parentType
   * @param parentId
   * @return
   */
  @SuppressWarnings("unchecked")
  public HashMap<String, Translation> findTranslations(
      Translation.ParentType parentType, Long parentId) {
    PersistenceManager pm = PersistenceFilter.getManager();
    javax.jdo.Query query = pm.newQuery(Translation.class);
    StringBuilder filterString = new StringBuilder();
    StringBuilder paramString = new StringBuilder();
    Map<String, Object> paramMap = null;
    paramMap = new HashMap<String, Object>();

    appendNonNullParam("parentType", filterString, paramString, "String", parentType, paramMap);
    appendNonNullParam("parentId", filterString, paramString, "Long", parentId, paramMap);

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

    HashMap<String, Translation> translations = new HashMap<String, Translation>();
    List<Translation> translationList = (List<Translation>) query.executeWithMap(paramMap);
    if (translationList != null) {
      for (Translation t : translationList) {
        translations.put(t.getLanguageCode(), t);
      }
    }
    return translations;
  }
Beispiel #27
0
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    Long orderId = Long.parseLong(req.getParameter("orderid"));
    Status status = Status.valueOf(req.getParameter("status"));

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (AdminAuthenticator.isAdmin(user)) {

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

      String select_query = "select from " + Order.class.getName();
      Query query = pm.newQuery(select_query);
      query.setFilter("id == paramId");
      query.declareParameters("java.lang.Long paramId");
      // execute
      List<Order> orders = (List<Order>) query.execute(orderId);

      if (!orders.isEmpty()) {
        // should be only one - safety check here
        Order order = orders.get(0);
        order.setStatus(status);
        pm.close();
        res.sendRedirect("/home.html");
      }
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Find listings under a percentage
    List<SteamMarketListing> listings = SteamMarketUtility.getSteamMarketListings();

    PersistenceManager pm = PMF.get().getPersistenceManager();
    String messageBody = "";
    for (int i = 0; i < listings.size(); i++) {
      SteamMarketListing listing = listings.get(i);
      MarketHistoryJDO history;
      try {
        history = (MarketHistoryJDO) pm.getObjectById(MarketHistoryJDO.class, listing.getLink());
        double average = history.averagePrice();
        double startingPrice = listing.getStartingPrice();
        if (startingPrice < (1 - PERCENT) * average) {
          messageBody += "Item:" + history.getUrl() + "<br />";
          messageBody += "Current: " + startingPrice + "<br />";
          messageBody += "Average: " + average + "<br />";
          messageBody += "<br />";
        }
      } catch (JDOObjectNotFoundException e) {
        // Item not found - listed since last crawl. Just wait for the item to be crawled.
      }
    }
    response.getWriter().write(messageBody);

    pm.close();
  }
Beispiel #29
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);
    }
  }
 protected void HandleRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   PersistenceManager pm = PMF.getManager();
   Query query = pm.newQuery(MediumData.class);
   query.deletePersistentAll();
   response.getWriter().format("table.medium deleteAll %s", new Object[] {ActionStatus.SUCCESS});
 }