예제 #1
0
  private static void tipoFuncionario() {
    Session session = HibernateUtil.getSession();
    session.beginTransaction();

    TipoFuncionario t1 = new TipoFuncionario();
    t1.setNome("Gerente");
    session.saveOrUpdate(t1);

    TipoFuncionario t2 = new TipoFuncionario();
    t2.setNome("Mecânico");
    t2.setMecanico(true);
    session.saveOrUpdate(t2);

    TipoFuncionario t3 = new TipoFuncionario();
    t3.setNome("Atendente");
    session.saveOrUpdate(t3);

    TipoFuncionario t4 = new TipoFuncionario();
    t4.setNome("Administrador");
    session.saveOrUpdate(t4);

    TipoFuncionario t5 = new TipoFuncionario();
    t5.setNome("Almoxarife");
    session.saveOrUpdate(t5);

    session.getTransaction().commit();
    System.out.println("Tipos de funcionarios criados!");
  }
예제 #2
0
 private void carregaPreuTipusHabitacions() {
   String[] nomsHotels = {
     "Palace", "Hilton", "Metropolitan", "Arts", "Catalunya", "Pensión Pepe", "Bonjour", "Oulala"
   };
   String[] nomsTipus = {"Individual", "Doble", "Matrimoni"};
   float[] preus = {100, 200, 250};
   for (int i = 0; i < nomsHotels.length; ++i) {
     for (int j = 0; j < nomsTipus.length; ++j) {
       PreuTipusHabitacio pth = new PreuTipusHabitacio();
       pth.setId(new PreuTipusHabitacioId(nomsHotels[i], nomsTipus[j]));
       pth.setPreu(preus[j]);
       if (j == 0) {
         AbsoluteDiscountPreuStrategy adps = new AbsoluteDiscountPreuStrategy();
         adps.setId(new PreuTipusHabitacioId(nomsHotels[i], nomsTipus[j]));
         adps.setDescompte(30);
         pth.setStrategy(adps);
         session.saveOrUpdate(pth);
         session.saveOrUpdate(adps);
       } else {
         PercentDiscountPreuStrategy pdps = new PercentDiscountPreuStrategy();
         pdps.setId(new PreuTipusHabitacioId(nomsHotels[i], nomsTipus[j]));
         pdps.setPerc(0.7F);
         pth.setStrategy(pdps);
         session.saveOrUpdate(pth);
         session.saveOrUpdate(pdps);
       }
     }
   }
 }
  /** Save all the VOs related to this core responsibility structure */
  public void save() throws ArchEException {
    Session openSession = ArchECoreDataProvider.getSessionFactory().getCurrentSession();
    if (openSession != null && openSession.isConnected() && openSession.isOpen()) {
      try {
        // Save or update the raw responsibility structure
        //				openSession.saveOrUpdate(rawRSVO);

        for (Iterator<ArchEResponsibilityVO> itResps = rawRSVO.getResponsibilities().iterator();
            itResps.hasNext(); ) {
          ArchEResponsibilityVO resp = itResps.next();
          String name = resp.getName();
          openSession.saveOrUpdate(resp);
          this.saveParametersForResponsibility(resp, openSession);
        }

        // Save or update the translation relations
        for (Iterator<ArchETranslationRelationVO> it = trVOs.iterator(); it.hasNext(); )
          openSession.saveOrUpdate(it.next());

        // Save or update the refinement relations
        for (Iterator<ArchERefinementRelationVO> it = refVOs.iterator(); it.hasNext(); )
          openSession.saveOrUpdate(it.next());

        // It deletes the list of 'removed' VOs
        for (Iterator it = removedRelationVOs.iterator(); it.hasNext(); )
          openSession.delete(it.next());

      } catch (HibernateException ex) {
        throw new ArchEException(ex.getMessage(), ex.getCause());
      }
    }
  }
예제 #4
0
 public static void main(String[] args) throws Exception {
   Configuration conf = new Configuration();
   conf.configure("/Metadata/metadata-hibernate.cfg.xml");
   conf.addAnnotatedClass(Child.class);
   conf.addAnnotatedClass(Parent.class);
   conf.addAnnotatedClass(ParentPk.class);
   HibernateUtil.setConfiguration(conf);
   Session session = HibernateUtil.getSession();
   Transaction tx = session.beginTransaction();
   try {
     Parent parent = new Parent();
     ParentPk pk = new ParentPk();
     parent.setFirstName("Class");
     parent.setLastName("Foo");
     parent.setMale(true);
     // parent.setId(pk);
     session.saveOrUpdate(parent);
     Child child = new Child();
     session.saveOrUpdate(child);
     // parent.getChildren().add(child);
     tx.commit();
   } catch (Exception e) {
     tx.rollback();
     throw e;
   } finally {
     session.close();
   }
 }
예제 #5
0
  public StockOpnameHeader save(
      List<StockOpnameDetail> stockOpnameDetails,
      Timestamp performedBeginTimestamp,
      Timestamp performedEndTimestamp,
      Session session) {

    StockOpnameHeader stockOpnameHeader = new StockOpnameHeader();
    stockOpnameHeader.setPerformedBy(Main.getUserLogin());
    stockOpnameHeader.setPerformedBeginTimestamp(performedBeginTimestamp);
    stockOpnameHeader.setPerformedEndTimestamp(performedEndTimestamp);
    stockOpnameHeader.setLastUpdatedBy(Main.getUserLogin().getId());
    stockOpnameHeader.setLastUpdatedTimestamp(CommonUtils.getCurrentTimestamp());

    session.saveOrUpdate(stockOpnameHeader);

    for (StockOpnameDetail stockOpname : stockOpnameDetails) {
      Item item = stockOpname.getItem();
      List<ItemStock> itemStocks = item.getItemStocks();
      for (ItemStock itemStock : itemStocks) {
        session.saveOrUpdate(itemStock);
      }
      session.saveOrUpdate(item);

      stockOpname.setStockOpnameHeader(stockOpnameHeader);
      session.saveOrUpdate(stockOpname);
    }

    return stockOpnameHeader;
  }
  @Test
  @Priority(10)
  public void initData() {
    Session session = openSession();

    // Rev 1
    session.getTransaction().begin();
    Person p = new Person();
    Name n = new Name();
    n.setName("name1");
    p.getNames().add(n);
    session.saveOrUpdate(p);
    session.getTransaction().commit();

    // Rev 2
    session.getTransaction().begin();
    n.setName("Changed name");
    session.saveOrUpdate(p);
    session.getTransaction().commit();

    // Rev 3
    session.getTransaction().begin();
    Name n2 = new Name();
    n2.setName("name2");
    p.getNames().add(n2);
    session.getTransaction().commit();

    personId = p.getId();
  }
예제 #7
0
  /**
   * Encargado de borrar la informacion de un riego apartir de su identificacion
   *
   * @param idIrr: Identificacion del riego
   * @return Estado del proceso
   */
  public String delete() {
    if (!usrDao.getPrivilegeUser(idUsrSystem, "crop/delete")) {
      return BaseAction.NOT_AUTHORIZED;
    }
    Integer idIrr = 0;
    try {
      idIrr = Integer.parseInt(this.getRequest().getParameter("idIrr"));
    } catch (NumberFormatException e) {
      idIrr = -1;
    }

    if (idIrr == -1) {
      state = "failure";
      info = "Fallo al momento de obtener la informacion a borrar";
      return "states";
    }

    SessionFactory sessions = HibernateUtil.getSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;

    try {
      tx = session.beginTransaction();
      Irrigation pr = irrDao.objectById(idIrr);
      pr.setStatus(false);
      //            session.delete(pro);
      session.saveOrUpdate(pr);

      LogEntities log = new LogEntities();
      log.setIdLogEnt(null);
      log.setIdEntityLogEnt(idEntSystem);
      log.setIdObjectLogEnt(pr.getIdIrr());
      log.setTableLogEnt("irrigation");
      log.setDateLogEnt(new Date());
      log.setActionTypeLogEnt("D");
      session.saveOrUpdate(log);
      //            logDao.save(log);
      tx.commit();
      state = "success";
      info = "El riego ha sido borrado con exito";
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
      state = "failure";
      info = "Fallo al momento de borrar un riego";
    } finally {
      session.close();
    }

    return "states";
    //        return SUCCESS;
  }
  @GlobalDBOpenCloseAndUserPrivilages
  public Map saveUserType(
      Session session,
      HttpServletRequest request,
      HttpServletResponse response,
      String LoggedInRegion,
      String LoggedInUser,
      String funtype,
      String usertypeid,
      String usertype) {
    Map resultMap = new HashMap();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      Usertype masterobj = new Usertype();
      if (usertypeid.equalsIgnoreCase("0")) {
        masterobj.setId(getSequenceId(session));
      } else {
        masterobj.setId(Integer.parseInt(usertypeid));
      }
      masterobj.setUsertypename(usertype);
      masterobj.setParentcode(0);
      session.saveOrUpdate(masterobj);
      transaction.commit();

      resultMap.put("success", "User Type Successfully Saved");
    } catch (Exception e) {
      e.printStackTrace();
      if (transaction != null) {
        transaction.rollback();
      }
      resultMap.put("ERROR", "User Type Transaction Faild");
    }
    return resultMap;
  }
예제 #9
0
  @Override
  public void saveOrUpdate(Session session, T obj) throws DaoException {
    log.info("BaseDaoAbstract.SaveOrUpdate by object: " + obj != null ? obj : "null");
    //        Session session = hibernateUtil.getSession();
    try {
      transaction = session.beginTransaction();
      session.saveOrUpdate(obj);
      transaction.commit();
      log.info("BaseDaoAbstract.saveOrUpdate -> COMMIT: " + obj != null ? obj : "null");
    } catch (HibernateException e) {
      if (transaction != null) {
        transaction.rollback();
        log.info("BaseDaoAbstract.saveOrUpdate -> catch -> ROLLBACK: " + e);
      }
      throw new DaoException(e);
    }
    /*finally {
        if(null!=session && session.isOpen()) {
            try {
                session.close();
            }catch (SessionException e) {
                log.info("error in session.close(): "+e);
            }
        }
    }*/

  }
예제 #10
0
  public User updateExistingUser(
      String login,
      String name,
      String password,
      List<Role> roles,
      boolean disabled,
      boolean deleted,
      Session session)
      throws UserException, AppException {

    User user = getDetail(login, session);
    user.setName(name);
    if (password != null && !password.trim().equals("")) {
      user.setPassword(SecurityUtils.hash(password));
    }
    if (deleted) {
      if (!disabled) {
        throw new UserException("Tidak dapat menghapus User yang masih dalam kondisi aktif");
      }
    }
    user.setDisabled(disabled);
    user.setDeleted(deleted);
    user.setLastUpdatedBy(Main.getUserLogin().getId());
    user.setLastUpdatedTimestamp(CommonUtils.getCurrentTimestamp());

    session.saveOrUpdate(user);

    updateUserRoleLink(user.getId(), roles, session);

    return user;
  }
예제 #11
0
  /**
   * Update a single <code>Patient</code> record.
   *
   * @param patientRecord
   * @return boolean
   */
  public boolean update(Patient patientRecord) {
    log.debug("PatientDAO.update() - Begin");
    Session session = null;
    Transaction tx = null;
    boolean result = true;

    if (patientRecord != null) {
      try {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        log.info("Updating Record...");

        session.saveOrUpdate(patientRecord);

        log.info("Patient Updated seccussfully...");
        tx.commit();
      } catch (Exception e) {
        result = false;
        if (tx != null) {
          tx.rollback();
        }
        log.error("Exception during update caused by :" + e.getMessage(), e);
      } finally {
        // Actual Patient update will happen at this step
        if (session != null) {
          session.close();
        }
      }
    }
    log.debug("PatientDAO.update() - End");
    return result;
  }
예제 #12
0
  public static Panel savePanel(Panel panel) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      session.saveOrUpdate(panel);

      tx.commit();

      return panel;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      return null;
    } finally {
      session.clear();
      session.close();
    }
  }
예제 #13
0
  private static void funcionarios() {
    Session session = HibernateUtil.getSession();
    session.beginTransaction();

    for (String linha : getFuncionariosFromCSV()) {
      String[] item = linha.split(";");

      Funcionario funcionario = new Funcionario();
      funcionario.setNome(item[0]);
      funcionario.setCpf(item[1]);
      try {
        funcionario.setNascimento(Formatos.getFormatoDeData().parse(item[2]));
      } catch (ParseException e) {
        e.printStackTrace();
      }
      funcionario.setEndereco(item[3]);
      funcionario.setEmail(item[4]);
      funcionario.setTelefone(item[5]);

      String hql = "from TipoFuncionario m where m.nome = :nome ";
      Query query = session.createQuery(hql).setString("nome", item[6]);
      funcionario.setTipoFuncionario((TipoFuncionario) query.uniqueResult());

      session.saveOrUpdate(funcionario);
    }

    session.getTransaction().commit();
    System.out.println("Funcionarios importados!");
  }
예제 #14
0
  @Test
  public void categoryAndEvent() {

    session.createQuery("delete from Event").executeUpdate();
    session.createQuery("delete from Category").executeUpdate();
    session.flush();
    Category category = new Category("category1");

    Event event1 = new Event("event1", new Date());
    Event event2 = new Event("event2", new Date());
    category.getEvents().add(event1);
    event1.setCategory(category);

    category.getEvents().add(event2);
    event2.setCategory(category);

    session.saveOrUpdate(category);
    session.flush();
    session.clear();

    @SuppressWarnings("unchecked")
    final List<Category> categories =
        (List<Category>) session.createCriteria(Category.class).list();
    assertEquals(1, categories.size());
    assertEquals(2, categories.get(0).getEvents().size());

    for (Category c : categories) log.debug("Category=[{}]", c);
  }
예제 #15
0
  @Test
  public void stateEntityImplSave() {

    session.createQuery("delete from StatefulEntityImpl").executeUpdate();
    session.flush();

    StatefulEntityImpl stateEntity = new StatefulEntityImpl("abc");
    session.persist(stateEntity);
    session.flush();

    StatefulEntityImpl stateEntity2 = new StatefulEntityImpl("가나다");
    session.persist(stateEntity2);
    session.flush();

    if (log.isDebugEnabled()) log.debug("엔티티를 저장했습니다. entity=" + stateEntity);

    session.clear();

    @SuppressWarnings("unchecked")
    final List<StatefulEntityImpl> loaded =
        (List<StatefulEntityImpl>)
            session.createQuery("from " + StatefulEntityImpl.class.getName()).list();

    assertEquals(2, loaded.size());

    StatefulEntityImpl entity = loaded.get(0);
    assertNotNull(entity);
    assertEquals("abc", entity.getName());

    entity.setName("modified");
    session.saveOrUpdate(entity);
    session.flush();

    log.debug("엔티티를 로드했습니다. entity=" + entity);
  }
  public static void updateProduct(Products pro) {
    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
      trns = session.beginTransaction();
      //
      Products lolo = new Products();
      lolo.setId(pro.getId());
      lolo.setName(pro.getName());
      lolo.setAvalibleAmmount(pro.getAvalibleAmmount());
      lolo.setUnit(pro.getUnit());
      lolo.setDescription(pro.getDescription());
      //
      session.saveOrUpdate(lolo);

      session.getTransaction().commit();
    } catch (RuntimeException e) {
      if (trns != null) {
        trns.rollback();
      }
      e.printStackTrace();
    } finally {
      session.flush();
      session.close();
    }
  }
예제 #17
0
 @Override
 public boolean saveMaxFileSequenceNo(CampaignProcessModel campaignProcessModel) {
   LOGGER.info(
       "Saving File Sequence no to CampaignProcess started at : " + System.currentTimeMillis());
   boolean transactionStatus = true;
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     session.saveOrUpdate(campaignProcessModel);
     tx.commit();
   } catch (HibernateException e) {
     tx.rollback();
     transactionStatus = false;
     LOGGER.error(
         "HibernateException while saving File Sequence no to  CampaignProcess table : "
             + e.getMessage());
     LOGGER.error(
         "Saving File Sequence no to CampaignProcess finished with error : "
             + System.currentTimeMillis());
   } finally {
     session.close();
   }
   LOGGER.info(
       "Saving File Sequence no to CampaignProcess is successful" + System.currentTimeMillis());
   return transactionStatus;
 }
  public void submitCurrentPurchase(List<SoldItem> goods, SingleSale sale)
      throws VerificationFailedException {
    // Let's assume we have checked and found out that the buyer is
    // underaged and
    // cannot buy chupa-chups
    // throw new VerificationFailedException("Underaged!");
    // XXX - Save purchase
    Session session = HibernateUtil.currentSession();

    Transaction transaction = session.beginTransaction();
    session.save(sale);
    transaction.commit();

    transaction = session.beginTransaction();
    for (int i = 0; i < goods.size(); i++) {
      session.saveOrUpdate(goods.get(i).getStockItem());
    }
    transaction.commit();
    transaction = session.beginTransaction();
    for (int i = 0; i < goods.size(); i++) {
      goods.get(i).setSaleId(sale);
      session.save(goods.get(i));
    }
    transaction.commit();
    transaction = session.beginTransaction();
    session.save(sale);
    log.debug("Stock updated in db - confirmed sale");
  }
예제 #19
0
  /** Save the bowl picks */
  public void saveBowlPicks(Integer userId, List<BowlPickBo> bowlPicks) {
    UserManager userMgr = new UserManager();
    User user = userMgr.getUserById(userId);

    Transaction saveTransaction = session.beginTransaction();
    for (BowlPickBo bowlPickBo : bowlPicks) {
      BowlMatchup matchup = getMatchupById(bowlPickBo.getBowlMatchupId());
      if (matchup.getLockFlag() == true) {
        continue;
      }

      BowlPick pick = null;
      if (bowlPickBo.getBowlPickId() != null) {
        pick = getBowlPickById(bowlPickBo.getBowlPickId());
      } else {
        pick = new BowlPick();
      }
      pick.setBowlMatchup(getMatchupById(bowlPickBo.getBowlMatchupId()));
      pick.setSelectedTeam(getCfbTeamById(bowlPickBo.getSelectedTeamId()));
      pick.setUser(user);
      pick.setLastEditTimestamp(new Date());
      pick.setCreateTimestamp(new Date());
      user.getBowlPicks().add(pick);

      if (pick.getBowlMatchup().getLockFlag() == true) {
        continue;
      }

      session.saveOrUpdate(pick);
    }
    saveTransaction.commit();
    session.flush();
  }
예제 #20
0
  public boolean testCreatTransaction() {

    // creation of session
    Session session = sessionFactory.openSession();

    // creation of transaction
    org.hibernate.Transaction tx = session.beginTransaction();

    try {
      // begin the transaction first
      tx.begin();

      // save the information
      session.saveOrUpdate(testData);

      // commit the changes
      tx.commit();

      // close session
      session.close();
      return true;

    } catch (Exception ex) {
      tx.rollback();

      ex.printStackTrace(System.out);

      return false;
    }
  }
예제 #21
0
  private static void clientes() {
    Session session = HibernateUtil.getSession();
    session.beginTransaction();

    for (String linha : getClientesFromCSV()) {
      String[] item = linha.split(";");

      Cliente cliente = new Cliente();
      cliente.setRazao(item[0]);
      cliente.setFantasia(item[1]);
      cliente.setNumeroDocumento(item[2]);
      try {
        cliente.setNascimento(Formatos.getFormatoDeData().parse(item[3]));
      } catch (ParseException e) {
        e.printStackTrace();
      }
      cliente.setEndereco(item[4]);
      cliente.setTelefone(item[5]);
      cliente.setEmail(item[6]);

      if ("física".equals(item[7])) cliente.setTipoPessoa(TipoPessoa.Fisica);
      else cliente.setTipoPessoa(TipoPessoa.Juridica);

      String hql = "from TipoDocumento m where m.nome = :nome ";
      Query query = session.createQuery(hql).setString("nome", item[8]);
      cliente.setTipoDocumento((TipoDocumento) query.uniqueResult());

      session.saveOrUpdate(cliente);
    }

    session.getTransaction().commit();
    System.out.println("Funcionarios importados!");
  }
  public void saveUser(User aUser, ArrayList<Authorization> aAuthorizationList)
      throws ControllerException {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;
    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      session.saveOrUpdate(aUser);
      for (Authorization authorization : aUser.getAuthorizations()) {
        session.delete(authorization);
      }
      Authorization authorization;
      for (Authorization newAuthorization : aAuthorizationList) {
        session.save(newAuthorization);
      }

      tx.commit();
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      throw new ControllerException("à¡Ô´¤ÇÒÁ¼Ô´¾ÅÒ´ÃÐËÇèÒ§¡Òúѹ·Ö¡ÃÒ¡ÒüÙéãªé");
    } finally {
      session.clear();
      session.close();
      //			if (session!= null && session.isOpen()) {
      //				session.close();
      //			}
    }
  }
예제 #23
0
 @Override
 public void saveOrUpdate(BaseForm form) {
   Session session = sessionFactory.openSession();
   session.saveOrUpdate(form);
   session.flush();
   session.close();
 }
예제 #24
0
 @Override
 public void saveOrUpdate(T obj) {
   /** 当不知道对象是不是持久化的对象的时候使用此方法 */
   Session sess = this.getSession();
   sess.saveOrUpdate(obj);
   // sess.flush();
 }
예제 #25
0
 public boolean crearArticulo(MA_Articulo articulo) throws sgiException {
   this.abrirSession();
   tx = null;
   try {
     tx = s.beginTransaction();
     s.saveOrUpdate(articulo);
     tx.commit();
     // articulo.trazar();
     this.cerrarSession();
     return true;
   } catch (Exception e) {
     tx.rollback();
     log.info("**************************************");
     log.info("El articulo '" + articulo.getNroArt() + "' no se ha podido crear.");
     log.info("DaoMArticulos.crearArticulo()");
     log.info("**************************************");
     // e.printStackTrace();
     this.cerrarSession();
     sgiException exc = new sgiException();
     exc.setMensaje("El articulo '" + articulo.getNroArt() + "' no se ha podido crear.");
     exc.setCodigo(1);
     articulo.trazar();
     e.printStackTrace();
     throw exc;
   }
 }
예제 #26
0
 public void saveOrUpdate(PontoDeInteresse poi) throws HibernateException {
   Session session = HibernateConnector.getInstance().getSession();
   Transaction t = session.beginTransaction();
   session.saveOrUpdate(poi);
   t.commit();
   session.close();
 }
  /** {@inheritDoc} */
  @Override
  public void put(@Nullable GridCacheTx tx, K key, @Nullable V val) throws GridException {
    init();

    if (log.isDebugEnabled())
      log.debug("Store put [key=" + key + ", val=" + val + ", tx=" + tx + ']');

    if (val == null) {
      remove(tx, key);

      return;
    }

    Session ses = session(tx);

    try {
      GridCacheHibernateBlobStoreEntry entry =
          new GridCacheHibernateBlobStoreEntry(toBytes(key), toBytes(val));

      ses.saveOrUpdate(entry);
    } catch (HibernateException e) {
      rollback(ses, tx);

      throw new GridException(
          "Failed to put value to cache store [key=" + key + ", val" + val + "]", e);
    } finally {
      end(ses, tx);
    }
  }
예제 #28
0
 /**
  * 添加一条日志(测试用)
  *
  * @param session
  * @return
  */
 private Object addStocks(Session session) {
   List<String> stockList = getAllStockDefList(session);
   for (String temp : stockCodes) {
     if (stockList.contains(temp) || stockList.contains(temp.replace("type_0", ""))) {
       continue;
     } else {
       StockDef stock = new StockDef();
       if (temp.indexOf("type_0") > -1) {
         temp = temp.replace("type_0", "");
         stock.setType(0);
       } else {
         stock.setType(1);
       }
       stock.setStockcode(temp);
       stock.setStockname(
           ConnectionFactory.getServiceCommon()
               .getStockNameByCode(temp, ConnectionFactory.newConnectionInstant(temp)));
       // System.out.println(stock.getStockname());
       session.saveOrUpdate(stock);
       stockList.add(temp);
       log.info("add stocks successfully!");
     }
   }
   return Constants.SUCCESS;
 }
예제 #29
0
  public User addNewUser(
      String login,
      String name,
      String password,
      List<Role> roles,
      boolean disabled,
      boolean deleted,
      Session session)
      throws UserException, AppException {

    if (DBUtils.getInstance().isExists("login", login, User.class, session)) {
      throw new UserException("User dengan Login ID " + login + " sudah pernah didaftarkan");
    }

    User user = new User();
    user.setLogin(login);
    user.setName(name);
    user.setPassword(SecurityUtils.hash(password));
    user.setDisabled(disabled);
    user.setDeleted(deleted);
    user.setLastUpdatedBy(Main.getUserLogin().getId());
    user.setLastUpdatedTimestamp(CommonUtils.getCurrentTimestamp());

    session.saveOrUpdate(user);

    updateUserRoleLink(user.getId(), roles, session);

    return user;
  }
예제 #30
0
  @SuppressWarnings("unchecked")
  @Transactional(
      propagation = Propagation.REQUIRES_NEW,
      readOnly = false,
      rollbackFor = Throwable.class)
  private void removeRoles(Flota f) {
    try {
      if (f != null && f.getId() != null) {
        Session currentSession = getSession();
        currentSession.clear();

        f = this.get(f.getId());

        final Set<Rol> roles = Collections.unmodifiableSet(f.getRoles());
        if (f != null && roles != null)
          for (Rol r : roles) {
            r = (Rol) currentSession.get(Rol.class, r.getId());
            if (r != null && r.getFlotas() != null) {
              final Set<Flota> flotas = Collections.unmodifiableSet(r.getFlotas());
              List<Flota> aBorrar = new LinkedList<Flota>();
              for (Flota fl : flotas) if (fl.getId().equals(f.getId())) aBorrar.add(fl);
              for (Flota fl : aBorrar) r.getFlotas().remove(fl);
              currentSession.saveOrUpdate(r);
            }
          }
      }
    } catch (Throwable t) {
      log.error(t, t);
    }
  }