Esempio n. 1
0
  public void testMbrTouches() throws SQLException, ParseException {
    if (!runTestsForDatastore()) {
      return;
    }

    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      Point point = (Point) wktReader.read("POINT(75 75)");
      Query query =
          pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrTouches(:point, geom)");
      List list = (List) query.execute(point);
      assertEquals(
          "Wrong number of geometries which are touched by a given point returned", 2, list.size());
      assertTrue(
          "Polygon 1 should be in the list of geometries which are touched by a given point",
          list.contains(getSamplePolygon(1)));
      assertTrue(
          "Polygon 2 should be in the list of geometries which are touched by a given point",
          list.contains(getSamplePolygon(2)));
    } finally {
      tx.commit();
    }
  }
Esempio n. 2
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;
 }
  private boolean persistNoteImage(String contentType, byte[] bytes, String noteKey) {
    Store.Api api = store.getApi();

    User user = UserServiceFactory.getUserService().getCurrentUser();
    // NoteImage image = new NoteImage(bytes, contentType, user.getEmail(), new Date(), new Date());

    try {
      Author me = api.getOrCreateNewAuthor(user);

      Transaction tx = api.begin();
      Note note = api.getNote(KeyFactory.stringToKey(noteKey));
      if (!note.getAuthorEmail().equalsIgnoreCase(me.getEmail())) {
        return false;
      }

      Transform resize = ImagesServiceFactory.makeResize(400, 400);
      ImagesService imagesService = ImagesServiceFactory.getImagesService();
      Image oldImage = ImagesServiceFactory.makeImage(bytes);
      Image newImage = imagesService.applyTransform(resize, oldImage, OutputEncoding.JPEG);
      note.setImageData(new Blob(newImage.getImageData()));

      note.setContentType(contentType);
      api.saveNote(note);
      tx.commit();

      log.debug("Persisted image with for note: " + note.getKey());

    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      return false;
    } finally {
      api.close();
    }
    return true;
  }
Esempio n. 4
0
  /** 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();
      }
    }
  }
Esempio n. 5
0
  public void testMbrEqual() throws SQLException, ParseException {
    if (!runTestsForDatastore()) {
      return;
    }

    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      Polygon polygon =
          (Polygon)
              wktReader.read(
                  "POLYGON((25 25,75 25,75 75,25 75,25 25),(45 45,55 45,55 55,45 55,45 45))");
      Query query =
          pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrEqual(geom, :polygon)");
      List list = (List) query.execute(polygon);
      assertEquals(
          "Wrong number of geometries which are equal to a given polygon returned", 1, list.size());
      assertTrue(
          "Polygon 1 should be in the list of geometries which are equal to a given polygon",
          list.contains(getSamplePolygon(1)));
    } finally {
      tx.commit();
    }
  }
 private void beginJdoTransaction() {
   final javax.jdo.Transaction transaction = getPersistenceManager().currentTransaction();
   if (transaction.isActive()) {
     throw new IllegalStateException("Transaction already active");
   }
   transaction.begin();
 }
Esempio n. 7
0
  @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();
      }
    }
  }
Esempio n. 8
0
  @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();
      }
    }
  }
Esempio n. 9
0
  @SuppressWarnings({"unchecked"})
  private void browserAuth(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm)
      throws IOException {
    OpenIdUser openIdUser = (OpenIdUser) req.getAttribute(OpenIdUser.ATTR_NAME);

    if (openIdUser == null) {
      setResponse(resp, 403, "OpenID authorization required");
      return;
    }
    String email = getEmail(openIdUser);

    String openidUrl = getOpenidUrl(resp, openIdUser, email);
    if (openidUrl == null) return;

    long id = Long.parseLong(req.getRequestURI().substring("/browser-auth/".length()));
    Date date = new Date();
    DbUser dbUser = findUser(pm, openidUrl, email);

    if (dbUser == null) {
      dbUser = createAndStoreUser(pm, openidUrl, email);
    }
    SqlCloudSession session =
        persistenceHelper.createSqlCloudSession(id, date, dbUser.createKeyObject(), email);
    Transaction tx = pm.currentTransaction();
    tx.begin();
    try {
      pm.makePersistent(session);
      tx.commit();
    } finally {
      if (tx.isActive()) tx.rollback();
    }
    resp.setStatus(200);
    resp.setContentType("text/html");
    PrintWriter writer = resp.getWriter();
    writer.println(
        "<title>"
            + getCloudName()
            + "</title>"
            + "<table border=0 cellpadding=10><tr>"
            + "<td bgcolor='#b9b9fe' valign='top'>"
            + "<img src='http://findbugs.sourceforge.net/umdFindbugs.png' alt='FindBugs'>"
            + "</td>"
            + "<td valign='top'>"
            + "<h1>You are now signed into "
            + getCloudName()
            + "</h1>"
            + "<p style='font-size: large'>"
            + "Return to the FindBugs application window to continue.</p>"
            + "<p>Signed in as <strong>"
            + escapeHtml(email)
            + "</strong><br>"
            + "<span style='font-size:x-small; font-style: italic'>("
            + escapeHtml(openidUrl)
            + ")</span></p>");
  }
Esempio n. 10
0
  private DbUser createAndStoreUser(PersistenceManager pm, String openidUrl, String email) {
    DbUser dbUser = persistenceHelper.createDbUser(openidUrl, email);

    Transaction tx = pm.currentTransaction();
    tx.begin();
    try {
      pm.makePersistent(dbUser);
      tx.commit();
    } finally {
      if (tx.isActive()) tx.rollback();
    }
    return dbUser;
  }
  @Override
  public long getLocalRevision() {
    if (localRevision < 0) {
      if (!write) throw new IllegalStateException("This is a read-only transaction!");

      jdoTransaction.setSerializeRead(true);
      final LocalRepository lr = getDao(LocalRepositoryDao.class).getLocalRepositoryOrFail();
      jdoTransaction.setSerializeRead(null);
      localRevision = lr.getRevision() + 1;
      lr.setRevision(localRevision);
      persistenceManager.flush();
    }
    return localRevision;
  }
Esempio n. 12
0
 private void recordSession(
     PersistenceManager pm, SqlCloudSession session, DbInvocation invocation) {
   Transaction tx;
   session.setInvocation(invocation);
   tx = pm.currentTransaction();
   tx.begin();
   try {
     pm.makePersistent(session);
     tx.commit();
   } finally {
     if (tx.isActive()) {
       tx.rollback();
     }
   }
 }
Esempio n. 13
0
  @Override
  public long update(Collection<LogEntry> selected) {
    if (selected.isEmpty()) {
      return 0;
    }

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

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

    try {
      tx.begin();
      Collection<LogEntry> result = AlarmJDOUtils.execute(updateManager, filter);
      logger.debug("got matching entries {}", result);
      long updated = result.size();

      Map<String, LogEntry> map = new HashMap<>();
      for (LogEntry e : selected) {
        map.put(e.getKey(), e);
      }

      for (LogEntry e : result) {
        e.update(map.get(e.getKey()));
      }

      /*
       * result is not detached so it will be updated on commit
       */
      tx.commit();
      logger.debug("successfully updated {} entries", updated);

      return updated;
    } catch (JDOException t) {
      logJDOException("update", filter, t);
      return 0;
    } finally {
      try {
        rollbackIfActive(tx);
      } finally {
        updateManager.close();
      }
    }
  }
Esempio n. 14
0
  private void showToken(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm)
      throws IOException {

    OpenIdUser openIdUser = (OpenIdUser) req.getAttribute(OpenIdUser.ATTR_NAME);

    if (openIdUser == null) {
      setResponse(resp, 403, "OpenID authorization required");
      return;
    }
    String email = getEmail(openIdUser);

    String openidUrl = getOpenidUrl(resp, openIdUser, email);
    if (openidUrl == null) return;

    DbUser user = findUser(pm, openidUrl, email);
    if (user == null) {
      user = createAndStoreUser(pm, openidUrl, email);
    }

    if (req.getParameter("generate") != null) {
      user.setUploadToken(generateUploadToken());
      Transaction tx = pm.currentTransaction();
      try {
        pm.makePersistent(user);
      } finally {
        if (tx.isActive()) tx.rollback();
      }
    }

    ServletOutputStream out = resp.getOutputStream();
    out.println("<title>" + getCloudName() + " - Token</title>");
    out.println("<body>");
    if (user.getUploadToken() != null) {
      out.println("Your token is: " + user.getUploadToken());
      out.println(
          "<form action=/token>"
              + "<input type=submit name=generate value='Regenerate Token'>"
              + "</form>");
    } else {
      out.println(
          "You have not yet created a command-line upload token. "
              + "<form action=/token>"
              + "<input type=submit name=generate value='Create Token'>"
              + "</form>");
    }
    out.println("</body>");
  }
  public static void addPrerequisiteCourse(String courseCode, String preReq_courseCode) {

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

    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      PrerequisiteCourse tmp = new PrerequisiteCourse(courseCode, preReq_courseCode);
      pm.makePersistent(tmp);
      tx.commit();
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
      pm.close();
    }
  }
Esempio n. 16
0
  // Retrieve the user from the database if it already exist or
  // create a new account if it is the first loggin
  @SuppressWarnings("unused")
  public static void createSuperUser() {

    PersistenceManager pm = PMFactory.getTxnPm();
    Transaction tx = null;

    Query q = pm.newQuery(UserProfile.class, "uniqueId == :uniqueId");
    q.setUnique(true);

    UserProfile superUser = new UserProfile();
    // OrphanageItem orphanage = new OrphanageItem();
    // NgoItem ngo = new NgoItem();
    // ProjectInfo project = new ProjectInfo();
    // ChapterItem chapter = new ChapterItem();
    // FriendItem friend = new FriendItem();
    /*
    superUser.addOrphanage(orphanage);
    superUser.addNgo(ngo);
    superUser.addProject(project);
    superUser.addChapter(chapter);
    superUser.addFriend(friend);*/

    // perform the query and creation under transactional control,
    // to prevent another process from creating an acct with the same id.
    try {
      for (int i = 0; i < NUM_RETRIES; i++) {
        tx = pm.currentTransaction();
        tx.begin();
        // Create friends from Google+

        pm.makePersistent(superUser);
        // detached = pm.detachCopy(superUser);
        tx.commit();
        break;
      } // end for
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
      pm.close();
      q.closeAll();
    }
  }
Esempio n. 17
0
 protected void setUp() throws Exception {
   super.setUp();
   if (runTestsForDatastore()) {
     PersistenceManager pm = pmf.getPersistenceManager();
     Transaction tx = pm.currentTransaction();
     try {
       tx.begin();
       pm.newQuery(SamplePoint.class).deletePersistentAll();
       pm.newQuery(SampleLineString.class).deletePersistentAll();
       pm.newQuery(SamplePolygon.class).deletePersistentAll();
       pm.newQuery(SampleGeometryCollection.class).deletePersistentAll();
     } finally {
       tx.commit();
     }
     Connection sqlConn = null;
     try {
       tx.begin();
       sqlConn = (Connection) pm.getDataStoreConnection();
       String connUrl = pmf.getConnectionURL().toLowerCase();
       String fileName = "sample_jts_postgis.sql";
       if (connUrl.contains("mysql") || connUrl.contains("mariadb")) {
         fileName = "sample_jts_mysql.sql";
       }
       File file =
           new File(
               PgGeometryMySQLTest.class
                   .getResource("/org/datanucleus/samples/data/" + fileName)
                   .toURI());
       String s = "";
       InputStream is = new FileInputStream(file);
       int c;
       while ((c = is.read()) != -1) {
         s += (char) c;
       }
       String ss[] = StringUtils.split(s, ";");
       for (int i = 0; i < ss.length; i++) {
         sqlConn.createStatement().execute(ss[i]);
       }
       is.close();
     } finally {
       sqlConn.close();
       tx.commit();
     }
   }
 }
 @Override
 public boolean isActive() {
   lock.lock();
   try {
     return jdoTransaction != null && jdoTransaction.isActive();
   } finally {
     lock.unlock();
   }
 }
Esempio n. 19
0
  private DbInvocation recordInvocation(
      PersistenceManager pm, LogIn loginMsg, SqlCloudSession session) {
    DbInvocation invocation = persistenceHelper.createDbInvocation();
    invocation.setWho(session.getUser());
    invocation.setStartTime(loginMsg.getAnalysisTimestamp());

    Transaction tx = pm.currentTransaction();
    tx.begin();
    try {
      invocation = pm.makePersistent(invocation);
      tx.commit();
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
    }
    return invocation;
  }
Esempio n. 20
0
  @Override
  public boolean saveUser(UserTestDTO user) {
    pm = PMF.get().getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      pm.makePersistent(user);
      tx.commit();
    } catch (Exception e) {
      if (tx.isActive()) {
        tx.rollback();
        return false;
      }
    } finally {
      pm.close();
    }

    return false;
  }
Esempio n. 21
0
  public static void main(String[] args) {
    PersistenceManagerFactory pmf = JdoUtils.getPMF();
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      Query q = pm.newQuery(Country.class, "name == givenName");
      q.declareParameters("String givenName");
      q.setUnique(true);
      Country aus = (Country) q.execute("Aus");
      // detaching null does not cause any problem
      aus = pm.detachCopy(aus);
      System.out.println("aus = " + aus);
      q.closeAll();
      tx.commit();
    } finally {
      if (tx.isActive()) tx.rollback();

      pm.close();
    }
  }
Esempio n. 22
0
 @SuppressWarnings({"unchecked"})
 private void logOut(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm)
     throws IOException {
   long id = Long.parseLong(req.getRequestURI().substring("/log-out/".length()));
   SqlCloudSession session = lookupCloudSessionById(id, pm);
   long deleted = 0;
   Transaction tx = pm.currentTransaction();
   tx.begin();
   try {
     pm.deletePersistent(session);
     deleted++;
     tx.commit();
   } finally {
     if (tx.isActive()) tx.rollback();
   }
   if (deleted >= 1) {
     resp.setStatus(200);
   } else {
     setResponse(resp, 404, "no such session");
   }
 }
Esempio n. 23
0
 @BeforeClass
 public static void doPersist() {
   // Persistence of a Product and a Book.
   PersistenceManager pm = pmf.getPersistenceManager();
   Transaction tx = pm.currentTransaction();
   try {
     tx.begin();
     for (int i = 0; i < 10; i++) {
       pm.makePersistent(new Product("C" + i, "F", 200.00, 2));
       pm.makePersistent(new Product("B" + i, "E", 400.00, 4));
       pm.makePersistent(new Product("A" + i, "D", 600.00, 6));
     }
     tx.commit();
   } finally {
     if (tx.isActive()) {
       tx.rollback();
     }
     pm.close();
   }
   System.out.println("");
 }
Esempio n. 24
0
  public void testMbrOverlaps() throws SQLException, ParseException {
    if (!runTestsForDatastore()) {
      return;
    }

    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      Polygon polygon = (Polygon) wktReader.read("POLYGON((10 10,50 10,50 50,10 50,10 10))");
      Query query =
          pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrOverlaps(geom, :polygon)");
      List list = (List) query.execute(polygon);
      assertEquals(
          "Wrong number of geometries which overlap a given linestring returned", 1, list.size());
      assertTrue(
          "LineString 1 should be in the list of geometries which overlap a given linestring",
          list.contains(getSamplePolygon(1)));
    } finally {
      tx.commit();
    }
  }
Esempio n. 25
0
  // Retrieve the user from the database if it already exist or
  // create a new account if it is the first loggin
  public static UserProfile findUserProfile(UserProfile user) {

    PersistenceManager pm = PMFactory.getTxnPm();
    Transaction tx = null;
    UserProfile oneResult = null, detached = null;

    String uniqueId = user.getUniqueId();

    Query q = pm.newQuery(UserProfile.class, "uniqueId == :uniqueId");
    q.setUnique(true);

    // perform the query and creation under transactional control,
    // to prevent another process from creating an acct with the same id.
    try {
      for (int i = 0; i < NUM_RETRIES; i++) {
        tx = pm.currentTransaction();
        tx.begin();
        oneResult = (UserProfile) q.execute(uniqueId);
        if (oneResult != null) {
          log.info("User uniqueId already exists: " + uniqueId);
          detached = pm.detachCopy(oneResult);
        } else {
          log.info("UserProfile " + uniqueId + " does not exist, creating...");
          // Create friends from Google+
          // user.setKarma(new Karma());
          pm.makePersistent(user);
          detached = pm.detachCopy(user);
        }
        try {
          tx.commit();
          break;
        } catch (JDOCanRetryException e1) {
          if (i == (NUM_RETRIES - 1)) {
            throw e1;
          }
        }
      } // end for
    } catch (JDOUserException e) {
      log.info("JDOUserException: UserProfile table is empty");
      // Create friends from Google+
      pm.makePersistent(user);
      detached = pm.detachCopy(user);
      try {
        tx.commit();
      } catch (JDOCanRetryException e1) {
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
      pm.close();
      q.closeAll();
    }

    return detached;
  }
  private void begin() {
    lock.lock();
    try {
      if (isActive()) throw new IllegalStateException("Transaction is already active!");

      lockIfWrite();

      persistenceManager = persistenceManagerFactory.getPersistenceManager();
      jdoTransaction = persistenceManager.currentTransaction();
      jdoTransaction.begin();
      listenerRegistry.onBegin();
    } finally {
      lock.unlock();
    }
  }
  @Override
  public void commit() {
    lock.lock();
    try {
      if (!isActive()) throw new IllegalStateException("Transaction is not active!");

      listenerRegistry.onCommit();
      daoClass2Dao.clear();
      jdoTransaction.commit();
      persistenceManager.close();
      jdoTransaction = null;
      persistenceManager = null;
      localRevision = -1;

      unlockIfWrite();
    } finally {
      lock.unlock();
    }
  }
 private void rollbackJdoTransaction() {
   final javax.jdo.Transaction transaction = getPersistenceManager().currentTransaction();
   if (transaction.isActive()) {
     transaction.rollback();
   }
 }
 private void commitJdoTransaction() {
   final javax.jdo.Transaction transaction = getPersistenceManager().currentTransaction();
   if (transaction.isActive()) {
     transaction.commit();
   }
 }
 private void ensureInHibernateTransaction() {
   javax.jdo.Transaction currentTransaction = getPersistenceManager().currentTransaction();
   ensureThatState(currentTransaction, is(notNullValue()));
   ensureThatState(currentTransaction.isActive(), is(true));
 }