Example #1
0
 /**
  * A strategy method to lock an object with an exclusive lock so that it can be processed
  *
  * @param entity the entity to be locked
  * @param entityManager entity manager
  * @return true if the entity was locked
  */
 protected boolean lockEntity(Object entity, EntityManager entityManager) {
   if (!getEndpoint().isConsumeLockEntity()) {
     return true;
   }
   try {
     LOG.debug("Acquiring exclusive lock on entity: {}", entity);
     if (isSkipLockedEntity()) {
       entityManager.lock(entity, lockModeType, NOWAIT);
     } else {
       entityManager.lock(entity, lockModeType);
     }
     return true;
   } catch (Exception e) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("Failed to achieve lock on entity: " + entity + ". Reason: " + e, e);
     }
     if (e instanceof PessimisticLockException || e instanceof OptimisticLockException) {
       // transaction marked as rollback can't continue gracefully
       throw (PersistenceException) e;
     }
     // TODO: Find if possible an alternative way to handle results of native queries.
     // Result of native queries are Arrays and cannot be locked by all JPA Providers.
     if (entity.getClass().isArray()) {
       return true;
     }
     return false;
   }
 }
  private void btnOKActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnOKActionPerformed
    EntityManager em = OPDE.createEM();
    try {
      em.getTransaction().begin();
      TradeForm myTradeForm = em.merge(tradeForm);
      em.lock(myTradeForm, LockModeType.OPTIMISTIC);
      myTradeForm.setSubtext(txtZusatz.getText());
      DosageForm dosageForm = em.merge((DosageForm) cmbForm.getSelectedItem());
      em.lock(dosageForm, LockModeType.OPTIMISTIC);
      myTradeForm.setDosageForm(dosageForm);

      em.getTransaction().commit();

      tradeForm = myTradeForm;
    } catch (Exception e) {
      if (em.getTransaction().isActive()) {
        em.getTransaction().rollback();
      }
      OPDE.fatal(e);
    } finally {
      em.close();
    }
    dispose();
  } // GEN-LAST:event_btnOKActionPerformed
Example #3
0
  private void btnToUnbekanntActionPerformed(ActionEvent e) {
    Lager unbekannt = LagerTools.getUnbekannt();
    StockTableModel2 model = (StockTableModel2) tblVorrat.getModel();
    Tools.log(txtLog, "Folgende Vorräte wurden auf Unbekannt umgebucht:");
    Tools.log(txtLog, "================================================");

    EntityManager em = Main.getEMF().createEntityManager();
    try {
      em.getTransaction().begin();

      for (int row = 0; row < model.getRowCount(); row++) {
        // Model Row Index Umwandlung ist hier unnötig. Markierungen bleiben unberücksichtigt.
        if (model.getStatus(row) == StockTableModel2.STATUS_FRAGLICH) {
          Stock stock = em.merge(model.getVorrat(row));
          em.lock(stock, LockModeType.OPTIMISTIC);
          Tools.log(txtLog, stock.getId(), stock.getProdukt().getBezeichnung(), "");
          stock.setLager(unbekannt);
        }
      }
      em.getTransaction().commit();
    } catch (OptimisticLockException ole) {
      em.getTransaction().rollback();
      Main.warn(ole);
    } catch (Exception ex) {
      em.getTransaction().rollback();
      Main.fatal(ex);
    } finally {
      em.close();
      loadVorratTable();
    }
    Tools.log(txtLog, "================================================");
  }
 public void updateMovie() {
   Movie m = em.find(Movie.class, 3, LockModeType.PESSIMISTIC_WRITE);
   em.lock(m, LockModeType.PESSIMISTIC_WRITE);
   m.setName("INCEPTION");
   em.merge(m);
   em.flush();
 }
 public WorkItemInfo merge(WorkItemInfo workItemInfo) {
   if (this.pessimisticLocking) {
     if (em.contains(workItemInfo)) {
       em.lock(workItemInfo, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
     } else {
       // Yes, this is a hack, but for detached entities, it's the only way to lock before merging
       WorkItemInfo dbWorkItemInfo =
           em.find(
               WorkItemInfo.class, workItemInfo.getId(), LockModeType.PESSIMISTIC_FORCE_INCREMENT);
       for (Field field : WorkItemInfo.class.getDeclaredFields()) {
         boolean access = field.isAccessible();
         field.setAccessible(true);
         try {
           field.set(dbWorkItemInfo, field.get(workItemInfo));
         } catch (Exception e) {
           logger.error(
               "Unable to set field " + field.getName() + " of unmerged WorkItemInfo instance!",
               e);
         }
         field.setAccessible(access);
       }
     }
   }
   return em.merge(workItemInfo);
 }
  @Override
  public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
    EntityManager em = getCurrent();

    if (em != null) {
      em.lock(entity, lockMode, properties);
      return;
    }

    em = createEntityManager();

    try {
      em.lock(entity, lockMode, properties);
    } finally {
      freeEntityManager(em);
    }
  }
Example #7
0
  /**
   * Taking Survey - Update Survey Status
   *
   * @param record
   * @return
   * @throws Exception
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public Map takeSurvey(Map record) throws Exception {
    EntityManager oracleManager = null;
    Object transaction = null;
    try {
      String log = "Method:CommonDMI.takeSurvey.";
      oracleManager = EMF.getEntityManager();
      transaction = EMF.getTransaction(oracleManager);

      Timestamp recDate = new Timestamp(System.currentTimeMillis());
      Long survey_id = new Long(record.get("survey_id").toString());
      String loggedUserName = record.get("loggedUserName").toString();
      RCNGenerator.getInstance().initRcn(oracleManager, recDate, loggedUserName, log);
      ArrayList<Survey> surveyList =
          (ArrayList<Survey>)
              oracleManager
                  .createNamedQuery("Survey.getLocked")
                  .setParameter("survId", survey_id)
                  .getResultList();
      if (surveyList == null || surveyList.isEmpty()) {
        throw new CallCenterException(
            "გარკვევის ეს ჩანაწერი უკვე გადაწყვეტილია. გთხოვთ სცადოთ სხვა !");
      }
      Survey survey = surveyList.get(0);
      oracleManager.lock(survey, LockModeType.OPTIMISTIC);
      if (survey.getBblocked() != null
          && survey.getBblocked().equals(1L)
          && !loggedUserName.equals(survey.getLoked_user())) {
        throw new CallCenterException(
            "გარკვევის ეს ჩანაწერი უკვე აღებულია სხვის მიერ. გთხოვთ სცადოთ სხვა !");
      }
      survey.setBblocked(1L);
      survey.setLoked_user(loggedUserName);
      oracleManager.merge(survey);

      oracleManager.flush();
      EMF.commitTransaction(transaction);

      Map result = DMIUtils.findRecordById("SurveyDS", "searchAllSurvey", survey_id, "mysurvey_id");
      log += ". Status Updating Finished SuccessFully. ";
      logger.info(log);
      return result;
    } catch (Exception e) {
      EMF.rollbackTransaction(transaction);
      if (e instanceof CallCenterException) {
        throw (CallCenterException) e;
      }
      logger.error("Error While Update Status for Survey Into Database : ", e);
      throw new CallCenterException("შეცდომა მონაცემების განახლებისას : " + e.toString());
    } finally {
      if (oracleManager != null) {
        EMF.returnEntityManager(oracleManager);
      }
    }
  }
Example #8
0
  private void btnOKActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnOKActionPerformed

    if (!saveOK()) return;

    EntityManager em = OPDE.createEM();
    try {
      em.getTransaction().begin();
      MedProducts myProduct = em.merge(product);

      myProduct.setText(txtName.getText().trim());
      myProduct.setSideEffects(txtSideEffects.getText().trim());
      myProduct.setACME(em.merge((ACME) cmbAcme.getSelectedItem()));

      for (TradeForm tf : myProduct.getTradeforms()) {
        em.lock(em.merge(tf), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
        for (MedPackage mp : tf.getPackages()) {
          em.lock(em.merge(mp), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
        }
      }

      em.lock(myProduct, LockModeType.OPTIMISTIC);

      em.getTransaction().commit();

      product = myProduct;
    } catch (Exception e) {
      if (em.getTransaction().isActive()) {
        em.getTransaction().rollback();
      }
      OPDE.fatal(e);
    } finally {
      em.close();
    }
    dispose();

    // hier gehts weiter. prüf auch die anderen locks bei den anderen editoren

  } // GEN-LAST:event_btnOKActionPerformed
Example #9
0
  private void commonTestLockLockModeIsolations(
      EntityManager em,
      LockModeType lockMode,
      int expectedSupportSQLCount,
      String expectedSupportSQL,
      int expectedNonSupportSQLCount,
      String expectedNonSupportSQL,
      int expectedVersionUpdateCount,
      String expectedVersionUpdateSQL) {
    OpenJPAEntityManager oem = (OpenJPAEntityManager) em.getDelegate();
    JDBCFetchConfigurationImpl fConfig =
        (JDBCFetchConfigurationImpl) ((EntityManagerImpl) oem).getBroker().getFetchConfiguration();
    DBDictionary dict =
        ((JDBCConfiguration) ((OpenJPAEntityManagerSPI) oem).getConfiguration())
            .getDBDictionaryInstance();

    em.clear();
    LockEmployee employee = em.find(LockEmployee.class, 1);
    resetSQL();
    int beforeIsolation = fConfig.getIsolation();
    em.lock(employee, lockMode);
    if (dict.supportsIsolationForUpdate() && dict instanceof DB2Dictionary) {
      assertEquals(expectedSupportSQLCount, getSQLCount());
      if (expectedSupportSQL != null) assertAllSQLInOrder(expectedSupportSQL);
    } else {
      assertEquals(expectedNonSupportSQLCount, getSQLCount());
      if (expectedNonSupportSQL != null) assertAllSQLInOrder(expectedNonSupportSQL);
    }

    resetSQL();
    em.flush();
    assertEquals(expectedVersionUpdateCount, getSQLCount());
    if (expectedVersionUpdateSQL != null) assertAllSQLInOrder(expectedVersionUpdateSQL);

    assertEquals(beforeIsolation, fConfig.getIsolation());
  }
 public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
   entity = getEntity(entity);
   delegate.lock(entity, lockMode, properties);
 }
  public void testAssassinOptimisticLockingUsingEntityManagerAPI() {
    // Cannot create parallel entity managers in the server.
    if (!isOnServer()) {
      EntityManager em = createEntityManager();
      beginTransaction(em);
      Assassin assassin = null;

      try {
        assassin = new Assassin();
        assassin.setName("OptLockAssassin");
        em.persist(assassin);
        commitTransaction(em);
      } catch (RuntimeException ex) {
        if (isTransactionActive(em)) {
          rollbackTransaction(em);
        }

        closeEntityManager(em);
        throw ex;
      }

      EntityManager em2 = createEntityManager();
      Exception optimisticLockException = null;
      beginTransaction(em);

      try {
        assassin = em.find(Assassin.class, assassin.getId());
        em.lock(assassin, LockModeType.WRITE);
        beginTransaction(em2);

        try {
          Assassin assassin2 = em2.find(Assassin.class, assassin.getId());
          assassin2.setName("OptLockAssassin2");
          commitTransaction(em2);
          em2.close();
        } catch (RuntimeException ex) {
          if (isTransactionActive(em2)) {
            rollbackTransaction(em2);
          }

          closeEntityManager(em2);
          throw ex;
        }

        try {
          em.flush();
        } catch (PersistenceException exception) {
          if (exception instanceof OptimisticLockException) {
            optimisticLockException = exception;
          } else {
            throw exception;
          }
        }

        rollbackTransaction(em);
      } catch (RuntimeException ex) {
        if (isTransactionActive(em)) {
          rollbackTransaction(em);
        }

        closeEntityManager(em);
        throw ex;
      }

      try {
        beginTransaction(em);
        assassin = em.find(Assassin.class, assassin.getId());
        em.remove(assassin);
        commitTransaction(em);
      } catch (RuntimeException ex) {
        if (isTransactionActive(em)) {
          rollbackTransaction(em);
        }

        closeEntityManager(em);
        throw ex;
      }

      assertFalse(
          "Proper exception not thrown when EntityManager.lock(object, OPTIMISTIC) is used.",
          optimisticLockException == null);
    }
  }
 @Override
 public void lock(Object arg0, LockModeType arg1, Map<String, Object> arg2) {
   // TODO Auto-generated method stub
   myEntityManager.lock(arg0, arg1, arg2);
 }
Example #13
0
 public void lock(Object entity, LockModeType lm) {
   delegate.lock(entity, lm);
 }