Esempio n. 1
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;
  }