Example #1
1
  public static Topic createFromDB(int topicID) {
    Topic topic = null;
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select t, count(p.postID) "
                  + "  from Topic as t, Post as p "
                  + " where t.topicID = p.topicID "
                  + "   and t.topicID = :topicid "
                  + " group by t.topicID");
      q.setInteger("topicid", topicID);

      for (Iterator<Object[]> it = q.iterate(); it.hasNext(); ) {
        Object[] el = it.next();
        topic = (Topic) el[0];
        Long replies = (Long) el[1];
        topic.setReplies(replies == null ? 0 : replies.intValue());
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return topic;
  }
Example #2
0
  public static HashMap<Integer, Integer> getUnseenTopics(User user) {

    HashMap<Integer, Integer> unseenHash = new HashMap<Integer, Integer>();
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select location, count(*) from Topic as t"
                  + " where t.topicID not in ("
                  + "		select topicID from LastseenTopic as l where l.userID = :userid and l.lasttime >= t.lastedit"
                  + "       )"
                  + " group by location");
      q.setInteger("userid", user.getId());

      List<Object[]> lsts = q.list();
      for (Object[] o : lsts) {
        unseenHash.put(new Integer("" + o[0]), new Integer("" + o[1]));
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return unseenHash;
  }
Example #3
0
  /**
   * Creates the ResourceAllocationSettingData for all the types (as shown in the table below) by
   * calling each method dedicated to the creation of a specific RASD.
   *
   * <p>Each of thes method should have the format: <br>
   * <code> createRASD[idResource] </code> <br>
   * E.g The method for idResource 10 will be createRASD10
   *
   * <p>Implement methods as needed and follow examples
   *
   * <pre>
   * +------------+-------------------------+
   * | idResource | name                    |
   * +------------+-------------------------+
   * |          1 | Other                   |
   * |          2 | Computer_System         |
   * |          3 | Processor               |
   * |          4 | Memory                  |
   * |          5 | IDE_Controller          |
   * |          6 | Parallel_SCSI_HBA       |
   * |          7 | FC_HBA                  |
   * |          8 | iSCSI_HBA               |
   * |          9 | IB_HCA                  |
   * |         10 | Ethernet_Adapter        |
   * |         11 | Other_Network_Adapter   |
   * |         12 | IO_Slot                 |
   * |         13 | IO_Device               |
   * |         14 | Floppy_Drive            |
   * |         15 | CD_Drive                |
   * |         16 | DVD_drive               |
   * |         17 | Disk_Drive              |
   * |         18 | Tape_Drive              |
   * |         19 | Storage_Extent          |
   * |         20 | Other_storage_device    |
   * |         21 | Serial_port             |
   * |         22 | Parallel_port           |
   * |         23 | USB_Controller          |
   * |         24 | Graphics_controller     |
   * |         25 | IEEE_1394_Controller    |
   * |         26 | Partitionable_Unit      |
   * |         27 | Base_Partitionable_Unit |
   * |         28 | Power                   |
   * |         29 | Cooling_Capacity        |
   * |         30 | Ethernet_Switch_Port    |
   * |         31 | DMTF_reserved           |
   * |         32 | Vendor_Reserved         |
   * +------------+-------------------------+
   * </pre>
   */
  public void createResourceAllocationSettingData() {
    Session session = null;
    Transaction transaction = null;

    try {

      session = HibernateUtil.getSession();
      session.beginTransaction();

      // Create the Rasds
      createRASD10(session);

      // This array of integers contains a list of resource types in which a rasd_management
      // entry will be made for each one and all related to the current virtualappliance
      int[] resourceTypes = {10};

      transaction = session.getTransaction();

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

      transaction = session.getTransaction();

      if (transaction != null && transaction.isActive()) {
        transaction.rollback();
      }
    }
  }
Example #4
0
 @Override
 public T load(Session session, Serializable id) throws DaoException {
   T obj = null;
   log.info("BaseDaoAbstract.Load class by id: " + id);
   //        Session session = hibernateUtil.getSession();
   //        log.info("\n\nload(); session.hash = " +session.hashCode()+ "\n\n");
   try {
     transaction = session.beginTransaction();
     obj = (T) session.load(getPersistentClass(), id);
     //            session.load(obj, id);
     transaction.commit();
     //            log.info("load() -> COMMIT: " + obj.toString());
     log.info("BaseDaoAbstract.load() -> COMMIT");
   } catch (HibernateException e) {
     if (transaction != null && transaction.isActive()) {
       transaction.rollback();
       log.info("BaseDaoAbstract.load() -> ROLLBACK: " + e);
     } else log.info("BaseDaoAbstract.load(): Error in transaction.rollback");
     throw new DaoException(e);
   }
   /*finally {
       if(null!=session && session.isOpen()) {
           try {
               session.close();
           }catch (SessionException e) {
               log.info("error in session.close(): "+e);
           }
       }
   }*/
   return obj;
 }
Example #5
0
  public List<T> getList(Session session) throws DaoException {
    ArrayList<T> list = new ArrayList<>();
    log.info("BaseDaoAbstract.getList() -> Get list entities;");
    //        Session session = hibernateUtil.getSession();

    try {
      transaction = session.beginTransaction();
      Criteria criteria = session.createCriteria(getPersistentClass());
      list = (ArrayList<T>) criteria.list();
      transaction.commit();
      log.info("BaseDaoAbstract.getList() -> COMMIT; " /* + list!=null?list.toString():"null"*/);
    } catch (HibernateException e) {
      if (transaction != null && transaction.isActive()) {
        transaction.rollback();
        log.info("BaseDaoAbstract.getList() -> 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);
            }
        }
    }*/
    return list;
  }
Example #6
0
  public Filme buscaFilme(Integer codigo) {
    Filme filme = null;

    try {
      sessao = HibernateUtil.getSessionFactory().getCurrentSession();
      transacao = sessao.beginTransaction();
      Criteria filtro = sessao.createCriteria(Filme.class);
      filtro.add(Restrictions.eq("filme", codigo));
      filme = (Filme) filtro.uniqueResult();
      transacao.commit();
    } catch (Throwable e) {
      if (transacao.isActive()) {
        transacao.rollback();
      }
    } finally {
      try {
        if (sessao.isOpen()) {
          sessao.close();
        }
      } catch (Throwable e) {
        System.out.println("Erro ao fechar operação de busca. Mensagem: " + e.getMessage());
      }
    }

    return filme;
  }
Example #7
0
  @Override
  public void delete(Session session, T obj) throws DaoException {
    log.info("BaseDaoAbstract.Delete class by object: " + obj);
    //        Session session = hibernateUtil.getSession();
    try {
      transaction = session.beginTransaction();
      session.delete(obj);
      transaction.commit();
      log.info("BaseDaoAbstract.delete() -> COMMIT: " + obj.toString());
    } catch (HibernateException e) {
      if (transaction != null && transaction.isActive()) {
        transaction.rollback();
        log.info("BaseDaoAbstract.delete() -> 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);
            }
        }
    }*/

  }
  public boolean delete(String codigo) throws DAOException {
    LOG.debug("DetallePedidoDao delete");

    boolean resp = false;
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      Detallepedido detallePedido = (Detallepedido) session.get(Detallepedido.class, codigo);
      session.delete(detallePedido);
      tx.commit();
      resp = true;
    } catch (Exception e) {
      LOG.error("Fatal " + e.getMessage());
      if (tx != null && tx.isActive()) {
        try {
          tx.rollback();
        } catch (HibernateException e1) {
          LOG.error("Fatal al tratar de hacer rollback " + e.getMessage());
          throw new DAOException("Error al grabar Campo y en rollback", e);
        }
      }
      throw new DAOException("Error al Nivel persistencia", e);
    } finally {
      session.close();
    }

    return resp;
  }
Example #9
0
  @SuppressWarnings("unchecked")
  public List<Filme> listar() {
    List<Filme> filmes = null;

    try {
      sessao = HibernateUtil.getSessionFactory().getCurrentSession();
      transacao = sessao.beginTransaction();
      Criteria filtro = sessao.createCriteria(Filme.class);
      filmes = filtro.list();
      transacao.commit();
    } catch (Throwable e) {
      if (transacao.isActive()) {
        transacao.rollback();
      }
    } finally {
      try {
        if (sessao.isOpen()) {
          sessao.close();
        }
      } catch (Throwable e) {
        System.out.println("Erro ao fechar operação de listar. Mensagem: " + e.getMessage());
      }
    }

    return filmes;
  }
Example #10
0
  public static boolean needsHighlight(Topic t, User u) {
    boolean highlight = true;
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select ls "
                  + "  from LastseenTopic as ls "
                  + " where ls.userID = :userID "
                  + "   and ls.topicID = :topicID "
                  + "   and ls.lasttime > :lastedit");
      q.setInteger("userID", u.getId());
      q.setInteger("topicID", t.getTopicID());
      q.setDate("lastedit", t.getLastedit());
      List<LastseenTopic> lsts = q.list();
      if (lsts.size() > 0) {
        highlight = lsts.get(0).getLasttime().before(t.getLastedit());
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return highlight;
  }
  @Override
  public Object invoke(MethodInvocation invocation) throws Throwable {
    final Session session = sessionProvider.get();
    final Transaction transaction = session.getTransaction();

    boolean isInitiator;
    synchronized (this) {
      isInitiator = !transaction.isActive();
      if (isInitiator) {
        transaction.begin();
      }
    }

    boolean thrown = false;
    try {
      return invocation.proceed();
    } catch (InvocationTargetException e) {
      thrown = true;
      throw e.getCause();
    } catch (Throwable e) {
      thrown = true;
      throw e;
    } finally {
      if (isInitiator) {
        if (thrown) {
          transaction.rollback();
        } else {
          System.out.println(isInitiator + ": committing!");
          transaction.commit();
        }
      }
    }
  }
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    final Transaction transaction = session.getTransaction();

    if (transaction.isActive()) transaction.commit();

    if (session != null) session.close();
  }
Example #13
0
 private void rollbackTransaction(Session session, boolean readOnly) {
   if (!readOnly) {
     final Transaction txn = session.getTransaction();
     if (txn != null && txn.isActive()) {
       txn.rollback();
     }
   }
 }
Example #14
0
 private void commitTransaction(Session session, UnitOfWork uow) {
   if (uow.transactional()) {
     Transaction txn = session.getTransaction();
     if (txn != null && txn.isActive()) {
       txn.commit();
     }
   }
 }
 private void commitTransaction(Session session) {
   if (unitOfWork.transactional()) {
     final Transaction txn = session.getTransaction();
     if (txn != null && txn.isActive()) {
       txn.commit();
     }
   }
 }
  /**
   * Rolls back hibernate session.
   *
   * @param ses Hibernate session.
   * @param tx Cache ongoing transaction.
   */
  private void rollback(SharedSessionContract ses, GridCacheTx tx) {
    // Rollback only if there is no cache transaction,
    // otherwise txEnd() will do all required work.
    if (tx == null) {
      Transaction hTx = ses.getTransaction();

      if (hTx != null && hTx.isActive()) hTx.rollback();
    }
  }
  /**
   * Ends hibernate session.
   *
   * @param ses Hibernate session.
   * @param tx Cache ongoing transaction.
   */
  private void end(Session ses, GridCacheTx tx) {
    // Commit only if there is no cache transaction,
    // otherwise txEnd() will do all required work.
    if (tx == null) {
      Transaction hTx = ses.getTransaction();

      if (hTx != null && hTx.isActive()) hTx.commit();

      ses.close();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void onSessionEnd(CacheStoreSession ses, boolean commit) {
    Session hibSes = ses.attach(null);

    if (hibSes != null) {
      try {
        Transaction tx = hibSes.getTransaction();

        if (commit) {
          hibSes.flush();

          if (tx.isActive()) tx.commit();
        } else if (tx.isActive()) tx.rollback();
      } catch (HibernateException e) {
        throw new CacheWriterException(
            "Failed to end store session [tx=" + ses.transaction() + ']', e);
      } finally {
        hibSes.close();
      }
    }
  }
Example #19
0
 /**
  * Closes all sessions opened via {@link #openSession()} which are still open and rolls back their
  * transaction if it is still open.
  */
 @After
 public void closeOpenedSessions() {
   for (Session session : openedSessions) {
     if (session.isOpen()) {
       Transaction transaction = session.getTransaction();
       if (transaction != null && transaction.isActive()) {
         transaction.rollback();
       }
       session.close();
     }
   }
 }
Example #20
0
  public List<T> getListFormatted(
      Session session,
      Map<String, String> ordersMap,
      Integer firstResult,
      Integer maxResults,
      Criterion criterion)
      throws DaoException {
    ArrayList<T> list = null;
    log.info("BaseDaoAbstract.Get list.Formatted entities: ");

    try {
      transaction = session.beginTransaction();
      Criteria criteria;

      criteria = session.createCriteria(getPersistentClass());

      if (ordersMap != null && ordersMap.size() > 0) {
        Set<String> keySet = ordersMap.keySet();

        for (String key : keySet) {
          Order order = null;
          if ("acs".equalsIgnoreCase(ordersMap.get(key))) order = Order.asc(key).ignoreCase();
          else if ("decs".equalsIgnoreCase(ordersMap.get(key)))
            order = Order.desc(key).ignoreCase();
          //                    System.out.println("||||||||| order: " +order);
          if (order != null) {
            criteria.addOrder(order);
          }
        }
      }
      if (firstResult != null && maxResults != null) {
        criteria.setFirstResult(firstResult);
        criteria.setMaxResults(maxResults);
      }
      if (criterion != null) {
        criteria.add(criterion);
      }

      list = (ArrayList<T>) criteria.list();
      transaction.commit();
      log.info(
          "BaseDaoAbstract.getListFormatted() -> COMMIT; " /* + list!=null?list.toString():"null"*/);
    } catch (HibernateException e) {
      if (transaction != null && transaction.isActive()) {
        transaction.rollback();
        log.info("BaseDaoAbstract.getListFormatted() -> ROLLBACK: " + e);
      }
      throw new DaoException(e);
    }

    return list;
  }
 public void intercept(
     final InterceptorStack stack, final ResourceMethod method, final Object instance) {
   Transaction transaction = null;
   try {
     transaction = session.beginTransaction();
     stack.next(method, instance);
     transaction.commit();
   } finally {
     if (transaction.isActive()) {
       transaction.rollback();
     }
   }
 }
Example #22
0
 public static List<GemTracker> getList(User u) {
   Transaction tx = null;
   Session session = HibernateUtil.getSessionFactory().getCurrentSession();
   try {
     tx = session.getTransaction();
     Criteria c = session.createCriteria(GemTracker.class);
     c.add(Restrictions.eq("user", u));
     c.addOrder(Order.asc("expectedEndDate"));
     return c.list();
   } catch (HibernateException e) {
     e.printStackTrace();
     if (tx != null && tx.isActive()) tx.rollback();
   }
   return null;
 }
Example #23
0
 @Override
 public void tearDown() throws Exception {
   try {
     Transaction tx = fts.getTransaction();
     if (!tx.isActive()) {
       tx = fts.beginTransaction();
     }
     assertEquals(1000, fts.createQuery("delete from " + Clock.class.getName()).executeUpdate());
     fts.purgeAll(Clock.class);
     tx.commit();
     fts.close();
   } finally {
     super.tearDown();
   }
 }
Example #24
0
 public static GemTracker loadByMage(User u, String mage) {
   Transaction tx = null;
   Session session = HibernateUtil.getSessionFactory().getCurrentSession();
   try {
     tx = session.getTransaction();
     Criteria c = session.createCriteria(GemTracker.class);
     c.add(Restrictions.eq("user", u));
     c.add(Restrictions.eq("mage", Mage.getOrCreateMage(mage)));
     c.setMaxResults(1);
     return (GemTracker) c.uniqueResult();
   } catch (HibernateException e) {
     e.printStackTrace();
     if (tx != null && tx.isActive()) tx.rollback();
   }
   return null;
 }
Example #25
0
  @Override
  public void afterZoneStart() {
    BFLogger.getInstance().info("AfterZoneStart");
    BFSessionManager.getInstance().setSessionEvent(new BFSessionEvent());
    Session session = HibernateFactoryUtil.getInstance().getCurrentSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();

      tx.commit();
    } catch (Exception ex) {
      BFLogger.getInstance().error(ex.getMessage(), ex);
      if (tx != null && tx.isActive()) {
        tx.rollback();
      }
    }
  }
Example #26
0
 public boolean insertCategory(Category category) {
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     session.save(category);
     tx.commit();
     return true;
   } catch (RuntimeException ex) {
     if (tx != null && tx.isActive()) {
       try {
         tx.rollback();
       } catch (HibernateException he) {
         System.err.println("Error rolling back transaction");
       }
       throw ex;
     }
     return false;
   }
 }
Example #27
0
  @SuppressWarnings("unchecked")
  public List<Reveal> find(Map<Pair<String, Condition>, Object> map) {
    List<Reveal> reveals = null;
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Criteria c = session.createCriteria(Reveal.class);
      c.add(Restrictions.eq("old", false));

      for (Pair<String, Condition> key : map.keySet()) {
        String field = key.getFirst();
        Condition condition = key.getSecond();
        Object value = map.get(key);

        switch (condition) {
          case LIKE:
            if (value instanceof String) c.add(Restrictions.ilike(field, value));
            else c.add(Restrictions.eq(field, value));
            break;
          case NOT_LIKE:
            if (value instanceof String) c.add(Restrictions.not(Restrictions.ilike(field, value)));
            else c.add(Restrictions.ne(field, value));
            break;
          case GREATER_THAN:
            c.add(Restrictions.gt(field, value));
            break;
          case LOWER_THAN:
            c.add(Restrictions.lt(field, value));
            break;
        }
      }

      c.addOrder(Order.desc("time"));
      c.setMaxResults(100);
      reveals = (List<Reveal>) c.list();
    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return reveals;
  }
Example #28
0
 /**
  * This method retrieve a list of laboratory tests currently available in the system
  *
  * @return lab test list List<TestNames>
  * @throws Method throws a {@link RuntimeException} in failing the return, throws a {@link
  *     HibernateException} on error rolling back transaction.
  */
 public List<Category> getCategoryList() {
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query = session.createQuery("select c from Category as c");
     List<Category> testList = query.list();
     tx.commit();
     return testList;
   } catch (RuntimeException ex) {
     if (tx != null && tx.isActive()) {
       try {
         tx.rollback();
       } catch (HibernateException he) {
         System.err.println("Error rolling back transaction");
       }
       throw ex;
     }
     return null;
   }
 }
Example #29
0
  public static List<Topic> getTopics(int location, int offset) {

    List<Topic> topics = new Vector<Topic>();

    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select u, t, count(p.postID) "
                  + "  from Topic as t, User as u, Post as p "
                  + " where t.starter = u.id "
                  + "   and t.location = :location "
                  + "   and p.topicID = t.topicID "
                  + " group by t.topicID "
                  + " order by t.sticky desc, t.lastedit desc");
      q.setMaxResults(Topic.MAXTOPICS);
      if (offset > 0) {
        q.setFirstResult(offset);
      }
      q.setInteger("location", location);

      for (Iterator<Object[]> it = q.iterate(); it.hasNext(); ) {
        Object[] el = it.next();
        User u = (User) el[0];
        Topic topic = (Topic) el[1];
        Long replies = (Long) el[2];
        topic.setUser(u);
        topic.setReplies(replies == null ? 0 : replies.intValue());
        topics.add(topic);
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return topics;
  }
Example #30
0
  public boolean delete(boolean cascade) {
    if (cascade) {
      Transaction tx = null;
      Session session = HibernateUtil.getSessionFactory().getCurrentSession();
      try {
        tx = session.getTransaction();
        Query qp = session.createQuery("delete from Post as p " + " where p.topicID = :topicid");
        qp.setInteger("topicid", topicID);
        qp.executeUpdate();

        Query ql =
            session.createQuery("delete from LastseenTopic as l " + " where l.topicID = :topicid");
        ql.setInteger("topicid", topicID);
        ql.executeUpdate();

      } catch (HibernateException e) {
        e.printStackTrace();
        if (tx != null && tx.isActive()) tx.rollback();
      }
    }

    return delete();
  }