/**
   * @param nameSMD : le Nom de SMD qui a envoyer la requete
   * @param newVersion : la nouvelle versions (le cas de MAJ)
   * @return "SMD Not Found" : si le SMD n'existe pas "Version Updated" : sinon
   */
  @POST
  @Path("setVersion")
  public String setVersion(
      @FormParam("nameSMD") String nameSMD, @FormParam("newVersion") String newVersion) {
    OperationInformationResources.logger.log(
        Level.INFO, "Version with (SMD = " + nameSMD + ", newVersion = " + newVersion + ")");

    Session connect = HibernateUtil.getSessionFactory().openSession();
    SiteSMD smd = SiteSMD.findByName(connect, nameSMD);
    String result = "SMD Not Found";

    if (smd != null) {
      String lst[] = newVersion.split("-");
      if (lst.length == 2) {
        smd.setVersion_code(lst[0]);
        smd.setVersion_system(lst[1]);

        connect.beginTransaction();
        connect.saveOrUpdate(smd);
        connect.getTransaction().commit();

        result = "Version Updated";
      } else {
        result = "Version Envoyer Incorrect";
      }
    }
    connect.close();

    OperationInformationResources.logger.log(Level.FINEST, "Returned Value " + result);
    return result;
  }
  /**
   * @param nameSMD : le Nom de SMD a mettre à jour
   * @return "SMD Not Found" : si le SMD n'existe pas "Connected OK" : sinon
   */
  @POST
  @Path("setConnected")
  public String setConnected(
      @FormParam("nameSMD") String nameSMD, @FormParam("what") boolean what) {
    OperationInformationResources.logger.log(
        Level.INFO, "Connect with (SMD = " + nameSMD + ", what = " + what + " )");

    Session connect = HibernateUtil.getSessionFactory().openSession();
    SiteSMD smd = SiteSMD.findByName(connect, nameSMD);
    String result = "SMD Not Found";

    if (smd != null) {
      smd.setConnected(what);

      connect.beginTransaction();
      connect.saveOrUpdate(smd);
      connect.getTransaction().commit();

      result = "Connected OK";
    }
    connect.close();

    OperationInformationResources.logger.log(Level.FINEST, "Returned Value " + result);
    return result;
  }
  public void testInterceptorWithNewSessionAndFlushNever() throws HibernateException {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    sf.openSession();
    sfControl.setReturnValue(session, 1);
    session.getSessionFactory();
    sessionControl.setReturnValue(sf);
    session.setFlushMode(FlushMode.MANUAL);
    sessionControl.setVoidCallable(1);
    session.close();
    sessionControl.setReturnValue(null, 1);
    sfControl.replay();
    sessionControl.replay();

    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setFlushModeName("FLUSH_NEVER");
    interceptor.setSessionFactory(sf);
    try {
      interceptor.invoke(new TestInvocation(sf));
    } catch (Throwable t) {
      fail("Should not have thrown Throwable: " + t.getMessage());
    }

    sfControl.verify();
    sessionControl.verify();
  }
Esempio n. 4
0
  @SuppressWarnings("unchecked")
  public List<Token> findTokens(
      Token search, int first, int pageSize, String sortField, SortOrder sortOrder)
      throws DAOException {
    List<Token> results = null;
    Session session = null;
    try {
      session = getSession();
      Criteria criteria = criteria(session, search);

      criteria.setFirstResult(first);
      criteria.setMaxResults(pageSize);

      if (sortField == null) {
        sortField = "tokenId";
      }

      Order ord =
          (sortOrder == null
                  || sortOrder.equals(SortOrder.UNSORTED)
                  || sortOrder.equals(SortOrder.ASCENDING))
              ? Order.asc(sortField)
              : Order.desc(sortField);
      criteria.addOrder(ord);

      results = criteria.list();
    } catch (Exception e) {
      throw new DAOException(e);
    } finally {
      if (session != null) {
        session.close();
      }
    }
    return results;
  }
 @Override
 public Response deleteRecords(ArrayList persistentObjects) throws Exception {
   Session s = null;
   try {
     boolean allOk = true;
     s = HibernateUtil.getSessionFactory().openSession();
     Transaction t = s.beginTransaction();
     for (Object o : persistentObjects) {
       s.delete(o);
     }
     try {
       t.commit();
     } catch (Exception ex) {
       LoggerUtil.error(this.getClass(), "deleteRecords", ex);
       t.rollback();
       allOk = false;
     }
     if (allOk) {
       return new VOResponse(true);
     } else {
       return new ErrorResponse("delete.constraint.violation");
     }
   } finally {
     s.close();
   }
 }
 @Override
 public Response insertRecords(int[] rowNumbers, ArrayList newValueObjects) throws Exception {
   Session s = null;
   if (getSet() != null) {
     ValueObject o = (ValueObject) newValueObjects.get(0);
     try {
       s = HibernateUtil.getSessionFactory().openSession();
       Transaction t = s.beginTransaction();
       AuditoriaBasica ab = new AuditoriaBasica(new Date(), General.usuario.getUserName(), true);
       if (o instanceof Auditable) {
         ((Auditable) o).setAuditoria(ab);
       }
       // getSet().add(o);
       ((Diagnostico) o).setEspecialidad((Especialidad) super.beanVO);
       // s.update(super.beanVO);
       s.save(o);
       selectedCell(0, 0, null, o);
       t.commit();
       return new VOListResponse(newValueObjects, false, newValueObjects.size());
     } catch (Exception ex) {
       getSet().remove(o);
       return new ErrorResponse(
           LoggerUtil.isInvalidStateException(this.getClass(), "insertRecords", ex));
     } finally {
       s.close();
     }
   } else {
     return new ErrorResponse("Primero tienes que guardar el Registro Principal");
   }
 }
 private void deleteData() throws Exception {
   Session s = openSession();
   Transaction t = s.beginTransaction();
   s.delete("from Componentizable");
   t.commit();
   s.close();
 }
Esempio n. 8
0
  public ArrayList store() {
    Configuration cfg = new Configuration();
    cfg.configure();
    SessionFactory sf = cfg.buildSessionFactory();
    Session hs = sf.openSession();

    String hqlquery = "from com.mangium.Car";
    Query query = hs.createQuery(hqlquery);
    ArrayList list = (ArrayList) query.list();
    Iterator i = list.iterator();

    cr = new ArrayList();

    while (i.hasNext()) {
      Car c = (Car) i.next();
      System.out.println(c.getCarid());
      System.out.println(c.getCarname());
      System.out.println(c.getCarcost());
      System.out.println(c.getCartype());
      cr.add(c);
    }
    hs.close();
    sf.close();

    System.out.println(cr);
    setCr(cr);
    return cr;
  }
  public void testInterceptorWithEntityInterceptor() throws HibernateException {
    MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class);
    org.hibernate.Interceptor entityInterceptor =
        (org.hibernate.Interceptor) interceptorControl.getMock();
    interceptorControl.replay();
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    sf.openSession(entityInterceptor);
    sfControl.setReturnValue(session, 1);
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    session.flush();
    sessionControl.setVoidCallable(1);
    session.close();
    sessionControl.setReturnValue(null, 1);
    sfControl.replay();
    sessionControl.replay();

    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    interceptor.setEntityInterceptor(entityInterceptor);
    try {
      interceptor.invoke(new TestInvocation(sf));
    } catch (Throwable t) {
      fail("Should not have thrown Throwable: " + t.getMessage());
    }

    interceptorControl.verify();
    sfControl.verify();
    sessionControl.verify();
  }
  public void testDom4jRetreival() {
    Session session = openSession();
    Transaction txn = session.beginTransaction();
    org.hibernate.Session dom4j = session.getSession(EntityMode.DOM4J);

    prepareTestData(session);

    Object rtn = dom4j.get(Stock.class.getName(), stockId);
    Element element = (Element) rtn;

    assertEquals("Something wrong!", stockId, Long.valueOf(element.attributeValue("id")));

    System.out.println("**** XML: ****************************************************");
    prettyPrint(element);
    System.out.println("**************************************************************");

    Element currVal = element.element("currentValuation");

    System.out.println("**** XML: ****************************************************");
    prettyPrint(currVal);
    System.out.println("**************************************************************");

    txn.rollback();
    session.close();
  }
Esempio n. 11
0
  public PaymentInvoice getPaymentInvoice(int transId) throws CustomerException {
    if (id <= 0) {
      throw new CustomerException("Invalid Customer...Id cannot be <= 0");
    }
    if (transId == 0) {
      throw new PaymentException("Please specify a transaction to look up an invoice against");
    }
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    PaymentInvoice paymentInvoice = new PaymentInvoice();

    Query q = session.getNamedQuery("fetch_pmt_invoice");
    q.setParameter("in_cust_id", getId());
    q.setParameter("in_trans_id", transId);
    List<PaymentInvoice> paymentInvoiceList = q.list();
    if (paymentInvoiceList != null && paymentInvoiceList.size() > 0) {
      for (PaymentInvoice tempPaymentInvoice : paymentInvoiceList) {
        paymentInvoice = tempPaymentInvoice;
      }
    }
    session.getTransaction().commit();
    // session.close();
    return paymentInvoice;
  }
Esempio n. 12
0
  public void testInsert() throws HibernateException, SQLException {
    if (isUsingIdentity()) {
      reportSkip("hand sql expecting non-identity id gen", "Custom SQL");
      return;
    }

    Role p = new Role();

    p.setName("Patient");

    Session s = openSession();

    s.save(p);
    s.flush();

    s.connection().commit();
    s.close();

    getSessions().evict(Role.class);
    s = openSession();

    Role p2 = (Role) s.get(Role.class, new Long(p.getId()));
    assertNotSame(p, p2);
    assertEquals(p2.getId(), p.getId());
    assertTrue(p2.getName().equalsIgnoreCase(p.getName()));
    s.delete(p2);
    s.flush();

    s.connection().commit();
    s.close();
  }
 @Override
 public Response updateRecords(
     int[] rowNumbers, ArrayList oldPersistentObjects, ArrayList persistentObjects)
     throws Exception {
   Response r = super.updateRecords(rowNumbers, oldPersistentObjects, persistentObjects);
   for (Object e : persistentObjects) {
     DireccionPersona d = (DireccionPersona) e;
     if (d.getTipoDireccion().getNombre().toLowerCase().contains("fiscal")) {
       Session s = null;
       try {
         s = HibernateUtil.getSessionFactory().openSession();
         Transaction tr = s.beginTransaction();
         Persona p = (Persona) beanVO;
         p.setDireccionFiscal(d);
         s.update(beanVO);
         tr.commit();
       } catch (Exception ex) {
         ex.printStackTrace();
       } finally {
         s.close();
       }
       break;
     }
   }
   return r;
 }
Esempio n. 14
0
  public static void adicionarHorario(Horario horario) {

    session = (Session) PreparaSessao.pegarSessao();
    session.save(horario);
    session.beginTransaction().commit();
    session.close();
  }
  @POST
  @Path("progress")
  public String setProgress(
      @FormParam("idOperation") long idOperation,
      @FormParam("progressStatus") double progressStatus) {
    OperationInformationResources.logger.log(
        Level.INFO, "Progress with (id = " + idOperation + ", etat = " + progressStatus + ")");

    String result = "Operation With id= '" + idOperation + "' does not exist";
    Session connect = HibernateUtil.getSessionFactory().openSession();

    if (progressStatus < 0) {
      result = progressStatus + "is invalid (must be between 0..100)";
    } else {
      OperationAbstract getOperation = OperationAbstract.findById(connect, idOperation);
      if (getOperation != null) {
        getOperation.setState(progressStatus);

        connect.beginTransaction();
        connect.saveOrUpdate(getOperation);
        connect.getTransaction().commit();

        result = "Status is updated";
      }
    }
    connect.close();
    OperationInformationResources.logger.log(Level.FINEST, "Returned Value " + result);
    return result;
  }
  // Ensure close is called on the stateful session correctly.
  @Test
  public void testStatefulClose() {

    SessionFactory sessionFactory = createMock(SessionFactory.class);
    Session session = createMock(Session.class);
    Query scrollableResults = createNiceMock(Query.class);
    HibernateCursorItemReader<Foo> itemReader = new HibernateCursorItemReader<Foo>();
    itemReader.setSessionFactory(sessionFactory);
    itemReader.setQueryString("testQuery");
    itemReader.setUseStatelessSession(false);

    expect(sessionFactory.openSession()).andReturn(session);
    expect(session.createQuery("testQuery")).andReturn(scrollableResults);
    expect(scrollableResults.setFetchSize(0)).andReturn(scrollableResults);
    expect(session.close()).andReturn(null);

    replay(sessionFactory);
    replay(session);
    replay(scrollableResults);

    itemReader.open(new ExecutionContext());
    itemReader.close();

    verify(sessionFactory);
    verify(session);
  }
  public void testDom4jSave() {
    Session pojos = openSession();
    Transaction txn = pojos.beginTransaction();

    prepareTestData(pojos);

    org.hibernate.Session dom4j = pojos.getSession(EntityMode.DOM4J);

    Element stock = DocumentFactory.getInstance().createElement("stock");
    stock.addElement("tradeSymbol").setText("IBM");

    Element val = stock.addElement("currentValuation").addElement("valuation");
    val.appendContent(stock);
    val.addElement("valuationDate").setText(new java.util.Date().toString());
    val.addElement("value").setText("121.00");

    dom4j.save(Stock.class.getName(), stock);
    dom4j.flush();

    txn.rollback();

    pojos.close();

    assertTrue(!pojos.isOpen());
    assertTrue(!dom4j.isOpen());

    prettyPrint(stock);
  }
  public void testInterceptorWithThreadBoundEmptyHolder() {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    sf.openSession();
    sfControl.setReturnValue(session, 1);
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    session.flush();
    sessionControl.setVoidCallable(1);
    session.close();
    sessionControl.setReturnValue(null, 1);
    sfControl.replay();
    sessionControl.replay();

    SessionHolder holder = new SessionHolder("key", session);
    holder.removeSession("key");
    TransactionSynchronizationManager.bindResource(sf, holder);
    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    try {
      interceptor.invoke(new TestInvocation(sf));
    } catch (Throwable t) {
      fail("Should not have thrown Throwable: " + t.getMessage());
    }

    sfControl.verify();
    sessionControl.verify();
  }
  public void testInterceptorWithFlushFailure() throws Throwable {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    sf.openSession();
    sfControl.setReturnValue(session, 1);
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    SQLException sqlEx = new SQLException("argh", "27");
    session.flush();
    ConstraintViolationException jdbcEx = new ConstraintViolationException("", sqlEx, null);
    sessionControl.setThrowable(jdbcEx, 1);
    session.close();
    sessionControl.setReturnValue(null, 1);
    sfControl.replay();
    sessionControl.replay();

    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    try {
      interceptor.invoke(new TestInvocation(sf));
      fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
      // expected
      assertEquals(jdbcEx, ex.getCause());
    }

    sfControl.verify();
    sessionControl.verify();
  }
  public void testInterceptorWithThreadBoundAndFilter() {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    session.isOpen();
    sessionControl.setReturnValue(true, 1);
    session.enableFilter("myFilter");
    sessionControl.setReturnValue(null, 1);
    session.disableFilter("myFilter");
    sessionControl.setVoidCallable(1);
    sfControl.replay();
    sessionControl.replay();

    TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    interceptor.setFilterName("myFilter");
    try {
      interceptor.invoke(new TestInvocation(sf));
    } catch (Throwable t) {
      fail("Should not have thrown Throwable: " + t.getMessage());
    } finally {
      TransactionSynchronizationManager.unbindResource(sf);
    }

    sfControl.verify();
    sessionControl.verify();
  }
Esempio n. 21
0
 public static void deletarHorario(Horario horario) {
   session = (Session) PreparaSessao.pegarSessao();
   Transaction transaction = session.beginTransaction();
   Horario horarioDB = (Horario) session.load(Horario.class, horario.getId());
   session.delete(horarioDB);
   transaction.commit();
   // session.close();
 }
Esempio n. 22
0
  @Transactional
  public List<Concept> findByNameAndCategory(String name, String category) {
    Session session = template.getSessionFactory().getCurrentSession();
    Query query = session.createQuery("from Concept where category = :category and name = :name");
    query.setParameter("category", category);
    query.setParameter("name", name);

    return query.list();
  }
  public void update(String hql, Object... params) {
    Session session = getSession();

    Query query = session.createQuery(hql);
    for (int i = 0; i < params.length; i++) {
      query.setParameter(i, params[i]);
    }
    query.executeUpdate();
  }
Esempio n. 24
0
 private Criteria createCriteria() throws HibernateException {
   Session session = HibernateUtils.getSessionFactory().openSession();
   Criteria criteria = session.createCriteria(Emprestimo.class, "c");
   criteria.createAlias("c.bemMaterial", "bema");
   criteria.createAlias("bema.categoria", "cate");
   criteria.createAlias("cate.usuario", "u");
   criteria.add(Restrictions.eq("u.id", getUsrLogado().getId()));
   return criteria;
 }
 @Test
 @Transactional
 public void testSaveOrderWithItems() throws Exception {
   Session session = sessionFactory.getCurrentSession();
   Order order = new Order();
   order.getItems().add(new Item());
   session.save(order);
   session.flush();
   assertNotNull(order.getId());
 }
 @After
 public void tearDown() {
   try {
     dao = null;
     service = null;
   } finally {
     Session session = sessionFactory.getCurrentSession();
     session.getTransaction().commit();
   }
 }
Esempio n. 27
0
  public static void main(String[] args) {
    Session session = HibernateUtils.getSessionFactory().openSession();
    SiteDaoImp daoImp = new SiteDaoImp();
    session.beginTransaction();
    Site site = new Site();
    site.setUrl("kariyer.net0");
    daoImp.delete(site);

    session.getTransaction().commit();
  }
Esempio n. 28
0
  public Integer save(final Token token) throws DAOException {
    Session session = null;
    Transaction tr = null;
    final Integer[] r = {null};
    try {
      session = getSession();
      tr = session.beginTransaction();
      final String sql = queryCache.getQuery("save_token.sql");
      Work work =
          new Work() {

            @Override
            public void execute(Connection c) throws SQLException {
              PreparedStatement st = c.prepareStatement(sql);
              int ix = 1;
              {
                Integer id = token.getTokenId();
                if (id == null) {
                  st.setNull(ix++, Types.INTEGER);
                } else {
                  st.setInt(ix++, id);
                }
              }

              {
                String value = token.getValue();
                if (value == null) {
                  st.setNull(ix++, Types.VARCHAR);
                } else {
                  st.setString(ix++, value);
                }
              }

              st.executeUpdate();
              ResultSet rs = st.getGeneratedKeys();
              if (rs.next()) {
                r[0] = rs.getInt(1);
              }
            }
          };

      session.doWork(work);
      tr.commit();
      return r[0];
    } catch (Exception e) {
      if (tr != null) {
        tr.rollback();
      }
      throw new DAOException(e);
    } finally {
      if (session != null) {
        session.close();
      }
    }
  }
Esempio n. 29
0
 @Override
 public void addToFavorites(List<Favorite> favorites, Poem poem) {
   Session session = sessionFactory.openSession();
   Transaction tx = session.beginTransaction();
   Poem p = (Poem) session.get(Poem.class, poem.getPid());
   Set<Favorite> set = new HashSet<Favorite>(favorites);
   p.setFavoriteLists(set);
   session.update(p);
   tx.commit();
   session.close();
 }
Esempio n. 30
0
  // Método duplicado na classe MonitorDAO ver qual é o verdadeiro
  public static void adicionarMonitorAoHorario(long idHorario, Monitor monitor) {
    session = (Session) PreparaSessao.pegarSessao();
    session.beginTransaction();

    Horario horario = new Horario();
    session.load(horario, idHorario);
    horario.setMonitor(monitor);
    session.save(horario);
    session.getTransaction().commit();
    session.close();
  }