@Test
  public void mapAndElementCollection() throws Exception {

    OneToManyAddress home = new OneToManyAddress();
    home.setCity("Paris");

    OneToManyAddress work = new OneToManyAddress();
    work.setCity("San Francisco");

    OneToManyUser user = new OneToManyUser();
    user.getAddresses().put("home", home);
    user.getAddresses().put("work", work);
    user.getNicknames().add("idrA");
    user.getNicknames().add("day[9]");

    em.persist(home);
    em.persist(work);
    em.persist(user);

    OneToManyUser user2 = new OneToManyUser();
    user2.getNicknames().add("idrA");
    user2.getNicknames().add("day[9]");

    em.persist(user2);
    em.flush();
    em.clear();

    user = em.find(OneToManyUser.class, user.getId());

    assertThat(user.getNicknames()).as("Should have 2 nick1").hasSize(2);
    assertThat(user.getNicknames()).as("Should contain nicks").contains("idrA", "day[9]");

    user.getNicknames().remove("idrA");
    user.getAddresses().remove("work");

    em.persist(user);
    em.flush();
    em.clear();

    user = em.find(OneToManyUser.class, user.getId());

    // TODO do null value
    assertThat(user.getAddresses()).as("List should have 1 elements").hasSize(1);
    assertThat(user.getAddresses().get("home").getCity())
        .as("home address should be under home")
        .isEqualTo(home.getCity());
    assertThat(user.getNicknames()).as("Should have 1 nick1").hasSize(1);
    assertThat(user.getNicknames()).as("Should contain nick").contains("day[9]");

    em.remove(user);
    // CascadeType.ALL 로 user 삭제 시 address 삭제 됨
    // em.srem(em.load(Address.class, home.getId()));
    // em.srem(em.load(Address.class, work.getId()));

    user2 = em.find(OneToManyUser.class, user2.getId());
    assertThat(user2.getNicknames()).as("Should have 2 nicks").hasSize(2);
    assertThat(user2.getNicknames()).as("Should contain nick").contains("idrA", "day[9]");
    em.remove(user2);
    em.flush();
  }
 public String processOrder(Order order, PaymentInfo payment, ShippingInfo shipping) {
   CreditCardPayment ccp = new CreditCardPayment();
   ccp.setCardholderName(payment.getCardholder_name());
   ccp.setCcNum(payment.getCc_num());
   ccp.setCcv(payment.getCcv());
   ccp.setExp(payment.getExp());
   int paymentNumber = Integer.parseInt(service.getPaymentProcessorPort().processPayment(ccp));
   if (paymentNumber >= 0) {
     payment.setConformationNumber(paymentNumber);
     order.setStatus("Pending");
     entityManager.persist(order);
     entityManager.persist(payment);
     entityManager.persist(shipping);
     entityManager.flush();
   } else {
     System.out.println("paymentNumber < 0");
   }
   payment.setCustomer_order_id_fk(order.getId());
   shipping.setCustomer_order_id_fk(order.getId());
   entityManager.persist(payment);
   entityManager.persist(order);
   entityManager.flush();
   notifyUser();
   return "" + order.getId();
 }
Example #3
0
  // Update roles and protocolMappers to given consentEntity from the consentModel
  private void updateGrantedConsentEntity(
      UserConsentEntity consentEntity, UserConsentModel consentModel) {
    Collection<UserConsentProtocolMapperEntity> grantedProtocolMapperEntities =
        consentEntity.getGrantedProtocolMappers();
    Collection<UserConsentProtocolMapperEntity> mappersToRemove =
        new HashSet<UserConsentProtocolMapperEntity>(grantedProtocolMapperEntities);

    for (ProtocolMapperModel protocolMapper : consentModel.getGrantedProtocolMappers()) {
      UserConsentProtocolMapperEntity grantedProtocolMapperEntity =
          new UserConsentProtocolMapperEntity();
      grantedProtocolMapperEntity.setUserConsent(consentEntity);
      grantedProtocolMapperEntity.setProtocolMapperId(protocolMapper.getId());

      // Check if it's already there
      if (!grantedProtocolMapperEntities.contains(grantedProtocolMapperEntity)) {
        em.persist(grantedProtocolMapperEntity);
        em.flush();
        grantedProtocolMapperEntities.add(grantedProtocolMapperEntity);
      } else {
        mappersToRemove.remove(grantedProtocolMapperEntity);
      }
    }
    // Those mappers were no longer on consentModel and will be removed
    for (UserConsentProtocolMapperEntity toRemove : mappersToRemove) {
      grantedProtocolMapperEntities.remove(toRemove);
      em.remove(toRemove);
    }

    Collection<UserConsentRoleEntity> grantedRoleEntities = consentEntity.getGrantedRoles();
    Set<UserConsentRoleEntity> rolesToRemove =
        new HashSet<UserConsentRoleEntity>(grantedRoleEntities);
    for (RoleModel role : consentModel.getGrantedRoles()) {
      UserConsentRoleEntity consentRoleEntity = new UserConsentRoleEntity();
      consentRoleEntity.setUserConsent(consentEntity);
      consentRoleEntity.setRoleId(role.getId());

      // Check if it's already there
      if (!grantedRoleEntities.contains(consentRoleEntity)) {
        em.persist(consentRoleEntity);
        em.flush();
        grantedRoleEntities.add(consentRoleEntity);
      } else {
        rolesToRemove.remove(consentRoleEntity);
      }
    }
    // Those roles were no longer on consentModel and will be removed
    for (UserConsentRoleEntity toRemove : rolesToRemove) {
      grantedRoleEntities.remove(toRemove);
      em.remove(toRemove);
    }

    em.flush();
  }
  @Test
  public void testDynamicInsertUpdate() {
    DynamicFoo foo = new DynamicFoo();
    foo.setCode(1);
    foo.setDescription("Static description");
    foo.setBar(Bar.TYPE2);
    entityManager.persist(foo);
    entityManager.flush();

    foo.setCode(2);
    entityManager.merge(foo);
    entityManager.flush();
  }
Example #5
0
  @PostConstruct
  public void startup() throws Exception {
    Query q = entityManager.createNativeQuery("DELETE from ADDRESS");
    q.executeUpdate();
    q = entityManager.createNativeQuery("DELETE from PERSON");
    q.executeUpdate();
    entityManager.flush();

    p = new Person();
    p.setFirstName("Shane");
    p.setLastName("Bryzak");
    p.setDateOfBirth(df.parse("1901-01-01"));
    p.setAddresses(new ArrayList<Address>());

    a = new Address();
    a.setPerson(p);
    a.setStreetNo(100);
    a.setStreetName("Main");
    a.setSuburb("Pleasantville");
    a.setPostCode("32123");
    a.setCountry("Australia");
    p.getAddresses().add(a);

    a = new Address();
    a.setPerson(p);
    a.setStreetNo(57);
    a.setStreetName("1st Avenue");
    a.setSuburb("Pittsville");
    a.setPostCode("32411");
    a.setCountry("Australia");
    p.getAddresses().add(a);
    entityManager.persist(p);
    entityManager.flush();

    p = new Person();
    p.setFirstName("Jozef");
    p.setLastName("Hartinger");
    p.setDateOfBirth(df.parse("1901-01-01"));
    p.setAddresses(new ArrayList<Address>());

    a = new Address();
    a.setPerson(p);
    a.setStreetNo(99);
    a.setStreetName("Purkynova");
    a.setSuburb("Kralovo pole");
    a.setPostCode("60200");
    a.setCountry("Czech republic");
    p.getAddresses().add(a);
    entityManager.persist(p);
    entityManager.flush();
  }
Example #6
0
  @Test
  public void checkPositionsNotNull() throws Exception {
    EntityManager em = getEm();
    HIterationProject project = em.find(HIterationProject.class, 1l);
    // assertThat( project, notNullValue() );

    HDocument hdoc = new HDocument("fullpath", ContentType.TextPlain, en_US);
    hdoc.setProjectIteration(project.getProjectIterations().get(0));

    List<HTextFlow> textFlows = hdoc.getTextFlows();
    HTextFlow flow1 = new HTextFlow(hdoc, "textflow1", "some content");
    HTextFlow flow2 = new HTextFlow(hdoc, "textflow2", "more content");
    textFlows.add(flow1);
    textFlows.add(flow2);
    em.persist(hdoc);
    em.flush();
    // em.clear();
    // hdoc = em.find(HDocument.class, docId);
    em.refresh(hdoc);

    List<HTextFlow> textFlows2 = hdoc.getTextFlows();
    assertThat(textFlows2.size(), is(2));
    flow1 = textFlows2.get(0);
    assertThat(flow1, notNullValue());
    flow2 = textFlows2.get(1);
    assertThat(flow2, notNullValue());

    // TODO: we should automate this...
    hdoc.incrementRevision();

    textFlows2.remove(flow1);
    flow1.setObsolete(true);
    dao.syncRevisions(hdoc, flow1);

    // flow1.setPos(null);
    em.flush();
    em.refresh(hdoc);
    em.refresh(flow1);
    em.refresh(flow2);
    assertThat(hdoc.getTextFlows().size(), is(1));
    flow2 = hdoc.getTextFlows().get(0);
    assertThat(flow2.getResId(), equalTo("textflow2"));

    flow1 = hdoc.getAllTextFlows().get("textflow1");
    // assertThat(flow1.getPos(), nullValue());
    assertThat(flow1.isObsolete(), is(true));
    assertThat(flow1.getRevision(), is(2));
    flow2 = hdoc.getAllTextFlows().get("textflow2");
    // assertThat(flow1.getPos(), is(0));
    assertThat(flow2.isObsolete(), is(false));
  }
 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 void testEL254937() {
   EntityManager em = createEntityManager(m_persistenceUnit);
   beginTransaction(em);
   LargeProject lp1 = new LargeProject();
   lp1.setName("one");
   em.persist(lp1);
   commitTransaction(em);
   em = createEntityManager(m_persistenceUnit);
   beginTransaction(em);
   em.remove(em.find(LargeProject.class, lp1.getId()));
   em.flush();
   JpaEntityManager eclipselinkEm = (JpaEntityManager) em.getDelegate();
   RepeatableWriteUnitOfWork uow = (RepeatableWriteUnitOfWork) eclipselinkEm.getActiveSession();
   // duplicate the beforeCompletion call
   uow.issueSQLbeforeCompletion();
   // commit the transaction
   uow.setShouldTerminateTransaction(true);
   uow.commitTransaction();
   // duplicate the AfterCompletion call.  This should merge, removing the LargeProject from the
   // shared cache
   uow.mergeClonesAfterCompletion();
   em = createEntityManager(m_persistenceUnit);
   LargeProject cachedLargeProject = em.find(LargeProject.class, lp1.getId());
   closeEntityManager(em);
   assertTrue(
       "Entity removed during flush was not removed from the shared cache on commit",
       cachedLargeProject == null);
 }
Example #9
0
 @Override
 public boolean registerDealerStorage(UserInfo user, DealerStorageInfo storage) {
   storage.setDealer_id(user.getUser_id());
   manager.persist(storage);
   manager.flush();
   return true;
 }
Example #10
0
  // TODO (after ERRAI-366): make this method package-private
  @EventHandler("saveButton")
  public void onSaveButtonClicked(ClickEvent event) {
    TypedQuery<Department> deptQuery = em.createNamedQuery("departmentByName", Department.class);
    deptQuery.setParameter("name", department.getText());
    Department resolvedDepartment;
    List<Department> resultList = deptQuery.getResultList();
    if (resultList.isEmpty()) {
      resolvedDepartment = new Department();
      resolvedDepartment.setName(department.getText());
    } else {
      resolvedDepartment = resultList.get(0);
    }
    Item item = itemBinder.getModel();
    item.setDepartment(resolvedDepartment);
    item.setAddedBy(user);
    item.setAddedOn(new Date());

    fooList.getItems().add(item);
    em.persist(fooList);
    em.flush();

    if (afterSaveAction != null) {
      afterSaveAction.run();
    }
  }
  public boolean setStock(List<DetailDTO> dtl) {
    for (DetailDTO detailDTO : dtl) {
      // NEW com.server.entity.beans.TblMaterial(c.idtblMaterial, c.stock )
      //     Query query = em.createQuery("SELECT c.idtblMaterial, c.stock,
      // c.idTipomaterial.idTipomaterial, c.subFamiliasidsubFam.idsubFam, c.idArea.idArea, c.costo,
      // c.noParte, c.descripcion, c.imagen, c.nombre"
      //            + "    FROM TblMaterial c WHERE c.idtblMaterial = :id ");
      //   query.setParameter("id", detailDTO.getIdMaterial());

      // Object[] res = (Object[]) query.getSingleResult();
      TypedQuery<TblMaterial> query =
          em.createNamedQuery("TblMaterial.findByIdtblMaterial", TblMaterial.class);
      query.setParameter("idtblMaterial", detailDTO.getIdMaterial());
      TblMaterial temp = query.getSingleResult();
      //   temp.setIdtblMaterial((Integer) res[0]);
      int oldStock = temp.getStock();
      temp.setStock(oldStock + detailDTO.getRegresados());
      //  temp.setStock((Integer) res[1] + detailDTO.getCantidad());
      //   temp.setIdTipomaterial(new TblTipomaterial((Integer) res[2]));
      //  temp.setSubFamiliasidsubFam(new Subfamilias((Integer) res[3]));
      // temp.setIdArea(new TblArea((Integer) res[4]));

      //  temp.setCosto((Long) res[5]);
      // temp.setNoParte((String) res[6]);
      // temp.setDescripcion((String) res[7]);
      // temp.setImagen((String) res[8]);
      // temp.setNombre((String) res[9]);
      this.edit(temp);
    }
    em.flush();
    return false;
  }
  @Test
  public void testDefaultPar() throws Exception {
    File testPackage = buildDefaultPar();
    addPackageToClasspath(testPackage);

    // run the test
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("defaultpar", new HashMap());
    EntityManager em = emf.createEntityManager();
    ApplicationServer as = new ApplicationServer();
    as.setName("JBoss AS");
    Version v = new Version();
    v.setMajor(4);
    v.setMinor(0);
    v.setMicro(3);
    as.setVersion(v);
    Mouse mouse = new Mouse();
    mouse.setName("mickey");
    em.getTransaction().begin();
    em.persist(as);
    em.persist(mouse);
    assertEquals(1, em.createNamedQuery("allMouse").getResultList().size());
    Lighter lighter = new Lighter();
    lighter.name = "main";
    lighter.power = " 250 W";
    em.persist(lighter);
    em.flush();
    em.remove(lighter);
    em.remove(mouse);
    assertNotNull(as.getId());
    em.remove(as);
    em.getTransaction().commit();
    em.close();
    emf.close();
  }
  @Transactional
  public void deleteUser(long id) {

    User user = manager.find(User.class, id);
    manager.remove(user);
    manager.flush();
  }
Example #14
0
  public void testEnumInEmbeddedId() {
    EntityManager em = emf.createEntityManager();
    Beneficiary b = new Beneficiary();
    b.setId("b8");
    List<BeneContact> contacts = new ArrayList<BeneContact>();
    BeneContact c = new BeneContact();
    c.setEmail("email8");
    BeneContactId id = new BeneContactId();
    id.setContactType(BeneContactId.ContactType.HOME);
    c.setBeneficiary(b);

    c.setId(id);
    em.persist(c);
    contacts.add(c);
    b.setContacts(contacts);
    em.persist(b);
    em.getTransaction().begin();
    em.flush();
    em.getTransaction().commit();
    em.clear();
    BeneContactId id1 = c.getId();
    BeneContact c1 = em.find(BeneContact.class, id1);
    assertEquals("email8", c1.getEmail());
    em.close();
  }
Example #15
0
  @Override
  public void updateCredential(UserCredentialModel cred) {
    CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType());

    if (credentialEntity == null) {
      credentialEntity = new CredentialEntity();
      credentialEntity.setId(KeycloakModelUtils.generateId());
      credentialEntity.setType(cred.getType());
      credentialEntity.setDevice(cred.getDevice());
      credentialEntity.setUser(user);
      em.persist(credentialEntity);
      user.getCredentials().add(credentialEntity);
    }
    if (cred.getType().equals(UserCredentialModel.PASSWORD)) {
      byte[] salt = getSalt();
      int hashIterations = 1;
      PasswordPolicy policy = realm.getPasswordPolicy();
      if (policy != null) {
        hashIterations = policy.getHashIterations();
        if (hashIterations == -1) hashIterations = 1;
      }
      credentialEntity.setValue(
          new Pbkdf2PasswordEncoder(salt).encode(cred.getValue(), hashIterations));
      credentialEntity.setSalt(salt);
      credentialEntity.setHashIterations(hashIterations);
    } else {
      credentialEntity.setValue(cred.getValue());
    }
    credentialEntity.setDevice(cred.getDevice());
    em.flush();
  }
  // User || admin
  @POST
  @Path("/create")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response addProducto(@QueryParam("mongo") Boolean mongo, DataProducto dp) {
    Producto p = new Producto();

    p.setNombre(dp.getNombre());
    p.setDescripcion(dp.getDescripcion());
    Categoria cat = em.find(Categoria.class, dp.getCategoria());
    if (cat == null) {
      DataResponse dr = new DataResponse();
      dr.setMensaje("Categoria " + dp.getCategoria() + " no existe");
      return Response.status(500).entity(dr).build();
    }
    p.setCategoria(cat);
    p.setGenerico(dp.getIsgenerico());
    try {
      em.persist(p);
      em.flush();
      dp.setID(p.getId());

      // MONGO
      if (mongo == null || mongo) new MongoController().upsertProduct(dp);

      return Response.status(201).entity(dp).build();

    } catch (Exception e) {
      DataResponse dr = new DataResponse();
      dr.setMensaje("Error inesperado.");
      dr.setDescripcion(e.getMessage());
      return Response.status(409).build();
    }
  }
Example #17
0
  private void deleteDriftFiles() throws Exception {
    getTransactionManager().begin();
    EntityManager em = getEntityManager();

    try {
      try {
        // wipe out any test DriftFiles (the test files have sha256 0,1,...)
        for (int i = 0, numDeleted = 1; (numDeleted > 0); ++i) {
          numDeleted =
              getEntityManager()
                  .createQuery("delete from JPADriftFile where hash_id = '" + i + "'")
                  .executeUpdate();
        }
      } catch (Exception e) {
        System.out.println("CANNOT PREPARE TEST: " + e);
        getTransactionManager().rollback();
        throw e;
      }

      em.flush();
      getTransactionManager().commit();
    } finally {
      em.close();
    }
  }
  /* Test TimeStampTZ with no zone set */
  public void testNoZone() {
    int year = 2000, month = 1, date = 10, hour = 11, minute = 21, second = 31;
    Integer tsId = null;
    java.util.Calendar originalCal = null, dbCal = null;

    EntityManager em = createEntityManager("timestamptz");
    beginTransaction(em);
    try {
      TStamp ts = new TStamp();
      originalCal = java.util.Calendar.getInstance();
      originalCal.set(year, month, date, hour, minute, second);
      ts.setNoZone(originalCal);
      em.persist(ts);
      em.flush();
      tsId = ts.getId();
      commitTransaction(em);
    } catch (Exception e) {
      e.printStackTrace();
      rollbackTransaction(em);
    } finally {
      clearCache();
      dbCal = em.find(TStamp.class, tsId).getNoZone();
      closeEntityManager(em);
    }

    assertEquals("The date retrived from db is not the one set to the child ", dbCal, originalCal);
    assertTrue("The year is not macth", year == dbCal.get(java.util.Calendar.YEAR));
    assertTrue("The month is not match", month == dbCal.get(java.util.Calendar.MONTH));
    assertTrue("The date is not match", date == dbCal.get(java.util.Calendar.DATE));
    assertTrue("The hour is not match", hour == dbCal.get(java.util.Calendar.HOUR));
    assertTrue("The minute is not match", minute == dbCal.get(java.util.Calendar.MINUTE));
    assertTrue("The second is not match", second == dbCal.get(java.util.Calendar.SECOND));
  }
 public T update(T entity) {
   //		log.info("Updating" + entity);
   em.merge(entity);
   em.flush();
   entityEventSrc.fire(entity);
   return entity;
 }
Example #20
0
  @GET
  @Path("{id}/file/{idFile}")
  @Produces({"application/xml", "application/json"})
  public File getFile(
      @Context HttpServletRequest request,
      @PathParam("id") Integer id,
      @PathParam("idFile") @DefaultValue("-1") Integer idFile) {
    Authentication.assertUserHasProject(request, em, id);

    File file;
    if (idFile == -1) {
      file = new File();
      file.setIsDir(1);
    } else {
      file = em.find(File.class, idFile);
    }
    em.flush();
    Collection<File> childrens =
        (Collection<File>)
            em.createNamedQuery("File.findByParentDirectoryN")
                .setParameter(1, idFile)
                .setParameter(2, id)
                .getResultList();
    file.setChildrenCollection(childrens);
    return file;
  }
Example #21
0
 public Bbs create(Bbs bbs) {
   em.persist(bbs);
   System.err.println(bbs);
   em.flush();
   System.err.println(bbs);
   return bbs;
 }
Example #22
0
 @PUT
 @Consumes({"application/xml", "application/json"})
 @Produces({"application/xml", "application/json"})
 @Transactional
 public Domains edit(Domain entity) {
   try {
     if (entity.getSite().getId() == null) entity.setSite(null);
     if (entity.getWell().getId() == null) entity.setWell(null);
     if (entity.getTypeOfWork().getId() == null) entity.setTypeOfWork(null);
     if (entity.getWorkProcess().getId() == null) entity.setWorkProcess(null);
     entity = entityManager.merge(entity);
     entityManager.flush();
     UserSessions.info(
         "ru.gispro.petrores.doc.service.DomainRESTFacade",
         UserSessions.getFacadeCallRequestUser(),
         "EDIT_REFBOOK_ITEM",
         "Edit Domain",
         entity.getId(),
         true,
         "RefBook item successfully changed");
     return new Domains(Arrays.asList(entity), 1l);
   } catch (RuntimeException e) {
     UserSessions.error(
         "ru.gispro.petrores.doc.service.DomainRESTFacade",
         UserSessions.getFacadeCallRequestUser(),
         "EDIT_REFBOOK_ITEM",
         "Edit Domain",
         entity.getId(),
         false,
         "Edit RefBook item error: " + e.toString(),
         e);
     throw e;
   }
 }
 @Test
 public void testFindRemoved() {
   final JPAEnvironment env = getEnvironment();
   final EntityManager em = env.getEntityManager();
   try {
     env.beginTransaction(em);
     Island island = new Island();
     em.persist(island);
     env.commitTransactionAndClear(em);
     Integer islandId = Integer.valueOf(island.getId());
     env.beginTransaction(em);
     island = em.find(Island.class, islandId);
     em.remove(island);
     verify(
         em.find(Island.class, islandId) == null, "entity in state FOR_DELETE but found by find");
     env.rollbackTransactionAndClear(em);
     env.beginTransaction(em);
     island = em.find(Island.class, islandId);
     em.remove(island);
     em.flush();
     verify(
         em.find(Island.class, islandId) == null,
         "entity in state DELETE_EXECUTED but found by find");
     env.rollbackTransactionAndClear(em);
   } finally {
     closeEntityManager(em);
   }
 }
Example #24
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[]
  }
  @Override
  public void addUser(UserRoles userRoles) throws DataAccessException {
    try {
      if (userRoles.getId() == null) {
        /* em = em.getEntityManagerFactory().createEntityManager();
        Session session = (Session) em.unwrap(Session.class);*/
        userRoles.setTransactionDate(new Date());
        // this is Temp fix for createdBy, TODO--> Based on admin Login
        if (userRoles.getCreatedBy() == null) {
          userRoles.setCreatedBy("*****@*****.**");
          userRoles.setRole("ADMIN");
        }
        if (userRoles.getUsers() != null) {
          String password = userRoles.getUsers().getPassword();
          PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
          String hashedPassword = passwordEncoder.encode(password);
          userRoles.getUsers().setPassword(hashedPassword);
          logger.info(" user Encrypted Password", hashedPassword);
        }

        em.persist(userRoles);
        // Here the TransactionRequiredException happens.
        em.flush();
      } else {
        em.merge(userRoles);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public ExamSession createExamSession(Student student, ExamSession esession, ExamPaper ePaper) {

    esession.setStudent(student);
    esession.setDate(new Date(System.currentTimeMillis()));
    esession.setExamPaper(ePaper);

    //        question.setCreatedBy(lecturer);
    //        question.setCreatedOn(new Date(System.currentTimeMillis()));
    //            question.setMark(mark);
    //            question.setQuestionText(questionText);
    //            question.setQuestionType(questionType);
    //            question.setVersion(0);
    //            question.setModule(module);
    //            question.setSubjectTags(subjectTags);
    em.persist(esession);

    // save options
    //        for (QuestionOption qo : question.getQuestionOptions()) {
    //
    //            qo.setQuestion(question);
    //
    //            em.persist(qo);
    //
    //        }

    em.flush();
    return esession;
    // }

    // return null;
  }
Example #27
0
  /**
   * Adding New SurveyKind
   *
   * @param record
   * @return
   * @throws Exception
   */
  public SurveyKind addSurveyKind(SurveyKind SurveyKind) throws Exception {
    EntityManager oracleManager = null;
    Object transaction = null;
    try {
      String log = "Method:CommonDMI.addSurveyKind.";
      oracleManager = EMF.getEntityManager();
      transaction = EMF.getTransaction(oracleManager);

      // sysdate
      Timestamp recDate = new Timestamp(System.currentTimeMillis());
      String loggedUserName = SurveyKind.getLoggedUserName();
      RCNGenerator.getInstance().initRcn(oracleManager, recDate, loggedUserName, log);
      oracleManager.persist(SurveyKind);
      oracleManager.flush();

      SurveyKind = oracleManager.find(SurveyKind.class, SurveyKind.getSurvey_kind_id());
      SurveyKind.setLoggedUserName(loggedUserName);

      EMF.commitTransaction(transaction);
      log += ". Inserting Finished SuccessFully. ";
      logger.info(log);
      return SurveyKind;
    } catch (Exception e) {
      EMF.rollbackTransaction(transaction);
      if (e instanceof CallCenterException) {
        throw (CallCenterException) e;
      }
      logger.error("Error While Insert SurveyKind Into Database : ", e);
      throw new CallCenterException("შეცდომა მონაცემების შენახვისას : " + e.toString());
    } finally {
      if (oracleManager != null) {
        EMF.returnEntityManager(oracleManager);
      }
    }
  }
  public int add(AccountAddViewModel accountAddViewModel) {
    int result = 0;
    try {
      Accounts account = new Accounts();
      account.setRole(Accounts.AccountRole.CUSTOMER);
      Timestamp current = new Timestamp((new Date()).getTime());
      account.setCreated(current);
      account.setUpdated(current);
      account.setDeleted(false);
      account.setUserName(accountAddViewModel.getUserName());
      account.setFirstName(accountAddViewModel.getFirstName());
      account.setLastName(accountAddViewModel.getLastName());
      account.setEmail(accountAddViewModel.getEmail());
      account.setPassword(accountAddViewModel.getPassword()); // todo: hash
      account.setPhoneNumber(accountAddViewModel.getPhoneNumber());
      account.setStreetName(accountAddViewModel.getStreetName());
      account.setStreetNumber(accountAddViewModel.getStreetNumber());
      account.setCity(accountAddViewModel.getCity());
      account.setTags(accountAddViewModel.getTags());

      em.persist(account);
      em.flush();
      result = account.getId();
    } catch (Exception e) {
      logger.warn(e.getMessage());
    }
    return result;
  }
Example #29
0
 @Override
 public boolean registerRetailerStorage(UserInfo user, RetailShopInfo shop) {
   shop.setRetailer_id(user.getUser_id());
   manager.persist(shop);
   manager.flush();
   return true;
 }
Example #30
0
  private void commonTestFindLockModeIsolations(
      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();
    resetSQL();
    int beforeIsolation = fConfig.getIsolation();
    em.find(LockEmployee.class, 1, lockMode);
    if (dict.supportsIsolationForUpdate() && dict instanceof DB2Dictionary) {
      assertEquals(expectedSupportSQLCount, getSQLCount());
      assertAllSQLInOrder(expectedSupportSQL);
    } else {
      assertEquals(expectedNonSupportSQLCount, getSQLCount());
      assertAllSQLInOrder(expectedNonSupportSQL);
    }

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

    assertEquals(beforeIsolation, fConfig.getIsolation());
  }