コード例 #1
1
 /**
  * トランザクションをコミットまたはロールバックします。
  *
  * <p>現在のスレッドに関連づけられているトランザクションがアクティブな場合は、 トランザクションをコミットします。 それ以外の場合はトランザクションをロールバックします。
  *
  * @throws Exception トランザクションマネージャで例外が発生した場合にスローされます
  * @see javax.transaction.TransactionManager#commit()
  * @see javax.transaction.TransactionManager#rollback()
  */
 protected void end() throws Exception {
   if (userTransaction.getStatus() == STATUS_ACTIVE) {
     userTransaction.commit();
   } else {
     userTransaction.rollback();
   }
 }
コード例 #2
0
  @Test(expected = EntityNotFoundException.class)
  @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT)
  public void testRemoveOfficeType() throws Exception {
    GovernmentOfficeType officeType;
    try {
      utx.begin();
      officeType = getDocumentsOfficesDAO().createRootOfficeType("name");
    } finally {
      utx.commit();
    }

    if (officeType == null) {
      Assert.fail("Office type shouldn't be NULL");
    }

    BigInteger officeTypeID = officeType.getID();

    try {
      utx.begin();
      try {
        GovernmentOfficeType foundOfficeType =
            getDocumentsOfficesDAO().findOfficeType(officeType.getID());
        Assert.assertNotNull(foundOfficeType);
      } catch (EntityNotFoundException e) {
        Assert.fail("Created office type is not found");
      }
      getDocumentsOfficesDAO().removeOfficeType(officeType);
      getDocumentsOfficesDAO().findOfficeType(officeTypeID);
    } finally {
      utx.commit();
    }
  }
コード例 #3
0
  @Test(expected = EntityNotFoundException.class)
  @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT)
  public void testRemoveDocumentTemplate() throws Exception {
    DocumentTemplate documentTemplate;
    try {
      utx.begin();
      documentTemplate =
          getDocumentsOfficesDAO().createDocumentTemplate("name", "%s", "%d", "officeTypeName");
    } finally {
      utx.commit();
    }

    if (documentTemplate == null) {
      Assert.fail("Document template shouldn't be NULL");
    }

    BigInteger documentTemplateID = documentTemplate.getID();

    try {
      utx.begin();
      try {
        DocumentTemplate foundDocumentTemplate =
            getDocumentsOfficesDAO().findDocumentTemplate(documentTemplate.getID());
        Assert.assertNotNull(foundDocumentTemplate);
      } catch (EntityNotFoundException e) {
        Assert.fail("Created document template is not found");
      }
      getDocumentsOfficesDAO().removeDocumentTemplate(documentTemplate);
      getDocumentsOfficesDAO().findDocumentTemplate(documentTemplateID);
    } finally {
      utx.commit();
    }
  }
コード例 #4
0
  @Test(expected = EntityNotFoundException.class)
  @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT)
  public void testRemoveEmail() throws Exception {
    Email email;
    try {
      utx.begin();
      User owner = getUserDAO().createUser("name", "name", "not name", "nick", "without password");
      email = getUserDAO().createUserEmail("address", owner);
    } finally {
      utx.commit();
    }

    if (email == null) {
      Assert.fail("Email shouldn't be NULL");
    }

    BigInteger emailID = email.getID();

    try {
      utx.begin();
      try {
        Email foundEmail = getUserDAO().findEmail(emailID);
        Assert.assertNotNull(foundEmail);
      } catch (EntityNotFoundException e) {
        Assert.fail("Created email is not found");
      }
      getUserDAO().removeUserEmail(email);
      getUserDAO().findEmail(emailID);
    } finally {
      utx.commit();
    }
  }
コード例 #5
0
  @Test(expected = EntityNotFoundException.class)
  @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT)
  public void testRemoveUser() throws Exception {
    User user;
    try {
      utx.begin();
      user = getUserDAO().createUser("name", "name", "name", "nick", "password");
    } finally {
      utx.commit();
    }

    if (user == null) {
      Assert.fail("User shouldn't be NULL");
    }

    BigInteger userID = user.getID();

    try {
      utx.begin();
      try {
        User foundUser = getUserDAO().findUser(userID);
        Assert.assertNotNull(foundUser);
      } catch (EntityNotFoundException e) {
        Assert.fail("Created user is not found");
      }
      getUserDAO().removeUser(user);
      getUserDAO().findUser(userID);
    } finally {
      utx.commit();
    }
  }
コード例 #6
0
  /** Test deleting user. */
  @Test
  public void testDeleteUser() throws Exception {
    System.out.println(">>> Deleting user");
    UserTransaction tx = getUserTransaction();
    try {
      AdminEJBLocal instance = (AdminEJBLocal) getEJBInstance(AdminEJB.class.getSimpleName());
      tx.begin();
      // Get user
      User user = instance.getUser(USER_NAME);
      tx.commit();

      assertNotNull("Failed to get user", user);

      user.setEntityAction(EntityAction.DELETE);

      tx.begin();
      User deltedUser = instance.saveUser(user);
      tx.commit();

      assertNull("Failed to delete user", deltedUser);

      System.out.println(">>> User has been deleted!");

    } catch (Exception e) {
      tx.rollback();
      fail(e.getMessage());
    }
  }
コード例 #7
0
  /** Test deleting group. */
  @Test
  public void testDeleteGroup() throws Exception {
    System.out.println(">>> Deleting group");
    UserTransaction tx = getUserTransaction();
    try {
      AdminEJBLocal instance = (AdminEJBLocal) getEJBInstance(AdminEJB.class.getSimpleName());
      tx.begin();
      // Get group
      Group group = instance.getGroup(GROUP_ID);
      tx.commit();

      assertNotNull("Failed to get group", group);

      group.setEntityAction(EntityAction.DELETE);

      tx.begin();
      Group deltedGroup = instance.saveGroup(group);
      tx.commit();

      assertNull("Failed to delete group", deltedGroup);

      System.out.println(">>> Group has been deleted!");

    } catch (Exception e) {
      tx.rollback();
      fail(e.getMessage());
    }
  }
コード例 #8
0
  @Test(expected = EntityNotFoundException.class)
  @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT)
  public void testRemoveBank() throws Exception {
    Bank bank;
    try {
      utx.begin();
      bank = getBankDAO().createBank("bank", "site");
    } finally {
      utx.commit();
    }

    if (bank == null) {
      Assert.fail("Bank shouldn't be NULL");
    }

    BigInteger bankID = bank.getID();

    try {
      utx.begin();
      try {
        Bank foundBank = getBankDAO().findBank(bankID);
        Assert.assertNotNull(foundBank);
      } catch (EntityNotFoundException e) {
        Assert.fail("Created bank is not found");
      }
      getBankDAO().removeBank(bank);
      getBankDAO().findBank(bankID);
    } finally {
      utx.commit();
    }
  }
コード例 #9
0
  /** Test changing group. */
  @Test
  public void testModifyGroup() throws Exception {
    System.out.println(">>> Modifying group");
    UserTransaction tx = getUserTransaction();
    try {
      AdminEJBLocal instance = (AdminEJBLocal) getEJBInstance(AdminEJB.class.getSimpleName());
      tx.begin();
      // Get group
      Group group = instance.getGroup(GROUP_ID);
      if (group != null) {
        group.getGroupRoles();
      }
      tx.commit();

      assertNotNull("Failed to get group", group);
      assertNotNull("Group name is null", group.getName());
      assertNotNull("Group description is null", group.getDescription());
      assertNotNull("Group roles is null", group.getGroupRoles());
      int rolesSize = group.getGroupRoles().size();

      group.setEntityAction(EntityAction.UPDATE);

      if (rolesSize > 1) {
        group.getGroupRoles().get(0).setEntityAction(EntityAction.DELETE);
        rolesSize -= 1;
      }

      group.setName("Updated Test group");
      group.setDescription("Updated description for group");

      tx.begin();
      Group updatedGroup = instance.saveGroup(group);
      tx.commit();

      // Re-read group
      tx.begin();
      updatedGroup = instance.getGroup(GROUP_ID);
      if (updatedGroup != null) {
        updatedGroup.getGroupRoles();
      }
      tx.commit();

      assertNotNull("Failed to get modified group", updatedGroup);
      assertEquals("Group name wasn't modified", updatedGroup.getName(), group.getName());
      assertEquals(
          "Group description wasn't modified",
          updatedGroup.getDescription(),
          group.getDescription());
      assertNotNull("Modified group roles is null", group.getGroupRoles());
      assertEquals("Group roles wasn't modified", updatedGroup.getGroupRoles().size(), rolesSize);

      System.out.println(">>> Group has been modified!");

    } catch (Exception e) {
      tx.rollback();
      fail(e.getMessage());
    }
  }
コード例 #10
0
  @Test(expected = EntityNotFoundException.class)
  @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT)
  public void testRemoveDocument() throws Exception {
    Document document;
    try {
      utx.begin();
      GovernmentOfficeType officeType = getDocumentsOfficesDAO().createRootOfficeType("name");
      GovernmentOffice office =
          getDocumentsOfficesDAO()
              .createOffice(
                  "name",
                  "state",
                  "city",
                  "street",
                  (short) 50,
                  (short) 38,
                  (short) 542,
                  546123,
                  null,
                  officeType);
      DocumentTemplate documentTemplate =
          getDocumentsOfficesDAO().createDocumentTemplate("name", "%s", "%d", officeType);
      User owner =
          getUserDAO()
              .createUser(
                  "user last name",
                  "user first name",
                  "user middle name",
                  "user nick name",
                  "user password");
      document =
          getDocumentsOfficesDAO()
              .createDocument(
                  "passport", "MA", 128554L, new Date(), owner, office, documentTemplate);
    } finally {
      utx.commit();
    }

    if (document == null) {
      Assert.fail("Document shouldn't be NULL");
    }

    BigInteger documentID = document.getID();

    try {
      utx.begin();
      try {
        Document foundDocument = getDocumentsOfficesDAO().findDocument(document.getID());
        Assert.assertNotNull(foundDocument);
      } catch (EntityNotFoundException e) {
        Assert.fail("Created document is not found");
      }
      getDocumentsOfficesDAO().removeDocument(document);
      getDocumentsOfficesDAO().findDocument(documentID);
    } finally {
      utx.commit();
    }
  }
コード例 #11
0
  public void testLoggingAutoActivate() throws Throwable {
    assertFalse(
        "Auto-logging of misuse of the wrapper should be off",
        BorrowedConnectionProxy.isCallStackTraced());

    UserTransaction txn = transactionService.getUserTransaction();
    Connection connection;
    try {
      txn.begin();
      // Dig the proxy out of ... somewhere
      ConnectionHolder conHolder =
          (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
      connection = conHolder.getConnection();
      txn.commit();
    } catch (Throwable e) {
      try {
        txn.rollback();
      } catch (Throwable ee) {
      }
      throw e;
    }
    // Now mess with the connection, which is protected by the Hibernate wrapper
    try {
      connection.commit();
      fail("Use case should have generated a HibernateException");
    } catch (HibernateException e) {
      // Expected
    }
    assertTrue(
        "Auto-logging of misuse of the wrapper should now be on",
        BorrowedConnectionProxy.isCallStackTraced());

    // Now start a new transaction and we should see logging
    txn = transactionService.getUserTransaction();
    try {
      txn.begin();
      // Dig the proxy out of ... somewhere
      ConnectionHolder conHolder =
          (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
      connection = conHolder.getConnection();
      txn.commit();
    } catch (Throwable e) {
      try {
        txn.rollback();
      } catch (Throwable ee) {
      }
      throw e;
    }
    // Now mess with the connection, which is protected by the Hibernate wrapper
    try {
      connection.commit();
      fail("Use case should have generated a HibernateException");
    } catch (HibernateException e) {
      // Expected
    }
    // Check for error logs
  }
コード例 #12
0
  @Test
  public void testInsert() throws Exception {
    assertNotNull(utx);

    // flushing database
    utx.begin();
    em.joinTransaction();
    em.createQuery("delete from Game").executeUpdate();
    utx.commit();

    // insert records
    utx.begin();
    em.joinTransaction();
    System.out.println("Inserting records...");
    for (String title : GAME_TITLES) {
      Game game = new Game(title);
      em.persist(game);
    }
    utx.commit();

    List<Game> games;

    // query with JPQL
    utx.begin();
    em.joinTransaction();
    System.out.println("Selecting (using JPQL)...");
    games = em.createQuery("select g from Game g order by g.id").getResultList();
    System.out.println("Found " + games.size() + " games (using JPQL)");
    assertEquals(GAME_TITLES.length, games.size());
    for (int i = 0; i < GAME_TITLES.length; i++) {
      assertEquals(GAME_TITLES[i], games.get(i).getTitle());
      System.out.println(games.get(i));
    }
    utx.commit();

    // query with Criteria
    utx.begin();
    em.joinTransaction();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Game> criteria = builder.createQuery(Game.class);

    Root<Game> game = criteria.from(Game.class);
    criteria.select(game);
    criteria.orderBy(builder.asc(game.get(Game_.id)));
    System.out.println("Selecting (using Criteria)...");
    games = em.createQuery(criteria).getResultList();
    System.out.println("Found " + games.size() + " games (using Criteria)");
    assertEquals(GAME_TITLES.length, games.size());
    for (int i = 0; i < GAME_TITLES.length; i++) {
      assertEquals(GAME_TITLES[i], games.get(i).getTitle());
      System.out.println(games.get(i));
    }
    utx.commit();
  }
コード例 #13
0
 public String guardarDireccion(GthDireccion direccion) {
   EntityManager manejador = fabrica.createEntityManager();
   try {
     utx.begin();
     manejador.joinTransaction();
     // Guarda o modifica direccion
     if (direccion.getIdeGtdir() == null) {
       long idegtdir =
           new Long(utilitario.getConexion().getMaximo("GTH_DIRECCION", "IDE_GTDIR", 1));
       Integer conertideaspvh = (int) idegtdir;
       direccion.setIdeGtdir(conertideaspvh); // maximo de utilitario
       manejador.persist(direccion);
     } else {
       manejador.merge(direccion);
     }
     utx.commit();
   } catch (Exception e) {
     try {
       utx.rollback();
     } catch (Exception e1) {
     }
     return e.getMessage();
   } finally {
     manejador.close();
   }
   return "";
 }
コード例 #14
0
 public void edit(Bitacora bitacora)
     throws NonexistentEntityException, RollbackFailureException, Exception {
   EntityManager em = null;
   try {
     utx.begin();
     em = getEntityManager();
     bitacora = em.merge(bitacora);
     utx.commit();
   } catch (Exception ex) {
     try {
       utx.rollback();
     } catch (Exception re) {
       throw new RollbackFailureException(
           "An error occurred attempting to roll back the transaction.", re);
     }
     String msg = ex.getLocalizedMessage();
     if (msg == null || msg.length() == 0) {
       BitacoraId id = bitacora.getId();
       if (findBitacora(id) == null) {
         throw new NonexistentEntityException("The bitacora with id " + id + " no longer exists.");
       }
     }
     throw ex;
   } finally {
     if (em != null) {
       em.close();
     }
   }
 }
コード例 #15
0
  public String guardarTelefono(GthTelefono telefono) {
    EntityManager manejador = fabrica.createEntityManager();
    try {
      utx.begin();
      if (telefono.getIdeGttel() == null) {
        // asignar maximo

        long ideaspvh =
            new Long(utilitario.getConexion().getMaximo("GTH_TELEFONO", "IDE_GTTEL", 1));
        System.out.println("guardar telefono " + ideaspvh);
        Integer conertideaspvh = 1; // (int) ideaspvh;
        telefono.setIdeGttel(conertideaspvh); // maximo de utilitario
        System.out.println("telefono " + telefono);
        manejador.persist(telefono);
      } else {
        manejador.merge(telefono);
      }
      utx.commit();
    } catch (Exception e) {
      try {
        utx.rollback();
      } catch (Exception e1) {
      }
      return e.getMessage();
    } finally {
      manejador.close();
    }
    return "";
  }
コード例 #16
0
  @Override
  public SessionDto register(String username, String password, String name, String email) {
    log.debug("registering new user: "******"Could not register user!", e);
      throw new RuntimeException("Could not register user!");
    }
  }
コード例 #17
0
  @Override
  public SessionDto login(String username, String attemptedPassword) {
    log.debug("logging in user: "******"Could not log in!", e);
      throw new RuntimeException("Could not log in!");
    }
  }
コード例 #18
0
  @Test
  @InSequence(2)
  @Ignore
  public void testTransactionCommit() throws Throwable {
    userTx.begin();
    HazelcastConnection c = getConnection();
    try {
      TransactionalMap<String, String> m = c.getTransactionalMap("testTransactionCommit");

      m.put("key", "value");

      doSql();

      assertEquals("value", m.get("key"));
    } finally {
      c.close();
    }
    userTx.commit();
    HazelcastConnection con2 = getConnection();

    try {
      assertEquals("value", con2.getMap("testTransactionCommit").get("key"));
      validateSQLdata(true);
    } finally {
      con2.close();
    }
  }
コード例 #19
0
  public void deletePPE(int w, int d, String t) {
    FacesMessage msg;
    Pruefplaneintrag ppe = pkh.findPPEByTimeAndDay(w, d, t);
    Pruefperioden currenPruefperiode = ppe.getPruefPeriode();
    int ppeId = ppe.getPpid();
    Logger.getLogger(PruefplaneintragHandler.class.getName())
        .log(Level.INFO, "Start deletePPE, selected: {0}", ppeId);
    try {

      utx.begin();
      em.remove(em.merge(ppe));
      utx.commit();

      this.updateStatus(ppe, new ArrayList<Pruefplaneintrag>());
      Logger.getLogger(PruefplaneintragHandler.class.getName())
          .log(Level.INFO, "Success at deletePPE, deleted: {0}", ppe.getPpid());
      msg =
          new FacesMessage(
              FacesMessage.SEVERITY_INFO,
              "Prüfung gelöscht: ",
              ppe.getSgmid().getModID().getModName());
      FacesContext.getCurrentInstance().addMessage(null, msg);
      allPpe = this.findAllPPE();
      pkh.updateWeek(currenPruefperiode.getPPWoche());
    } catch (Exception ex) {
      Logger.getLogger(PruefplaneintragHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
コード例 #20
0
  private void testStartProcess(RuntimeEngine runtime) throws Exception {

    synchronized (
        (SingleSessionCommandService)
            ((CommandBasedStatefulKnowledgeSession) runtime.getKieSession()).getRunner()) {
      UserTransaction ut =
          (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
      try {
        ut.begin();
        logger.debug("Starting process on ksession {}", runtime.getKieSession().getIdentifier());
        Map<String, Object> params = new HashMap<String, Object>();
        DateTime now = new DateTime();
        now.plus(1000);

        params.put("x", "R2/" + wait + "/PT1S");
        ProcessInstance processInstance =
            runtime.getKieSession().startProcess("IntermediateCatchEvent", params);
        logger.debug(
            "Started process instance {} on ksession {}",
            processInstance.getId(),
            runtime.getKieSession().getIdentifier());
        ut.commit();
      } catch (Exception ex) {
        ut.rollback();
        throw ex;
      }
    }
  }
コード例 #21
0
ファイル: servicioConducta.java プロジェクト: diego10j/sigac
  public String guardarConducta(EquivalenciaConducta iconducta) {
    EquivalenciaConducta conducta = iconducta;
    try {
      utx.begin();
      manejador.joinTransaction();
      // nombre tabla y atributo
      if (conducta.getEqcCodigo() == null) {
        long lon_codigo =
            utilitario.getConexion().getMaximo("Equivalencia_conducta", "eqc_codigo", 1);
        conducta.setEqcCodigo(new Integer(String.valueOf(lon_codigo)));
        System.out.println("ide " + lon_codigo);
        conducta.setEqcCodigo(new Integer(String.valueOf(lon_codigo)));
        manejador.persist(conducta);
      } else {
        manejador.merge(conducta);
      }

      utx.commit();
    } catch (Exception e) {
      try {
        utx.rollback();
      } catch (Exception e1) {
      }
      e.printStackTrace();
      return e.getMessage();
    }
    return "";
  }
コード例 #22
0
 public void create(Bitacora bitacora)
     throws PreexistingEntityException, RollbackFailureException, Exception {
   if (bitacora.getId() == null) {
     bitacora.setId(new BitacoraId());
   }
   EntityManager em = null;
   try {
     utx.begin();
     em = getEntityManager();
     em.persist(bitacora);
     utx.commit();
   } catch (Exception ex) {
     try {
       utx.rollback();
     } catch (Exception re) {
       throw new RollbackFailureException(
           "An error occurred attempting to roll back the transaction.", re);
     }
     if (findBitacora(bitacora.getId()) != null) {
       throw new PreexistingEntityException("Bitacora " + bitacora + " already exists.", ex);
     }
     throw ex;
   } finally {
     if (em != null) {
       em.close();
     }
   }
 }
コード例 #23
0
 public String guardarCargaFamiliar(GthCargasFamiliares carga) {
   EntityManager manejador = fabrica.createEntityManager();
   try {
     utx.begin();
     manejador.joinTransaction();
     // Guarda o modifica
     if (carga.getIdeGtcaf() == null) {
       long idegtcaf =
           new Long(utilitario.getConexion().getMaximo("GTH_CARGAS_FAMILIARES", "IDE_GTCAF", 1));
       Integer conertideaspvh = (int) idegtcaf;
       carga.setIdeGtcaf(conertideaspvh);
       manejador.persist(carga);
     } else {
       manejador.merge(carga);
     }
     utx.commit();
   } catch (Exception e) {
     try {
       utx.rollback();
     } catch (Exception e1) {
     }
     return e.getMessage();
   } finally {
     manejador.close();
   }
   return "";
 }
コード例 #24
0
  @Override
  public void updateComment(Comment comment)
      throws NonExistingEntityException, IllegalArgumentException {

    if (comment == null) {
      throw new IllegalArgumentException("Comment is null.");
    }

    if (comment.getId() == null) {
      throw new IllegalArgumentException("Comment id is null.");
    }

    commentCache = provider.getCacheContainer().getCache("commentcache");

    if (!commentCache.containsKey(comment.getId())) {
      throw new NonExistingEntityException("Comment does not exist in cache.");
    }

    try {
      userTransaction.begin();
      commentCache.put(comment.getId(), comment);
      userTransaction.commit();
      logger.info("Comment with id: " + comment.getId() + " was updated in cache store.");
    } catch (Exception e) {
      if (userTransaction != null) {
        try {
          userTransaction.rollback();
        } catch (Exception e1) {
          e1.printStackTrace();
        }
      }
      logger.error("Error while updating comment.", e);
      throw new CacheException(e);
    }
  }
コード例 #25
0
 private void saveDomainEntityToRepositoryWithTransaction(Car domainEntity)
     throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException,
         HeuristicRollbackException {
   userTransaction.begin();
   carRepository.save(domainEntity);
   userTransaction.commit();
 }
コード例 #26
0
 public void destroy(BitacoraId id)
     throws NonexistentEntityException, RollbackFailureException, Exception {
   EntityManager em = null;
   try {
     utx.begin();
     em = getEntityManager();
     Bitacora bitacora;
     try {
       bitacora = em.getReference(Bitacora.class, id);
       bitacora.getId();
     } catch (EntityNotFoundException enfe) {
       throw new NonexistentEntityException(
           "The bitacora with id " + id + " no longer exists.", enfe);
     }
     em.remove(bitacora);
     utx.commit();
   } catch (Exception ex) {
     try {
       utx.rollback();
     } catch (Exception re) {
       throw new RollbackFailureException(
           "An error occurred attempting to roll back the transaction.", re);
     }
     throw ex;
   } finally {
     if (em != null) {
       em.close();
     }
   }
 }
コード例 #27
0
ファイル: SessionTest.java プロジェクト: psiroky/jbpm
 private void testStartProcess(SessionManagerFactory factory) throws Exception {
   SessionManager sessionManager = factory.getSessionManager();
   long taskId;
   synchronized (
       (SingleSessionCommandService)
           ((CommandBasedStatefulKnowledgeSession) sessionManager.getKnowledgeSession())
               .getCommandService()) {
     UserTransaction ut =
         (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
     ut.begin();
     System.out.println(
         "Starting process on ksession " + sessionManager.getKnowledgeSession().getId());
     ProcessInstance processInstance =
         sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null);
     System.out.println(
         "Started process instance "
             + processInstance.getId()
             + " on ksession "
             + sessionManager.getKnowledgeSession().getId());
     long workItemId =
         ((HumanTaskNodeInstance)
                 ((WorkflowProcessInstance) processInstance).getNodeInstances().iterator().next())
             .getWorkItemId();
     taskId = sessionManager.getTaskService().getTaskByWorkItemId(workItemId).getId();
     System.out.println("Created task " + taskId);
     ut.commit();
   }
   sessionManager.getTaskService().claim(taskId, "mary");
   sessionManager.dispose();
 }
  /**
   * Get the stored MD4 hashed password for the user, or null if the user does not exist
   *
   * @param userName String
   * @return MD4 hash or null
   */
  protected String getMD4Hash(String userName) {
    String md4hash = null;

    // Wrap the auth component calls in a transaction
    UserTransaction tx = transactionService.getUserTransaction();
    try {
      tx.begin();

      // Get the stored MD4 hashed password for the user, or null if the user does not exist
      md4hash = nltmAuthenticator.getMD4HashedPassword(userName);
    } catch (Throwable ex) {
      if (getLogger().isDebugEnabled()) getLogger().debug(ex);
    } finally {
      // Rollback/commit the transaction if still valid
      if (tx != null) {
        try {
          // Commit or rollback the transaction
          if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK
              || tx.getStatus() == Status.STATUS_ROLLEDBACK
              || tx.getStatus() == Status.STATUS_ROLLING_BACK) {
            // Transaction is marked for rollback
            tx.rollback();
          } else {
            // Commit the transaction
            tx.commit();
          }
        } catch (Throwable ex) {
          if (getLogger().isDebugEnabled()) getLogger().debug(ex);
        }
      }
    }

    return md4hash;
  }
コード例 #29
0
ファイル: SessionTest.java プロジェクト: psiroky/jbpm
  public void testNewSessionDispose() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2);
    KnowledgeBase kbase = kbuilder.newKnowledgeBase();
    SessionManagerFactory factory = new NewSessionSessionManagerFactory(kbase);
    final SessionManager sessionManager = factory.getSessionManager();
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null);
    TransactionManagerServices.getTransactionManager()
        .getTransaction()
        .registerSynchronization(
            new Synchronization() {
              public void beforeCompletion() {}

              public void afterCompletion(int status) {
                try {
                  sessionManager.dispose();
                } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
              }
            });
    ut.commit();
    factory.dispose();
  }
コード例 #30
-1
  public String eliminarConyugue(String ideGtemp) {
    EntityManager manejador = fabrica.createEntityManager();
    try {
      GthConyuge conygue = getConyuque(ideGtemp);
      if (conygue != null) {
        utx.begin();
        manejador.joinTransaction();
        // Borra telefono de conyugue
        List<GthTelefono> telefonos = getListaTelefonoConyugue(conygue.getIdeGtcon().toString());
        if (telefonos != null && !telefonos.isEmpty()) {
          for (GthTelefono telefonoActual : telefonos) {
            manejador.remove(telefonoActual);
          }
        }
        // Borra datos de union
        GthUnionLibre union = getUnionLibre(conygue.getIdeGtcon().toString());
        if (union != null) {
          manejador.remove(union);
        }
        manejador.remove(conygue);
        utx.commit();
      }

    } catch (Exception e) {
      try {
        utx.rollback();
      } catch (Exception e1) {
      }
      return e.getMessage();
    } finally {
      manejador.close();
    }
    return "";
  }