Example #1
0
  @Override
  public String execute() throws Exception {
    String name = this.getRequest().getParameter("name");
    String value = this.getRequest().getParameter("value");
    String type = this.getRequest().getParameter("type");
    String policy = this.getRequest().getParameter("policy");
    String enable = this.getRequest().getParameter("enable");

    Session session = SessionFactorySingle.getSessionFactory().openSession();
    session.beginTransaction();

    Criteria criteria = session.createCriteria(TypeDeviceFilter.class);
    criteria.add(Restrictions.eq("id", Integer.valueOf(type)));
    List<TypeDeviceFilter> typeDeviceFilters_array = criteria.list();
    TypeDeviceFilter typeDeviceFilter = typeDeviceFilters_array.get(0);

    criteria = session.createCriteria(DeviceFilter.class);
    criteria.add(Restrictions.eq("name", name));
    List<DeviceFilter> deviceFilters = (List<DeviceFilter>) criteria.list();

    DeviceFilter deviceFilter;
    if (deviceFilters.size() > 0) {
      deviceFilter = deviceFilters.get(0);
      deviceFilter.setName(name);
      deviceFilter.setValue(value);
      deviceFilter.setType(typeDeviceFilter);
      deviceFilter.setPolicy(Boolean.valueOf(policy));
      deviceFilter.setEnable(Boolean.valueOf(enable));
    } else {
      deviceFilter = new DeviceFilter(name, value, typeDeviceFilter, Boolean.valueOf(policy));
    }

    session.save(deviceFilter);
    session.getTransaction().commit();

    criteria = session.createCriteria(TroubleList.class);
    criteria.add(Restrictions.eq("name", "main"));
    TroubleList troubleList = (TroubleList) criteria.list().get(0);
    troubleList.getFilters().add(deviceFilter);

    session.beginTransaction();

    session.save(troubleList);
    session.getTransaction().commit();

    session.flush();
    session.close();

    ManagerMainDeviceFilter.getInstance().addNewDeviceInputFilter(deviceFilter);

    return null;
  }
  public void testCachedQueryOnInsert() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    Query q = s.createQuery("from Simple s");
    List list = q.setCacheable(true).list();
    assertTrue(list.size() == 1);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    q = s.createQuery("from Simple s");
    list = q.setCacheable(true).list();
    assertTrue(list.size() == 1);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    Simple simple2 = new Simple();
    simple2.setCount(133);
    s.save(simple2, new Long(12));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    q = s.createQuery("from Simple s");
    list = q.setCacheable(true).list();
    assertTrue(list.size() == 2);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    q = s.createQuery("from Simple s");
    list = q.setCacheable(true).list();
    assertTrue(list.size() == 2);
    Iterator i = list.iterator();
    while (i.hasNext()) s.delete(i.next());
    t.commit();
    s.close();
  }
  public void testBroken() throws Exception {
    if (getDialect() instanceof Oracle9Dialect) return;
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Broken b = new Fixed();
    b.setId(new Long(123));
    b.setOtherId("foobar");
    s.save(b);
    s.flush();
    b.setTimestamp(new Date());
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.update(b);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    b = (Broken) s.load(Broken.class, b);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.delete(b);
    t.commit();
    s.close();
  }
  public void testSetProperties() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));
    Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count");
    q.setProperties(simple);
    assertTrue(q.list().get(0) == simple);
    // misuse of "Single" as a propertyobject, but it was the first testclass i found with a
    // collection ;)
    Single single = new Single() { // trivial hack to test properties with arrays.
          String[] getStuff() {
            return (String[]) getSeveral().toArray(new String[getSeveral().size()]);
          }
        };

    List l = new ArrayList();
    l.add("Simple 1");
    l.add("Slimeball");
    single.setSeveral(l);
    q = s.createQuery("from Simple s where s.name in (:several)");
    q.setProperties(single);
    assertTrue(q.list().get(0) == simple);

    q = s.createQuery("from Simple s where s.name in (:stuff)");
    q.setProperties(single);
    assertTrue(q.list().get(0) == simple);
    s.delete(simple);
    t.commit();
    s.close();
  }
Example #5
0
  public static void adicionarHorario(Horario horario) {

    session = (Session) PreparaSessao.pegarSessao();
    session.save(horario);
    session.beginTransaction().commit();
    session.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");
   }
 }
  public static void main(String[] args) {

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    // CREATE
    for (int i = 1; i <= 30; i++) {
      UserInfo user = new UserInfo();

      user.setName("User" + i);
      session.save(user);
    }
    session.getTransaction().commit();
    session.close();

    UserInfo user = new UserInfo();
    session = sessionFactory.openSession();
    session.beginTransaction();
    // Retreive
    user = (UserInfo) session.get(UserInfo.class, 6);
    // Update
    user.setName("Updated User Name");
    session.update(user);

    // Delete
    user = (UserInfo) session.get(UserInfo.class, 5);
    session.delete(user);
    session.getTransaction().commit();
    session.close();

    //		System.out.println("User Object retrieved is: " + user);

  }
Example #8
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();
  }
  public void testSqlFunctionAsAlias() throws Exception {
    String functionName = locateAppropriateDialectFunctionNameForAliasTest();
    if (functionName == null) {
      log.info("Dialect does not list any no-arg functions");
      return;
    }

    log.info("Using function named [" + functionName + "] for 'function as alias' test");
    String query =
        "select "
            + functionName
            + " from Simple as "
            + functionName
            + " where "
            + functionName
            + ".id = 10";

    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    List result = s.find(query);
    assertTrue(result.size() == 1);
    assertTrue(result.get(0) instanceof Simple);
    s.delete(result.get(0));
    t.commit();
    s.close();
  }
  public void testCachedQuery() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    Query q = s.createQuery("from Simple s where s.name=?");
    q.setCacheable(true);
    q.setString(0, "Simple 1");
    assertTrue(q.list().size() == 1);
    assertTrue(q.list().size() == 1);
    assertTrue(q.list().size() == 1);
    q = s.createQuery("from Simple s where s.name=:name");
    q.setCacheable(true);
    q.setString("name", "Simple 1");
    assertTrue(q.list().size() == 1);
    simple = (Simple) q.list().get(0);

    q.setString("name", "Simple 2");
    assertTrue(q.list().size() == 0);
    assertTrue(q.list().size() == 0);
    simple.setName("Simple 2");
    assertTrue(q.list().size() == 1);
    assertTrue(q.list().size() == 1);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    q = s.createQuery("from Simple s where s.name=:name");
    q.setString("name", "Simple 2");
    q.setCacheable(true);
    assertTrue(q.list().size() == 1);
    assertTrue(q.list().size() == 1);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.update(simple, new Long(10));
    s.delete(simple);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    q = s.createQuery("from Simple s where s.name=?");
    q.setCacheable(true);
    q.setString(0, "Simple 1");
    assertTrue(q.list().size() == 0);
    assertTrue(q.list().size() == 0);
    t.commit();
    s.close();
  }
 @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());
 }
  private Session _prepareSession() throws Exception {
    Session session =
        _sessionFactoryImpl.openSession(
            new EmptyInterceptor() {

              @Override
              public String getEntityName(Object object) {
                if (object instanceof TestClassNameImpl) {
                  return ClassNameImpl.class.getName();
                }

                return super.getEntityName(object);
              }
            });

    Transaction transaction = session.beginTransaction();

    try {
      _className1 = new TestClassNameImpl(session);

      _className1.setPrimaryKey(RandomTestUtil.nextLong());

      session.save(_className1);

      _className2 = new ClassNameImpl();

      _className2.setPrimaryKey(RandomTestUtil.nextLong());

      session.save(_className2);
    } finally {
      transaction.commit();
    }

    _className1.setValue(RandomTestUtil.randomString());

    _className1.setMvccVersion(_className1.getMvccVersion() + 1);

    _className2.setValue(RandomTestUtil.randomString());

    _className2.setMvccVersion(_className1.getMvccVersion() + 1);

    return session;
  }
Example #13
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();
  }
Example #14
0
  public void testCRUD() throws HibernateException, SQLException {
    if (isUsingIdentity()) {
      reportSkip("hand sql expecting non-identity id gen", "Custom SQL");
      return;
    }

    Person p = new Person();

    p.setName("Max");
    p.setLastName("Andersen");
    p.setNationalID("110974XYZ�");
    p.setAddress("P. P. Street 8");

    Session s = openSession();

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

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

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

    Person p2 = (Person) s.get(Person.class, p.getId());
    assertNotSame(p, p2);
    assertEquals(p2.getId(), p.getId());
    assertEquals(p2.getLastName(), p.getLastName());
    s.flush();

    List list = s.createQuery("select p from Party as p").list();
    assertTrue(list.size() == 1);

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

    s = openSession();

    list = s.createQuery("select p from Person as p where p.address = 'L�rkev�nget 1'").list();
    assertTrue(list.size() == 0);
    p.setAddress("L�rkev�nget 1");
    s.update(p);
    list = s.createQuery("select p from Person as p where p.address = 'L�rkev�nget 1'").list();
    assertTrue(list.size() == 1);
    list = s.createQuery("select p from Party as p where p.address = 'P. P. Street 8'").list();
    assertTrue(list.size() == 0);

    s.delete(p);
    list = s.createQuery("select p from Person as p").list();
    assertTrue(list.size() == 0);

    s.connection().commit();
    s.close();
  }
  private void prepareTestData(Session s) {
    Employee john = new Employee("John Doe");
    john.setCompany("JBoss");
    john.setDepartment("hr");
    john.setTitle("hr guru");
    john.setRegion("US");

    Employee polli = new Employee("Polli Wog");
    polli.setCompany("JBoss");
    polli.setDepartment("hr");
    polli.setTitle("hr novice");
    polli.setRegion("US");
    polli.setManager(john);
    john.getMinions().add(polli);

    Employee suzie = new Employee("Suzie Q");
    suzie.setCompany("JBoss");
    suzie.setDepartment("hr");
    suzie.setTitle("hr novice");
    suzie.setRegion("EMEA");
    suzie.setManager(john);
    john.getMinions().add(suzie);

    Customer cust = new Customer("John Q Public");
    cust.setCompany("Acme");
    cust.setRegion("US");
    cust.setContactOwner(john);

    Person ups = new Person("UPS guy");
    ups.setCompany("UPS");
    ups.setRegion("US");

    s.save(john);
    s.save(cust);
    s.save(ups);

    s.flush();
  }
 @Test
 @Transactional
 public void testSaveAndGet() throws Exception {
   Session session = sessionFactory.getCurrentSession();
   Order order = new Order();
   order.getItems().add(new Item());
   session.save(order);
   session.flush();
   // Otherwise the query returns the existing order (and we didn't set the
   // parent in the item)...
   session.clear();
   Order other = (Order) session.get(Order.class, order.getId());
   assertEquals(1, other.getItems().size());
   assertEquals(other, other.getItems().iterator().next().getOrder());
 }
Example #17
0
  public void testJoinedSubclass() throws HibernateException, SQLException {
    Medication m = new Medication();

    m.setPrescribedDrug(new Drug());

    m.getPrescribedDrug().setName("Morphine");

    Session s = openSession();

    s.save(m.getPrescribedDrug());
    s.save(m);

    s.flush();
    s.connection().commit();
    s.close();
    s = openSession();

    Medication m2 = (Medication) s.get(Medication.class, m.getId());
    assertNotSame(m, m2);

    s.flush();
    s.connection().commit();
    s.close();
  }
 public static int insert(Session session, Object objectForInsert) {
   try {
     session.save(objectForInsert);
     return 1;
   } catch (HibernateException e) {
     LOGGER.error(
         "Insert Exception. Record can't be inserted for object="
             + objectForInsert
             + " for class "
             + objectForInsert.getClass()
             + " on session "
             + session
             + ". Method insert return 0.",
         e);
     return 0;
   }
 }
Example #19
0
  public void saveTempBanner(TempBanner data) throws Exception {
    Session session = null;

    try {
      session = HibernateUtil.getSessionFactory().openSession();
      session.getTransaction().begin();
      session.save(data);
      session.getTransaction().commit();
    } catch (HibernateException e) {
      session.getTransaction().rollback();
      throw e;
    } finally {
      if (session != null && session.isOpen()) {
        session.flush();
        session.close();
      }
    }
  }
  // ADD A EMPLOYEE BANK DETAILS IN tblempbank
  @Override
  public int addEmployeeBank(EmployeeBank employeebank)
      throws HibernateException, ConstraintViolationException {
    Session session = SessionFactoryUtil.getSessionFactory().openSession();
    int status = 0;
    try {
      session.beginTransaction();
      java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());

      Criteria criteria = session.createCriteria(EmployeeBank.class);
      criteria.add(Restrictions.eq("organizationId", employeebank.getOrganizationId()));
      criteria.add(
          Restrictions.eq("employee", new Employee(employeebank.getEmployee().getEmployeeId())));
      criteria.add(Restrictions.eq("bank", new Bank(employeebank.getBank().getBankId())));
      if (criteria.list().size() == 0) {
        employeebank.setInsertDate(date.toString());
        employeebank.setUpdateDate(date.toString());
        session.save(employeebank);
        status = 1;
      } else {
        Iterator<EmployeeBank> iterator = criteria.list().iterator();
        while (iterator.hasNext()) {
          EmployeeBank empbank = iterator.next();
          if (empbank.getDeleteFlag() == true) {
            empbank.setDeleteFlag(false);
            empbank.setInsertDate(date.toString());
            empbank.setUpdateDate(date.toString());
            session.update(empbank);
            status = 1;
          } else {
            return 5;
          }
        }
      }

    } catch (Exception e) {
      e.printStackTrace();

    } finally {
      session.getTransaction().commit();
      session.close();
    }
    return status;
  }
 @Test
 @Transactional
 public void testSaveAndFind() throws Exception {
   Session session = sessionFactory.getCurrentSession();
   Order order = new Order();
   Item item = new Item();
   item.setProduct("foo");
   order.getItems().add(item);
   session.save(order);
   session.flush();
   // Otherwise the query returns the existing order (and we didn't set the
   // parent in the item)...
   session.clear();
   Order other =
       (Order)
           session
               .createQuery("select o from Order o join o.items i where i.product=:product")
               .setString("product", "foo")
               .uniqueResult();
   assertEquals(1, other.getItems().size());
   assertEquals(other, other.getItems().iterator().next().getOrder());
 }
  public void testNothinToUpdate() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.update(simple, new Long(10));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.update(simple, new Long(10));
    s.delete(simple);
    t.commit();
    s.close();
  }
Example #23
0
  public static void main(String[] args) throws ParseException {

    Student student = new Student();

    StudentDetail detail = new StudentDetail();

    student.setName("student 1");
    student.setCreatedDate(new Date());
    student.setBirthDate(new SimpleDateFormat("dd-MM-yyyy").parse("01-01-1988"));

    detail.setMobileNumber("23232323");
    student.setDetail(detail);

    SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    session.save(student);

    session.getTransaction().commit();
    session.close();
    sessionFactory.close();
  }
  public void testSQLFunctions() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));

    if (getDialect() instanceof DB2Dialect) {
      s.find("from Simple s where repeat('foo', 3) = 'foofoofoo'");
      s.find("from Simple s where repeat(s.name, 3) = 'foofoofoo'");
      s.find("from Simple s where repeat( lower(s.name), 3 + (1-1) / 2) = 'foofoofoo'");
    }

    assertTrue(s.find("from Simple s where upper( s.name ) ='SIMPLE 1'").size() == 1);
    if (!(getDialect() instanceof HSQLDialect)) {
      assertTrue(
          s.find(
                      "from Simple s where not( upper( s.name ) ='yada' or 1=2 or 'foo'='bar' or not('foo'='foo') or 'foo' like 'bar' )")
                  .size()
              == 1);
    }
    if (!(getDialect() instanceof MySQLDialect)
        && !(getDialect() instanceof SybaseDialect)
        && !(getDialect() instanceof MckoiDialect)
        && !(getDialect() instanceof InterbaseDialect)
        && !(getDialect()
            instanceof TimesTenDialect)) { // My SQL has a funny concatenation operator
      assertTrue(
          s.find("from Simple s where lower( s.name || ' foo' ) ='simple 1 foo'").size() == 1);
    }
    if ((getDialect() instanceof SybaseDialect)) {
      assertTrue(
          s.find("from Simple s where lower( s.name + ' foo' ) ='simple 1 foo'").size() == 1);
    }
    if ((getDialect() instanceof MckoiDialect) || (getDialect() instanceof TimesTenDialect)) {
      assertTrue(
          s.find("from Simple s where lower( concat(s.name, ' foo') ) ='simple 1 foo'").size()
              == 1);
    }

    Simple other = new Simple();
    other.setName("Simple 2");
    other.setCount(12);
    simple.setOther(other);
    s.save(other, new Long(20));
    // s.find("from Simple s where s.name ## 'cat|rat|bag'");
    assertTrue(s.find("from Simple s where upper( s.other.name ) ='SIMPLE 2'").size() == 1);
    assertTrue(s.find("from Simple s where not ( upper( s.other.name ) ='SIMPLE 2' )").size() == 0);
    assertTrue(
        s.find(
                    "select distinct s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2")
                .size()
            == 1);
    assertTrue(
        s.find(
                    "select s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2 order by s.other.count")
                .size()
            == 1);
    Simple min = new Simple();
    min.setCount(-1);
    s.save(min, new Long(30));
    if (!(getDialect() instanceof MySQLDialect)
        && !(getDialect() instanceof HSQLDialect)) { // My SQL has no subqueries
      assertTrue(
          s.find("from Simple s where s.count > ( select min(sim.count) from Simple sim )").size()
              == 2);
      t.commit();
      t = s.beginTransaction();
      assertTrue(
          s.find(
                      "from Simple s where s = some( select sim from Simple sim where sim.count>=0 ) and s.count >= 0")
                  .size()
              == 2);
      assertTrue(
          s.find(
                      "from Simple s where s = some( select sim from Simple sim where sim.other.count=s.other.count ) and s.other.count > 0")
                  .size()
              == 1);
    }

    Iterator iter =
        s.iterate("select sum(s.count) from Simple s group by s.count having sum(s.count) > 10");
    assertTrue(iter.hasNext());
    assertTrue(new Integer(12).equals(iter.next()));
    assertTrue(!iter.hasNext());
    if (!(getDialect() instanceof MySQLDialect)) {
      iter = s.iterate("select s.count from Simple s group by s.count having s.count = 12");
      assertTrue(iter.hasNext());
    }

    s.iterate(
        "select s.id, s.count, count(t), max(t.date) from Simple s, Simple t where s.count = t.count group by s.id, s.count order by s.count");

    Query q = s.createQuery("from Simple s");
    q.setMaxResults(10);
    assertTrue(q.list().size() == 3);
    q = s.createQuery("from Simple s");
    q.setMaxResults(1);
    assertTrue(q.list().size() == 1);
    q = s.createQuery("from Simple s");
    assertTrue(q.list().size() == 3);
    q = s.createQuery("from Simple s where s.name = ?");
    q.setString(0, "Simple 1");
    assertTrue(q.list().size() == 1);
    q = s.createQuery("from Simple s where s.name = ? and upper(s.name) = ?");
    q.setString(1, "SIMPLE 1");
    q.setString(0, "Simple 1");
    q.setFirstResult(0);
    assertTrue(q.iterate().hasNext());
    q =
        s.createQuery(
            "from Simple s where s.name = :foo and upper(s.name) = :bar or s.count=:count or s.count=:count + 1");
    q.setParameter("bar", "SIMPLE 1");
    q.setString("foo", "Simple 1");
    q.setInteger("count", 69);
    q.setFirstResult(0);
    assertTrue(q.iterate().hasNext());
    q = s.createQuery("select s.id from Simple s");
    q.setFirstResult(1);
    q.setMaxResults(2);
    iter = q.iterate();
    int i = 0;
    while (iter.hasNext()) {
      assertTrue(iter.next() instanceof Long);
      i++;
    }
    assertTrue(i == 2);
    q = s.createQuery("select all s, s.other from Simple s where s = :s");
    q.setParameter("s", simple);
    assertTrue(q.list().size() == 1);

    q = s.createQuery("from Simple s where s.name in (:name_list) and s.count > :count");
    HashSet set = new HashSet();
    set.add("Simple 1");
    set.add("foo");
    q.setParameterList("name_list", set);
    q.setParameter("count", new Integer(-1));
    assertTrue(q.list().size() == 1);

    ScrollableResults sr = s.createQuery("from Simple s").scroll();
    sr.next();
    sr.get(0);
    sr.close();

    s.delete(other);
    s.delete(simple);
    s.delete(min);
    t.commit();
    s.close();
  }
  @Before
  public void before() {

    Session session = sf.openSession();
    Transaction tx = session.beginTransaction();

    DeviceType devType = new DeviceType();
    devType.setName("Dispositivo 1");

    List<SoundRequest> soundRequests = new ArrayList<SoundRequest>();
    devType.setSoundRequests(soundRequests);

    List<Field> fields = new ArrayList<Field>();
    devType.setFields(fields);

    List<SimpleCommand> smpCmds = new ArrayList<SimpleCommand>();
    devType.setSimpleCommands(smpCmds);

    List<CompoundCommand> cmpCmds = new ArrayList<CompoundCommand>();
    devType.setCompoundCommands(cmpCmds);

    List<Alarm> alarms = new ArrayList<Alarm>();
    devType.setAlarms(alarms);

    /*
     * Setting soundig request
     */
    SoundRequest soundR1 = new SoundRequest();
    soundR1.setAddressType(AddressType.COIL);
    soundR1.setAddress(new Integer(4100));
    soundR1.setCount(new Integer(2));
    soundR1.setDeviceType(devType);
    soundRequests.add(soundR1);

    SoundRequest soundR2 = new SoundRequest();
    soundR2.setAddressType(AddressType.DISCRETE);
    soundR2.setAddress(new Integer(5100));
    soundR2.setCount(new Integer(2));
    soundR2.setDeviceType(devType);
    soundRequests.add(soundR2);

    SoundRequest soundR3 = new SoundRequest();
    soundR3.setAddressType(AddressType.HOLDING_REGISTER);
    soundR3.setAddress(new Integer(6100));
    soundR3.setCount(new Integer(2));
    soundR3.setDeviceType(devType);
    soundRequests.add(soundR3);

    SoundRequest soundR4 = new SoundRequest();
    soundR4.setAddressType(AddressType.INPUT_REGISTER);
    soundR4.setAddress(new Integer(7100));
    soundR4.setCount(new Integer(2));
    soundR4.setDeviceType(devType);
    soundRequests.add(soundR4);

    /*
     * Setting fields
     */
    Field field1 = new Field();
    field1.setAddressType(AddressType.COIL);
    field1.setAddress(new Integer(4100));
    field1.setName("Coil 1");
    field1.setBitType(true);
    field1.setDeviceType(devType);
    fields.add(field1);

    Field field2 = new Field();
    field2.setAddressType(AddressType.COIL);
    field2.setAddress(new Integer(4101));
    field2.setName("Coil 2");
    field2.setBitType(true);
    field2.setDeviceType(devType);
    fields.add(field2);

    Field field3 = new Field();
    field3.setAddressType(AddressType.DISCRETE);
    field3.setAddress(new Integer(5100));
    field3.setName("Discrete 1");
    field3.setBitType(true);
    field3.setDeviceType(devType);
    fields.add(field3);

    Field field4 = new Field();
    field4.setAddressType(AddressType.DISCRETE);
    field4.setAddress(new Integer(5101));
    field4.setName("Discrete 2");
    field4.setBitType(true);
    field4.setDeviceType(devType);
    fields.add(field4);

    Field field5 = new Field();
    field5.setAddressType(AddressType.HOLDING_REGISTER);
    field5.setAddress(new Integer(6100));
    field5.setName("Holding register 6100 bit 0");
    field5.setBitType(true);
    field5.setBitOffset(new Integer(0));
    field5.setDeviceType(devType);
    fields.add(field5);

    Field field6 = new Field();
    field6.setAddressType(AddressType.HOLDING_REGISTER);
    field6.setAddress(new Integer(6100));
    field6.setName("Holding register 6100 bit 7");
    field6.setBitType(true);
    field6.setBitOffset(new Integer(7));
    field6.setDeviceType(devType);
    fields.add(field6);

    Field field7 = new Field();
    field7.setAddressType(AddressType.HOLDING_REGISTER);
    field7.setAddress(new Integer(6100));
    field7.setName("Holding register 6100 bit 15");
    field7.setBitType(true);
    field7.setBitOffset(new Integer(15));
    field7.setDeviceType(devType);
    fields.add(field7);

    Field field8 = new Field();
    field8.setAddressType(AddressType.HOLDING_REGISTER);
    field8.setAddress(new Integer(6100));
    field8.setName("Holding register 6100 bit 15");
    field8.setBitType(true);
    field8.setBitOffset(new Integer(15));
    field8.setDeviceType(devType);
    fields.add(field8);

    Field field9 = new Field();
    field9.setAddressType(AddressType.HOLDING_REGISTER);
    field9.setAddress(new Integer(6101));
    field9.setName("Holding register 6101 complete reg");
    field9.setBitType(false);
    field9.setDeviceType(devType);
    fields.add(field9);

    Field field10 = new Field();
    field10.setAddressType(AddressType.INPUT_REGISTER);
    field10.setAddress(new Integer(7100));
    field10.setName("Input Register complete reg 7100");
    field10.setBitType(false);
    field10.setDeviceType(devType);
    fields.add(field10);

    Field field11 = new Field();
    field11.setAddressType(AddressType.INPUT_REGISTER);
    field11.setAddress(new Integer(7101));
    field11.setName("Input Register complete reg 7101");
    field11.setBitType(false);
    field11.setDeviceType(devType);
    fields.add(field11);

    /*
     * Simple Commands
     */

    SimpleCommand smpCmd1 = new SimpleCommand();
    smpCmd1.setAddressType(AddressType.COIL);
    smpCmd1.setAddress(new Integer(4100));
    smpCmd1.setName("Set Coil 1");
    smpCmd1.setDeviceType(devType);
    smpCmds.add(smpCmd1);

    SimpleCommand smpCmd2 = new SimpleCommand();
    smpCmd2.setAddressType(AddressType.HOLDING_REGISTER);
    smpCmd2.setAddress(new Integer(6100));
    smpCmd2.setBitOffset(new Integer(0));
    smpCmd2.setName("Set Holding register 6100 bit 0");
    smpCmd2.setDeviceType(devType);
    smpCmds.add(smpCmd2);

    /*
     * Compound Commands
     */

    CompoundCommand cmpCmd1 = new CompoundCommand();
    cmpCmd1.setAddress(new Integer(6101));
    cmpCmd1.setName("Set Holding register 6101");
    cmpCmd1.setDeviceType(devType);
    cmpCmds.add(cmpCmd1);

    /*
     * Alarms
     */

    Alarm alarm1 = new Alarm();
    alarm1.setField(field1);
    alarm1.setDeviceType(devType);
    alarm1.setName("Alarma " + field1.getName());
    alarm1.setOperator(Operator.EQUAL);
    alarm1.setThreshold(new Integer(1));
    alarms.add(alarm1);

    Alarm alarm2 = new Alarm();
    alarm2.setField(field10);
    alarm2.setDeviceType(devType);
    alarm2.setName("Alarma " + field10.getName());
    alarm2.setOperator(Operator.MAYOR_EQUAL);
    alarm2.setThreshold(new Integer(200));
    alarms.add(alarm2);

    session.save(devType);

    /*
     * Setting Device
     */
    Device dev = new Device();
    dev.setAddressValues(new ArrayList<AddressValue>());
    dev.setAutoActualization(new Boolean(false));
    dev.setAutoConection(new Boolean(false));
    dev.setDescription("Este dispositivo se la banca");
    dev.setIP("localhost");
    dev.setLastActivity(new Date());
    dev.setName("La bomba loca");
    dev.setPort(new Integer(502));
    dev.setSounding(new Boolean(true));
    dev.setSoundingTime(new Integer(3000));
    dev.setType(devType);
    dev.setUnitID(new Integer(1));
    dev.setVisible(true);
    session.save(dev);

    /*
     * Setting User
     */

    SimpleUser usr = new SimpleUser();
    usr.setUserName("pepito");
    usr.setPassword("pepito");
    usr.setDevices(new ArrayList<Device>());
    usr.getDevices().add(dev);
    session.save(usr);

    tx.commit();
    session.close();
  }
  @POST
  @Path("progressSMD")
  public String setProgressSMD(
      @FormParam("nameSMD") String nameSMD,
      @FormParam("id_progress") long idProgress,
      @FormParam("title") String title,
      @FormParam("value") double valueProgress) {

    OperationInformationResources.logger.log(
        Level.INFO,
        "NAME: "
            + nameSMD
            + " Progress with (id = "
            + idProgress
            + ", etat = "
            + valueProgress
            + ")  \n contenu "
            + title);

    String result = "Progress with (id = " + idProgress + ", etat = " + valueProgress + ")";
    Session connect = HibernateUtil.getSessionFactory().openSession();

    if (idProgress < 0) {
      result += "   PROBLEM ID <0";
    } else {

      if (valueProgress < 0) {

        SiteSMD site = SiteSMD.findByName(connect, nameSMD);
        site.setHave_a_probleme(true);
        connect.beginTransaction();
        connect.saveOrUpdate(site);
        connect.getTransaction().commit();
      }

      ProgressData getProgress = ProgressData.findById(connect, idProgress);
      if (getProgress != null) {

        // remplire DATA
        getProgress.setTitle(title);
        getProgress.setValue(valueProgress);
        getProgress.setLast_date(Calendar.getInstance().getTime());
        if (valueProgress == 100) {
          getProgress.setFinished(true);
        }

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

        result = "Status is updated";
      } else {
        // remplire DATA
        SiteSMD site = SiteSMD.findByName(connect, nameSMD);
        if (site == null) {
          result = "SMD Not Found";
        } else {
          getProgress = new ProgressData();
          getProgress.setId(idProgress);
          getProgress.setTitle(title);
          getProgress.setValue(valueProgress);
          getProgress.setLast_date(Calendar.getInstance().getTime());
          if (valueProgress == 100) {
            getProgress.setFinished(true);
          }
          getProgress.setSmd(site);

          connect.beginTransaction();
          connect.save(getProgress);
          connect.getTransaction().commit();
          result = "Status is updated";
        }
      }
    }
    connect.close();
    OperationInformationResources.logger.log(Level.FINEST, "Returned Value " + result);
    return result;
  }
 public void save(Bureau a) {
   Transaction tr1 = session.beginTransaction();
   session.save(a);
   tr1.commit();
 }
Example #28
0
 public void addHouse(House house) throws Exception {
   Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
   session.save(house);
 }
  public void testDialectSQLFunctions() throws Exception {

    Session s = openSession();
    Transaction t = s.beginTransaction();

    Iterator iter = s.iterate("select max(s.count) from Simple s");

    if (getDialect() instanceof MySQLDialect) assertTrue(iter.hasNext() && iter.next() == null);

    Simple simple = new Simple();
    simple.setName("Simple Dialect Function Test");
    simple.setAddress("Simple Address");
    simple.setPay(new Float(45.8));
    simple.setCount(2);
    s.save(simple, new Long(10));

    // Test to make sure allocating an specified object operates correctly.
    assertTrue(
        s.find("select new org.hibernate.test.legacy.S(s.count, s.address) from Simple s").size()
            == 1);

    // Quick check the base dialect functions operate correctly
    assertTrue(s.find("select max(s.count) from Simple s").size() == 1);
    assertTrue(s.find("select count(*) from Simple s").size() == 1);

    if (getDialect() instanceof OracleDialect) {
      // Check Oracle Dialect mix of dialect functions - no args (no parenthesis and single arg
      // functions
      java.util.List rset =
          s.find("select s.name, sysdate(), trunc(s.pay), round(s.pay) from Simple s");
      assertNotNull("Name string should have been returned", (((Object[]) rset.get(0))[0]));
      assertNotNull("Todays Date should have been returned", (((Object[]) rset.get(0))[1]));
      assertEquals("trunc(45.8) result was incorrect ", new Float(45), ((Object[]) rset.get(0))[2]);
      assertEquals("round(45.8) result was incorrect ", new Float(46), ((Object[]) rset.get(0))[3]);

      simple.setPay(new Float(-45.8));
      s.update(simple);

      // Test type conversions while using nested functions (Float to Int).
      rset = s.find("select abs(round(s.pay)) from Simple s");
      assertEquals("abs(round(-45.8)) result was incorrect ", new Float(46), rset.get(0));

      // Test a larger depth 3 function example - Not a useful combo other than for testing
      assertTrue(s.find("select trunc(round(sysdate())) from Simple s").size() == 1);

      // Test the oracle standard NVL funtion as a test of multi-param functions...
      simple.setPay(null);
      s.update(simple);
      Integer value =
          (Integer)
              s.find("select MOD( NVL(s.pay, 5000), 2 ) from Simple as s where s.id = 10").get(0);
      assertTrue(0 == value.intValue());
    }

    if ((getDialect() instanceof HSQLDialect)) {
      // Test the hsql standard MOD funtion as a test of multi-param functions...
      Integer value =
          (Integer) s.find("select MOD(s.count, 2) from Simple as s where s.id = 10").get(0);
      assertTrue(0 == value.intValue());
    }

    s.delete(simple);
    t.commit();
    s.close();
  }
  public void testBlobClob() throws Exception {

    Session s = openSession();
    Blobber b = new Blobber();
    b.setBlob(Hibernate.createBlob("foo/bar/baz".getBytes()));
    b.setClob(Hibernate.createClob("foo/bar/baz"));
    s.save(b);
    // s.refresh(b);
    // assertTrue( b.getClob() instanceof ClobImpl );
    s.flush();
    s.refresh(b);
    // b.getBlob().setBytes( 2, "abc".getBytes() );
    b.getClob().getSubString(2, 3);
    // b.getClob().setString(2, "abc");
    s.flush();
    s.connection().commit();
    s.close();

    s = openSession();
    b = (Blobber) s.load(Blobber.class, new Integer(b.getId()));
    Blobber b2 = new Blobber();
    s.save(b2);
    b2.setBlob(b.getBlob());
    b.setBlob(null);
    // assertTrue( b.getClob().getSubString(1, 3).equals("fab") );
    b.getClob().getSubString(1, 6);
    // b.getClob().setString(1, "qwerty");
    s.flush();
    s.connection().commit();
    s.close();

    s = openSession();
    b = (Blobber) s.load(Blobber.class, new Integer(b.getId()));
    b.setClob(Hibernate.createClob("xcvfxvc xcvbx cvbx cvbx cvbxcvbxcvbxcvb"));
    s.flush();
    s.connection().commit();
    s.close();

    s = openSession();
    b = (Blobber) s.load(Blobber.class, new Integer(b.getId()));
    assertTrue(b.getClob().getSubString(1, 7).equals("xcvfxvc"));
    // b.getClob().setString(5, "1234567890");
    s.flush();
    s.connection().commit();
    s.close();

    /*InputStream is = getClass().getClassLoader().getResourceAsStream("jdbc20.pdf");
    s = sessionsopenSession();
    b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
    System.out.println( is.available() );
    int size = is.available();
    b.setBlob( Hibernate.createBlob( is, is.available() ) );
    s.flush();
    s.connection().commit();
    ResultSet rs = s.connection().createStatement().executeQuery("select datalength(blob_) from blobber where id=" + b.getId() );
    rs.next();
    assertTrue( size==rs.getInt(1) );
    rs.close();
    s.close();

    s = sessionsopenSession();
    b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
    File f = new File("C:/foo.pdf");
    f.createNewFile();
    FileOutputStream fos = new FileOutputStream(f);
    Blob blob = b.getBlob();
    byte[] bytes = blob.getBytes( 1, (int) blob.length() );
    System.out.println( bytes.length );
    fos.write(bytes);
    fos.flush();
    fos.close();
    s.close();*/

  }