public static void modificarPuesto(int idEmpleado, String Puesto) {
   EmpleadoEntity empleado = getEmpleadoPorID(idEmpleado);
   EntityTransaction entityTransaction = ConexionBD.getEm().getTransaction();
   entityTransaction.begin();
   empleado.setPuesto(Puesto);
   entityTransaction.commit();
 }
  public User editUser(Long userId, String password, long bitmap) {
    if (password.isEmpty()) {
      return null;
    }

    Privileges privileges = new Privileges(bitmap);
    EntityTransaction transaction = startSaveTransaction();

    User user = getUserById(userId);
    if (user != null) {
      user.setPassword(password);
      user.setCategoryRead(privileges.isCategoryRead());
      user.setCategoryWrite(privileges.isCategoryWrite());
      user.setCategoryDelete(privileges.isCategoryDelete());
      user.setItemRead(privileges.isItemRead());
      user.setItemWrite(privileges.isItemWrite());
      user.setItemDelete(privileges.isItemDelete());
      user.setItemCommentRead(privileges.isItemCommentRead());
      user.setItemCommentWrite(privileges.isItemCommentWrite());
      user.setItemCommentDelete(privileges.isItemCommentDelete());
      user.setUserPromote(privileges.isUserPromote());
      user.setUserDemote(privileges.isUserDemote());
      user.setUserDelete(privileges.isUserDelete());
    }

    try {
      entityManager.persist(user);
      transaction.commit();
      return user;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Beispiel #3
0
 @Override
 public R apply(final D input) {
   RuntimeException rootCause = null;
   for (int i = 0; i < retries; i++) {
     EntityTransaction db = Entities.get(this.entityType);
     try {
       R ret = this.function.apply(input);
       db.commit();
       return ret;
     } catch (RuntimeException ex) {
       db.rollback();
       if (Exceptions.isCausedBy(ex, OptimisticLockException.class)) {
         rootCause = Exceptions.findCause(ex, OptimisticLockException.class);
       } else if (Exceptions.isCausedBy(ex, LockAcquisitionException.class)) {
         rootCause = Exceptions.findCause(ex, LockAcquisitionException.class);
       } else {
         rootCause = ex;
         Logs.extreme().error(ex, ex);
         throw ex;
       }
       try {
         TimeUnit.MILLISECONDS.sleep(20);
       } catch (InterruptedException ex1) {
         Exceptions.maybeInterrupted(ex1);
       }
       continue;
     }
   }
   throw (rootCause != null
       ? rootCause
       : new NullPointerException(
           "BUG: Transaction retry failed but root cause exception is unknown!"));
 }
  public Item editItem(
      Long itemId,
      String title,
      String description,
      BigDecimal price,
      Long categoryId,
      User updateUser) {
    if (updateUser == null || !updateUser.isItemWrite() || title.isEmpty() || price == null) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    Item item = getItem(itemId);
    if (item != null) {
      item.setTitle(title);
      item.setDescription(description);
      item.setPrice(price);
      item.setCategory(getCategoryById(categoryId));
      item.setUpdateUser(updateUser);
      item.setUpdateTimestamp(new Timestamp(new Date().getTime()));
    }

    try {
      entityManager.persist(item);
      transaction.commit();
      return item;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
  public Category editCategory(
      Long categoryId, String name, String description, String overpassKeyValue, User updateUser) {
    if (updateUser == null || !updateUser.isCategoryWrite() || name.isEmpty()) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    Category category = getCategoryById(categoryId);
    if (category != null) {
      category.setName(name);
      category.setDescription(description);
      category.setOverpassKeyValue(overpassKeyValue);
      category.setUpdateUser(updateUser);
      category.setUpdateTimestamp(new Timestamp(new Date().getTime()));
    }

    try {
      entityManager.persist(category);
      transaction.commit();
      return category;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
 public void guardar(Estado c) {
   EntityManager em = FactoryDAO.em;
   EntityTransaction etx = em.getTransaction();
   etx.begin();
   em.persist(c);
   etx.commit();
 }
  public List<InterestRate> getInterestRates() {

    // Obtains entity manager object
    EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();

    // Obtains transaction from entity manager
    EntityTransaction entr = entityManager.getTransaction();

    // -----------Begin transaction-----------
    List<InterestRate> interestRates = null;
    try {
      entr.begin();
      // Get a list of accounts from DB
      TypedQuery<InterestRate> query =
          entityManager.createQuery(
              "SELECT i FROM " + InterestRate.class.getName() + " i", InterestRate.class);
      interestRates = query.getResultList();
      entr.commit();
    } catch (Exception e) {
      entityManager.close();
    }
    // -----------End transaction-----------

    return interestRates;
  }
 /**
  * Updates or adds an agent to the database.
  *
  * @param agent The Agent you wish to modify or add in the database.
  */
 protected void updateAgentInDatabase(AgentImpl agent) {
   EntityManager em = null;
   EntityTransaction tx = null;
   try {
     em = emf.createEntityManager();
     tx = em.getTransaction();
     tx.begin();
     AgentImpl existing = getAgent(agent.getName(), agent.getOrganization(), em);
     if (existing == null) {
       em.persist(agent);
     } else {
       existing.setConfiguration(agent.getConfiguration());
       existing.setLastHeardFrom(agent.getLastHeardFrom());
       existing.setState(agent.getState());
       existing.setSchedulerRoles(agent.getSchedulerRoles());
       existing.setUrl(agent.getUrl());
       em.merge(existing);
     }
     tx.commit();
   } catch (RollbackException e) {
     logger.warn("Unable to commit to DB in updateAgent.");
     throw e;
   } finally {
     if (em != null) em.close();
   }
 }
 /**
  * Retrieve a task list for the user. Tasks are retrieved from the storage for the user performing
  * the request.
  *
  * @return A list of tasks
  */
 private List<Task> retrieveTaskList() {
   List<Task> lstTasks = new LinkedList<>();
   EntityManager em = getEntityManager();
   EntityTransaction et = null;
   List<Object[]> taskList = null;
   try {
     et = em.getTransaction();
     et.begin();
     taskList =
         em.createNamedQuery("tasks.userAll").setParameter("user", getUser()).getResultList();
     et.commit();
   } catch (RuntimeException re) {
     if (et != null && et.isActive()) {
       et.rollback();
     }
     log.error("Impossible to retrieve the task list");
     log.error(re);
     throw new RuntimeException("Impossible to access the task list");
   } finally {
     em.close();
   }
   if (taskList != null && !taskList.isEmpty()) {
     for (Object[] elem : taskList) {
       int idElem = 0;
       Task tmpTask = new Task();
       tmpTask.setId((String) elem[idElem++]);
       tmpTask.setDescription((String) elem[idElem++]);
       tmpTask.setState((Task.STATE) elem[idElem++]);
       tmpTask.setDateCreated((Date) elem[idElem]);
       lstTasks.add(tmpTask);
     }
   }
   return lstTasks;
 }
  public static void create(Localidad localidad) {

    EntityManager entityManager = PersistenceManager.getEntityManager();

    EntityTransaction tr = entityManager.getTransaction();

    tr.begin();

    try {
      entityManager.persist(localidad);
      tr.commit();
      System.out.println(
          "Creación de localidad:"
              + localidad.getNombre()
              + ", de la prov: "
              + localidad.getProvincia().getNombre()
              + " exitosa");
    } catch (Exception ex) {
      tr.rollback();
      System.err.println(
          "Error en LibroDAO.create"
              + "("
              + Thread.currentThread().getStackTrace()[1].getLineNumber()
              + "):"
              + ex.getLocalizedMessage());
    } finally {
      entityManager.close();
    }
  }
Beispiel #11
0
  public void queryMedicalHistory4() {
    EntityManager em = emf.createEntityManager();
    Map medicals = new HashMap();
    long ssn = 0;
    EntityTransaction tran = em.getTransaction();
    tran.begin();
    String jpql = "select m from MedicalHistory2 m";
    Query q = em.createQuery(jpql);
    List<MedicalHistory2> ms = q.getResultList();
    for (MedicalHistory2 m : ms) {
      ssn = m.getId();
    }
    tran.commit();
    em.close();

    em = emf.createEntityManager();
    tran = em.getTransaction();
    tran.begin();
    jpql = "select m from MedicalHistory2 m where m.patient.ssn = " + ssn;
    q = em.createQuery(jpql);
    ms = q.getResultList();
    for (MedicalHistory2 m : ms) {
      assertMedicalHistory2(m);
    }
    tran.commit();
    em.close();

    findObj4(ssn);
  }
Beispiel #12
0
  @Test
  @RunOrder(5)
  public void deleteByEntityTest() {

    getForUpfate();
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    try {
      transaction.begin();
      // ============= Query construction ============== //
      JpaQueryStream<Person> stream =
          JpaQueryProvider.delete(em, Person.class)
              .where()
              .equal(Person::getPersonalNo, PERSONAL_NO2)
              .and()
              .like(Person::getLastName, "lname%")
              .and()
              .startsWith(Person::getFirstName, "fname");
      int rows = stream.execute();
      // =============================================//
      transaction.commit();
      System.out.println();
      System.out.println("-------Entity----");
      System.out.println();
      System.out.format("deleted %s rows\n", rows);
      Assert.assertEquals("No expected row number was updated", rows, 1);
    } catch (Throwable ex) {
      rollback(transaction);
    } finally {
      em.close();
    }
  }
Beispiel #13
0
  private void getForUpfate() {

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    try {
      JpaQueryStream<Person> stream =
          JpaQueryProvider.select(em, Person.class)
              .where()
              .equal(Person::getPersonalNo, PERSONAL_NO2)
              .and()
              .like(Person::getLastName, "lname%")
              .and()
              .startsWith(Person::getFirstName, "fname");
      Person person = stream.getFirst();
      transaction.begin();
      if (person == null) {
        Person newPerson = QueryTest.initPerson();
        em.persist(newPerson);
        person = newPerson;
      }
      transaction.commit();
    } catch (Throwable ex) {
      rollback(transaction);
    } finally {
      em.close();
    }
  }
  /**
   * Update person
   *
   * @param p
   * @return
   */
  public Person updatePerson(Person p) {

    // Call setters
    if (p.birthdate != null) {
      this.setBirthdate(p.birthdate);
    }
    if (p.email != null) {
      this.setEmail(p.email);
    }
    if (p.firstname != null) {
      this.setFirstname(p.getFirstname());
    }
    if (p.lastname != null) {
      this.setLastname(p.getLastname());
    }

    EntityManager em = LifeStyleDao.instance.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    p = em.merge(this);
    tx.commit();
    LifeStyleDao.instance.closeConnections(em);

    return p;
  }
  /**
   * Add launch permissions.
   *
   * @param accountIds
   */
  public void addPermissions(final List<String> accountIds) {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
      final ImageInfo entity = Entities.merge(this);
      Iterables.all(
          accountIds,
          new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
              try {
                final Account account = Accounts.lookupAccountById(input);
                ImageInfo.this.getPermissions().add(input);
              } catch (final Exception e) {
                try {
                  final User user = Accounts.lookupUserById(input);
                  ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                } catch (AuthException ex) {
                  try {
                    final User user = Accounts.lookupUserByAccessKeyId(input);
                    ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                  } catch (AuthException ex1) {
                    LOG.error(ex1, ex1);
                  }
                }
              }
              return true;
            }
          });
      db.commit();
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
    }
  }
Beispiel #16
0
  private void withoutBatch() {
    // tag::batch-session-batch-example[]
    EntityManager entityManager = null;
    EntityTransaction txn = null;
    try {
      entityManager = entityManagerFactory().createEntityManager();

      txn = entityManager.getTransaction();
      txn.begin();

      for (int i = 0; i < 100_000; i++) {
        Person Person = new Person(String.format("Person %d", i));
        entityManager.persist(Person);
      }

      txn.commit();
    } catch (RuntimeException e) {
      if (txn != null && txn.isActive()) txn.rollback();
      throw e;
    } finally {
      if (entityManager != null) {
        entityManager.close();
      }
    }
    // end::batch-session-batch-example[]
  }
  /**
   * Remove launch permissions.
   *
   * @param accountIds
   */
  public void removePermissions(final List<String> accountIds) {

    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
      final ImageInfo entity = Entities.merge(this);
      Iterables.all(
          accountIds,
          new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
              try {
                final Account account = Accounts.lookupAccountById(input);
                ImageInfo.this.getPermissions().remove(input);
              } catch (final Exception e) {
                LOG.error(e, e);
              }
              return true;
            }
          });

      db.commit();
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
    }
  }
Beispiel #18
0
  private void withBatch() {
    int entityCount = 100;
    // tag::batch-session-batch-insert-example[]
    EntityManager entityManager = null;
    EntityTransaction txn = null;
    try {
      entityManager = entityManagerFactory().createEntityManager();

      txn = entityManager.getTransaction();
      txn.begin();

      int batchSize = 25;

      for (int i = 0; i < entityCount; ++i) {
        Person Person = new Person(String.format("Person %d", i));
        entityManager.persist(Person);

        if (i % batchSize == 0) {
          // flush a batch of inserts and release memory
          entityManager.flush();
          entityManager.clear();
        }
      }

      txn.commit();
    } catch (RuntimeException e) {
      if (txn != null && txn.isActive()) txn.rollback();
      throw e;
    } finally {
      if (entityManager != null) {
        entityManager.close();
      }
    }
    // end::batch-session-batch-insert-example[]
  }
 public void modificar(Estado c) {
   EntityManager em = FactoryDAO.em;
   EntityTransaction etx = em.getTransaction();
   etx.begin();
   em.merge(c);
   etx.commit();
 }
 // cr�ation d'objets
 public static void test1() throws ParseException {
   // contexte de persistance
   EntityManager em = getEntityManager();
   // cr�ation personnes
   p1 =
       new Personne(
           "Martin", "Paul", new SimpleDateFormat("dd/MM/yy").parse("31/01/2000"), true, 2);
   p2 =
       new Personne(
           "Durant", "Sylvie", new SimpleDateFormat("dd/MM/yy").parse("05/07/2001"), false, 0);
   // cr�ation adresses
   a1 = new Adresse("8 rue Boileau", null, null, "49000", "Angers", null, "France");
   a2 = new Adresse("Apt 100", "Les Mimosas", "15 av Foch", "49002", "Angers", "03", "France");
   a3 = new Adresse("x", "x", "x", "x", "x", "x", "x");
   a4 = new Adresse("y", "y", "y", "y", "y", "y", "y");
   // associations personne <--> adresse
   p1.setAdresse(a1);
   p2.setAdresse(a2);
   // d�but transaction
   EntityTransaction tx = em.getTransaction();
   tx.begin();
   // persistance des personnes
   em.persist(p1);
   em.persist(p2);
   // et des adresses a3 et a4 non li�es � des personnes
   em.persist(a3);
   em.persist(a4);
   // fin transaction
   tx.commit();
   // on affiche les tables
   dumpPersonne();
   dumpAdresse();
 }
  public InterestRate getInterestRateByInterestRateId(String interestRateId) {

    // Obtains entity manager object
    EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();

    // Obtains transaction from entity manager
    EntityTransaction entr = entityManager.getTransaction();

    // -----------Begin transaction-----------
    InterestRate interestRate = null;
    try {
      entr.begin();
      // Get a list of accounts from DB
      TypedQuery<InterestRate> query =
          entityManager.createQuery(
              "SELECT i FROM " + InterestRate.class.getName() + " i where i.interestRateId = ?",
              InterestRate.class);
      query.setParameter(1, Integer.parseInt(interestRateId));
      interestRate = query.getSingleResult();

      entr.commit();
    } catch (Exception e) {
      entityManager.close();
    }
    // -----------End transaction-----------

    return interestRate;
  }
  public static void main(String[] args) {
    try {
      EntityManagerFactory f = Persistence.createEntityManagerFactory("DemoPU");
      EntityManager manager = f.createEntityManager();
      Scanner in = new Scanner(System.in);
      System.out.print("Enter id to modify");
      int id = in.nextInt();
      in.nextLine();
      Emp e = manager.find(Emp.class, id);
      System.out.println("current details are");
      System.out.println(e.getEname() + "\t" + e.getJob() + "\t" + e.getSalary());
      System.out.println("Enter name to update");
      String n = in.nextLine();
      System.out.println("Enter job to update");
      String j = in.nextLine();
      System.out.println("Enter salary to update");
      int s = in.nextInt();
      EntityTransaction t = manager.getTransaction();
      t.begin();
      e.setEname(n);
      e.setJob(j);
      e.setSalary(s);

      t.commit();
      manager.close();
      System.out.println("updated");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  public ItemComment editItemComment(
      Long itemCommentId, String text, Integer rating, User updateUser) {
    if (updateUser == null
        || !updateUser.isItemCommentWrite()
        || text.isEmpty()
        || rating == null) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    ItemComment itemComment = getItemComment(itemCommentId);
    if (itemComment != null) {
      itemComment.setText(text);
      itemComment.setRating(correctRating(rating));
      itemComment.setUpdateUser(updateUser);
      itemComment.setUpdateTimestamp(new Timestamp(new Date().getTime()));
    }

    try {
      entityManager.persist(itemComment);
      transaction.commit();
      return itemComment;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
 @Override
 public boolean apply(@Nullable Class aClass) {
   EntityTransaction tran = Entities.get(AccountEntity.class);
   try {
     List<AccountEntity> accounts = Entities.query(new AccountEntity());
     if (accounts != null && accounts.size() > 0) {
       for (AccountEntity account : accounts) {
         if (account.getCanonicalId() == null || account.getCanonicalId().equals("")) {
           account.setCanonicalId(genCanonicalId());
           LOG.debug(
               "putting canonical id "
                   + account.getCanonicalId()
                   + " on account "
                   + account.getAccountNumber());
         }
       }
     }
     tran.commit();
   } catch (Exception ex) {
     tran.rollback();
     LOG.error(
         "caught exception during upgrade, while attempting to generate and assign canonical ids");
     Exceptions.toUndeclared(ex);
   }
   return true;
 }
  public User createUser(String username, String password, long bitmap) {
    if (username.isEmpty() || password.isEmpty()) {
      return null;
    }

    Privileges privileges = new Privileges(bitmap);
    EntityTransaction transaction = startSaveTransaction();

    User user =
        new User(
            username,
            password,
            privileges.isCategoryRead(),
            privileges.isCategoryWrite(),
            privileges.isCategoryDelete(),
            privileges.isItemRead(),
            privileges.isItemWrite(),
            privileges.isItemDelete(),
            privileges.isItemCommentRead(),
            privileges.isItemCommentWrite(),
            privileges.isItemCommentDelete(),
            privileges.isUserPromote(),
            privileges.isUserDemote(),
            privileges.isUserDelete());

    try {
      entityManager.persist(user);
      transaction.commit();
      return user;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Beispiel #26
0
 public void updateContact(Contact cn, String id) {
   EntityTransaction et = em.getTransaction();
   et.begin();
   Query query = em.createQuery("UPDATE c from Contact c WHERE c.id=" + id);
   query.executeUpdate();
   et.commit();
 }
  public Item createItem(
      String title, String description, BigDecimal price, Long categoryId, User createUser) {
    if (createUser == null
        || !createUser.isItemWrite()
        || title.isEmpty()
        || price == null
        || categoryId == 0) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    Item item =
        new Item(getCategoryById(categoryId), title, description, price, createUser, createUser);

    try {
      entityManager.persist(item);
      transaction.commit();
      return item;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Beispiel #28
0
 @Override
 public void delete(Object instance) {
   EntityTransaction tx = manager.getTransaction();
   tx.begin();
   manager.remove(instance);
   tx.commit();
 }
  void markAsBroken(ETask task, EntityManager em) {
    EntityTransaction et = em.getTransaction();

    et.begin();
    task.setStatus(ETask.statusSysError);
    et.commit();
  }
 public static void modificarNombre(int idEmpleado, String nombre) {
   EmpleadoEntity empleado = getEmpleadoPorID(idEmpleado);
   EntityTransaction entityTransaction = ConexionBD.getEm().getTransaction();
   entityTransaction.begin();
   empleado.setNombre(nombre);
   entityTransaction.commit();
 }