/** Test that session-closed protections work properly in all environments. */
  @Test
  public void testSessionClosedProtections() throws Throwable {
    prepare();
    Session s = getSessionUnderTest();
    release(s);
    done();
    assertFalse(s.isOpen());
    assertFalse(s.isConnected());
    assertNotNull(s.getStatistics());
    assertNotNull(s.toString());

    try {
      s.createQuery("from Silly").list();
      fail("allowed to create query on closed session");
    } catch (Throwable ignore) {
    }

    try {
      s.getTransaction();
      fail("allowed to access transaction on closed session");
    } catch (Throwable ignore) {
    }

    try {
      s.close();
      fail("allowed to close already closed session");
    } catch (Throwable ignore) {
    }

    try {
      s.isDirty();
      fail("allowed to check dirtiness of closed session");
    } catch (Throwable ignore) {
    }
  }
  @Test
  public void testSuppliedConnection() throws Throwable {
    prepare();

    Connection originalConnection =
        sessionFactory().getServiceRegistry().getService(ConnectionProvider.class).getConnection();
    Session session = sessionFactory().withOptions().connection(originalConnection).openSession();

    Silly silly = new Silly("silly");
    session.save(silly);

    // this will cause the connection manager to cycle through the aggressive release logic;
    // it should not release the connection since we explicitly suplied it ourselves.
    session.flush();
    assertTrue(session.isConnected());

    session.delete(silly);
    session.flush();

    release(session);
    done();

    sessionFactory()
        .getServiceRegistry()
        .getService(ConnectionProvider.class)
        .closeConnection(originalConnection);
  }
예제 #3
0
  @Create
  @Transactional
  public void initialize() {

    LOGGER.debug("hibernateSession.isConnected(): " + hibernateSession.isConnected());
    LOGGER.debug("hibernateSession.isOpen(): " + hibernateSession.isOpen());
    LOGGER.debug("hibernateSession.getTransaction(): " + hibernateSession.getTransaction());
    LOGGER.debug(
        "hibernateSession.getTransaction().isActive(): "
            + hibernateSession.getTransaction().isActive());

    localeId = charmsUser.getLocaleId();
    themeId = charmsUser.getThemeId();
    timezoneId = charmsUser.getTimezoneId();

    email = charmsUser.getEmail();

    LOGGER.debug(
        "initialized userPropertiesActionBean: "
            + " "
            + localeId
            + " "
            + themeId
            + " "
            + timezoneId);
  }
  /** 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());
      }
    }
  }
 private void cleanupSession() {
   if (session != null && !((SessionImplementor) session).isClosed()) {
     if (session.isConnected()) {
       session.doWork(new RollbackWork());
     }
     session.close();
   }
   session = null;
 }
예제 #6
0
 @Test
 public void getSiteByHQL() {
   Session session = sessionFactory.openSession();
   try {
     int seconds = 11;
     Thread.sleep(seconds * 1000);
     SQLQuery query = session.createSQLQuery("select id from site");
     query.list();
     System.out.println("result========================================");
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     System.out.println("before:");
     System.out.println("connect:" + session.isConnected());
     System.out.println("open:::" + session.isOpen());
     session.clear();
     session.close();
     System.out.println("after:");
     System.out.println("connect:" + session.isConnected());
     System.out.println("open:::" + session.isOpen());
   }
   System.out.println("------------------------------------------------");
   Session session2 = sessionFactory.openSession();
   try {
     int seconds2 = 8;
     Thread.sleep(seconds2 * 1000);
     SQLQuery query = session2.createSQLQuery("select id from site");
     query.list();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     System.out.println("before:");
     System.out.println("connect:" + session2.isConnected());
     System.out.println("open:::" + session2.isOpen());
     session2.clear();
     session2.close();
     System.out.println("after:");
     System.out.println("connect:" + session2.isConnected());
     System.out.println("open:::" + session2.isOpen());
   }
 }
  /**
   * Execute the selection query in the database
   *
   * @return The query result. Each Object is a cell content.
   *     <p>The cell contents use database types (date,int,string...), keep in mind in case of
   *     future conversions/castings.
   * @throws InterruptedException
   */
  @SuppressWarnings("unchecked")
  public List<List<Object>> executeQuery() throws InterruptedException {

    List<List<Object>> rowsList = new ArrayList<List<Object>>();
    Query query;

    if (!session.isConnected()) {
      resetConnection();
    }

    if (sqlSourceHelper.isCustomQuerySet()) {

      query = session.createSQLQuery(sqlSourceHelper.buildQuery());

      if (sqlSourceHelper.getMaxRows() != 0) {
        query = query.setMaxResults(sqlSourceHelper.getMaxRows());
      }
    } else {
      query =
          session
              .createSQLQuery(sqlSourceHelper.getQuery())
              .setFirstResult(Integer.parseInt(sqlSourceHelper.getCurrentIndex()));

      if (sqlSourceHelper.getMaxRows() != 0) {
        query = query.setMaxResults(sqlSourceHelper.getMaxRows());
      }
    }

    try {
      rowsList =
          query
              .setFetchSize(sqlSourceHelper.getMaxRows())
              .setResultTransformer(Transformers.TO_LIST)
              .list();
    } catch (Exception e) {
      resetConnection();
    }

    if (!rowsList.isEmpty()) {
      if (sqlSourceHelper.isCustomQuerySet()) {
        sqlSourceHelper.setCurrentIndex(rowsList.get(rowsList.size() - 1).get(0).toString());
      } else {
        sqlSourceHelper.setCurrentIndex(
            Integer.toString(
                (Integer.parseInt(sqlSourceHelper.getCurrentIndex()) + rowsList.size())));
      }
    }

    return rowsList;
  }
  public static void main(String[] args) {

    System.out.println("-------- MySQL Hibernate Connection Testing ------------");

    Session session = HibernateUtil.getSessionFactory().openSession();

    if (session.isConnected()) {
      System.out.println("Connection Successful!! You made it, take control your database now!");
    } else {
      System.out.println("Failed to make connection!");
    }

    System.out.println("Now Gathering Hibernate Statistics");

    Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
    stats.setStatisticsEnabled(true);

    // Number of connection requests. Note that this number represents
    // the number of times Hibernate asked for a connection, and
    // NOT the number of connections (which is determined by your
    // pooling mechanism).
    System.out.println("Number of Connections # " + stats.getConnectCount());
    // Number of flushes done on the session (either by client code or
    // by hibernate).
    System.out.println("Flush Count # " + stats.getFlushCount());
    // The number of completed transactions (failed and successful).
    System.out.println(
        "The number of completed transactions (failed and successful) # "
            + stats.getTransactionCount());
    // The number of transactions completed without failure
    System.out.println(
        "The number of transactions completed without failure# "
            + stats.getSuccessfulTransactionCount());
    // The number of sessions your code has opened.
    System.out.println(
        "The number of sessions your code has opened # " + stats.getSessionOpenCount());
    // The number of sessions your code has closed.
    System.out.println(
        "The number of sessions your code has closed # " + stats.getSessionCloseCount());
    // All of the queries that have executed.
    System.out.println("All of the queries that have executed # " + stats.getQueries());
    // Total number of queries executed.
    System.out.println("Total number of queries executed # " + stats.getQueryExecutionCount());
    // Time of the slowest query executed.
    System.out.println("Time of the slowest query executed # " + stats.getQueryExecutionMaxTime());

    System.out.println("---------------------------------------------------");
    stats.logSummary();
  }
  /** Restore all the VOs related to this core responsibility structure */
  public void restore() throws ArchEException {
    Session openSession = ArchECoreDataProvider.getSessionFactory().getCurrentSession();
    if (openSession != null && openSession.isConnected() && openSession.isOpen()) {
      try {
        // Restore a raw responsibility structure
        rawRSVO =
            (ArchEResponsibilityStructureVO)
                (openSession
                    .createQuery("from ArchEResponsibilityStructureVO as v where v.id = ?")
                    .setInteger(0, version.getId())
                    .uniqueResult());

        // Lazy initialization of collections
        Hibernate.initialize(rawRSVO.getResponsibilities());

        for (Iterator<ArchEResponsibilityVO> itResps = rawRSVO.getResponsibilities().iterator();
            itResps.hasNext(); )
          this.restoreParametersForResponsibility(itResps.next(), openSession);

        // Restore the translation relations from requirements to responsibilities
        Query qrels =
            ArchECoreDataProvider.getSessionFactory()
                .getCurrentSession()
                .createQuery(
                    "from ArchETranslationRelationVO as rel where rel.parentType = ? and rel.version = ?");
        qrels.setString(0, "Scenario");
        qrels.setInteger(1, version.getId());
        trVOs = qrels.list();

        // Restore the refinement relations (between responsibilities)
        Query qrefs =
            ArchECoreDataProvider.getSessionFactory()
                .getCurrentSession()
                .createQuery("from ArchERefinementRelationVO as rel where rel.version = ?");
        qrefs.setInteger(0, version.getId());
        refVOs = qrefs.list();

      } catch (HibernateException ex) {
        throw new ArchEException(ex.getMessage(), ex.getCause());
      }
    }
  }
  /**
   * Save AS all the VOs related to this core responsibility structure
   *
   * @param newVersion The version for the new VOs
   * @throws ArchEException
   */
  public void saveAs(ArchEVersionVO newVersion) throws ArchEException {
    Session openSession = ArchECoreDataProvider.getSessionFactory().getCurrentSession();
    if (openSession != null && openSession.isConnected() && openSession.isOpen()) {
      try {

        // Save the newly-created raw responsibility structure
        rawRSVO.setId(newVersion.getId());

        ArchEResponsibilityVO itemResp = null;
        for (Iterator<ArchEResponsibilityVO> it = rawRSVO.getResponsibilities().iterator();
            it.hasNext(); ) {
          itemResp = it.next();
          itemResp.setVersion(newVersion);
          openSession.save(itemResp);
          this.saveParametersForResponsibilityAs(newVersion, itemResp, openSession);
        }

        // Create a copy of the existing translation relations
        ArchETranslationRelationVO itemTr = null;
        for (Iterator<ArchETranslationRelationVO> it = trVOs.iterator(); it.hasNext(); ) {
          itemTr = it.next();
          itemTr.setVersion(newVersion);
          openSession.save(itemTr);
        }

        // Create a copy of the existing refinement relations
        ArchERefinementRelationVO itemRef = null;
        for (Iterator<ArchERefinementRelationVO> it = refVOs.iterator(); it.hasNext(); ) {
          itemRef = it.next();
          itemRef.setVersion(newVersion);
          openSession.save(itemRef);
        }

      } catch (HibernateException ex) {
        throw new ArchEException(ex.getMessage(), ex.getCause());
      }
    }
  }
  /**
   * Delete all the VOs related to this core responsibility structure
   *
   * @throws ArchEException
   */
  public void delete() throws ArchEException {
    Session openSession = ArchECoreDataProvider.getSessionFactory().getCurrentSession();
    if (openSession != null && openSession.isConnected() && openSession.isOpen()) {
      try {
        // Delete the raw responsibility structure
        openSession.delete(rawRSVO);

        for (Iterator<ArchEResponsibilityVO> itResps = rawRSVO.getResponsibilities().iterator();
            itResps.hasNext(); )
          this.deleteParametersForResponsibility(itResps.next(), openSession);

        // Delete the translation relations
        for (Iterator<ArchETranslationRelationVO> itTr = trVOs.iterator(); itTr.hasNext(); )
          openSession.delete(itTr.next());

        // Delete the refinement relations
        for (Iterator<ArchERefinementRelationVO> itRef = refVOs.iterator(); itRef.hasNext(); )
          openSession.delete(itRef.next());

      } catch (HibernateException ex) {
        throw new ArchEException(ex.getMessage(), ex.getCause());
      }
    }
  }
예제 #12
0
 public void disconnect() {
   if (session.isConnected()) session.disconnect();
 }
예제 #13
0
 public boolean isConnected() {
   return session.isConnected();
 }
예제 #14
0
 /**
  * Disconnect and return Session from current Thread.
  *
  * @return Session the disconnected Session
  */
 public static Session disconnectSession() {
   Session session = getSession();
   threadSession.set(null);
   if (session.isConnected() && session.isOpen()) session.disconnect();
   return session;
 }