public void excuteBatch() throws BusinessException {
    Connection conn = null;
    PreparedStatement psmt = null;

    synchronized (vector) {
      try {
        conn = DataSourceUtils.getConnection(SessionFactoryUtils.getDataSource(sessionFactory));
        conn.setAutoCommit(false);
        psmt = conn.prepareStatement(SqlFactory.getInstance().insertPolicyDevice());
        for (PolicyDevice pd : vector) {
          psmt.setString(1, (String) new UUIDHexGenerator().generate(null, null));
          psmt.setString(2, pd.getPolicyId());
          psmt.setString(3, pd.getDeviceId());
          psmt.setShort(4, pd.getType());
          psmt.setShort(5, pd.getStatus());
          psmt.addBatch();
        }
        psmt.executeBatch();
        conn.commit();
        vector.clear();
      } catch (SQLException e) {
        e.printStackTrace();
        try {
          if (conn != null) {
            conn.rollback();
          }
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
        throw new BusinessException(
            ErrorCode.DATABASE_ACCESS_ERROR, "Could not get database connnection");
      } catch (Exception e) {
        e.printStackTrace();
        try {
          if (conn != null) {
            conn.rollback();
          }
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
        throw new BusinessException(ErrorCode.ERROR, e.getMessage());
      } finally {
        try {
          if (psmt != null) {
            psmt.close();
            psmt = null;
          }
          if (conn != null) {
            DataSourceUtils.releaseConnection(
                conn, SessionFactoryUtils.getDataSource(sessionFactory));
          }
        } catch (Exception e) {
          e.printStackTrace();
          throw new BusinessException(
              ErrorCode.DATABASE_ACCESS_ERROR, "Could not close database connnection");
        }
      }
    }
  }
  /**
   * Obtain a Hibernate Session, either from the current transaction or a new one. The latter is
   * only allowed if "allowCreate" is true.
   *
   * <p><b>Note that this is not meant to be invoked from HibernateTemplate code but rather just in
   * plain Hibernate code.</b> Either rely on a thread-bound Session or use it in combination with
   * {@link #releaseSession}.
   *
   * <p>In general, it is recommended to use {@link #getHibernateTemplate() HibernateTemplate},
   * either with the provided convenience operations or with a custom {@link
   * org.springframework.orm.hibernate3.HibernateCallback} that provides you with a Session to work
   * on. HibernateTemplate will care for all resource management and for proper exception
   * conversion.
   *
   * @param allowCreate if a non-transactional Session should be created when no transactional
   *     Session can be found for the current thread
   * @return the Hibernate Session
   * @throws DataAccessResourceFailureException if the Session couldn't be created
   * @throws IllegalStateException if no thread-bound Session found and allowCreate=false
   * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
   */
  protected final Session getSession(boolean allowCreate)
      throws DataAccessResourceFailureException, IllegalStateException {

    return (!allowCreate
        ? SessionFactoryUtils.getSession(getSessionFactory(), false)
        : SessionFactoryUtils.getSession(
            getSessionFactory(),
            this.hibernateTemplate.getEntityInterceptor(),
            this.hibernateTemplate.getJdbcExceptionTranslator()));
  }
Exemple #3
0
  @Override
  protected void tearDown() throws Exception {
    TransactionSynchronizationManager.unbindResource(sessionFactory);
    SessionFactoryUtils.releaseSession(session, sessionFactory);

    super.tearDown();
  }
 /** {@inheritDoc} */
 public String getUserPassword(String username) {
   SimpleJdbcTemplate jdbcTemplate =
       new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory()));
   Table table = AnnotationUtils.findAnnotation(User.class, Table.class);
   return jdbcTemplate.queryForObject(
       "select password from " + table.name() + " where username=?", String.class, username);
 }
  /* (non-Javadoc)
   * @see org.jobcenter.internalservice.SetUpHibernateSessionForNonWebRequestProcessing#closeSession()
   */
  public void closeSession() {

    if (sessionFactory != null) {

      SessionHolder sessionHolder =
          (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);

      SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
  }
  public void doStuff(String userName, String rollName, String albumName) {
    Session m_session = SessionFactoryUtils.getSession(m_sessionFactory, false);
    try {
      m_transaction = m_session.beginTransaction();

      ImageGroupRepository gf = (ImageGroupRepository) m_appContext.getBean(GROUP_FACTORY_BEAN);
      UserRepository uf = (UserRepository) m_appContext.getBean(USER_FACTORY_BEAN);

      ImageGroup roll = gf.getRollByOwnerAndName(uf.getByScreenName(userName), rollName);

      ImageGroup album = new ImageGroup(albumName, roll.getOwner(), ImageGroup.Type.ALBUM);
      album.setDisplayName(roll.getDisplayName());
      album.setDescription(roll.getDescription());
      album.setSupergroup(roll.getSupergroup());
      // XXX: not copying subgroups
      // this is probably a leaf group
      m_session.save(album);

      SortedSet frames = roll.getFrames();
      Iterator iter = frames.iterator();
      ImageFrame oldFrame, newFrame;
      while (iter.hasNext()) {
        oldFrame = (ImageFrame) iter.next();
        newFrame = new ImageFrame(oldFrame.getImage());
        newFrame.setPosition(oldFrame.getPosition());
        newFrame.setCaption(oldFrame.getCaption());
        newFrame.setImageGroup(album);
        m_session.save(newFrame);
        s_logger.debug("Saved frame " + newFrame.getPosition());
      }
      m_session.save(album);
      m_transaction.commit();
      SessionFactoryUtils.releaseSession(m_session, m_sessionFactory);
      s_logger.info("Saved new album: " + album.getName());
    } catch (Exception e) {
      s_logger.error("Exception copying image frame data", e);
      try {
        m_transaction.rollback();
      } catch (HibernateException e1) {
        s_logger.error("Exception rolling back transaction!", e1);
      }
    }
  }
Exemple #7
0
 @Transactional
 void clear(final String organismCommonName, final String analysisProgram)
     throws HibernateException, SQLException {
   Session session = SessionFactoryUtils.getSession(sessionFactory, false);
   session.doWork(
       new Work() {
         public void execute(Connection connection) throws SQLException {
           new ClearDomains(connection, organismCommonName, analysisProgram).clear();
         }
       });
 }
Exemple #8
0
  protected void setUp() throws Exception {
    super.setUp();

    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    hibernateTemplate = (HibernateTemplate) context.getBean("hibernateTemplate");

    sessionFactory = (SessionFactory) context.getBean("sessionFactory");

    session = SessionFactoryUtils.getSession(sessionFactory, null, null);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
  }
  /** @param args */
  public static void main(String[] args) throws Exception {
    System.out.println("Starting up... " + new Date());
    logger.info("Starting up...");
    ApplicationContext context = new ClassPathXmlApplicationContext("rssAggregatorContext.xml");
    SessionFactory sessionFactory = context.getBean(SessionFactory.class);

    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));

    RSSAggregatorService rssAggregatorService =
        context.getBean("rssAggregatorService", RSSAggregatorService.class);
    rssAggregatorService.checkActiveFeedsForUpdates();

    // check the feeds?

    TransactionSynchronizationManager.unbindResource(sessionFactory);
    SessionFactoryUtils.releaseSession(session, sessionFactory);

    System.out.println("Finished at " + new Date());
    logger.info("Finished");
  }
 /**
  * Close the session and shut down the database. This method should be called once the tests are
  * complete. It should ordinarily be called from an <code>@AfterClass</code> method of the test
  * class.
  */
 public void cleanUp() {
   /*
    * If the database is not shutdown, the changes will not be
    * persisted to the data file. It's useful to be able to inspect
    * the loaded data directly sometimes, so it's important to do
    * this. (The HSLQDB documentation suggests that comitted changes
    * will never be lost even if the database is not shut down. That
    * does not appear to be true.)
    */
   session.createSQLQuery("shutdown").executeUpdate();
   SessionFactoryUtils.releaseSession(session, sessionFactory);
   session = null;
 }
 private boolean bindSession() {
   if (sessionFactory == null) {
     throw new IllegalStateException("No sessionFactory property provided");
   }
   final Object inStorage = TransactionSynchronizationManager.getResource(sessionFactory);
   if (inStorage != null) {
     ((SessionHolder) inStorage).getSession().flush();
     return false;
   } else {
     Session session = SessionFactoryUtils.getSession(sessionFactory, true);
     session.setFlushMode(FlushMode.AUTO);
     TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
     return true;
   }
 }
 public void staticIndex() {
   log.info("static index  page");
   CmsSite site = cmsSiteMng.findById(siteId);
   Session session = SessionFactoryUtils.getSession(sessionFactory, true);
   session = sessionFactory.openSession();
   session.beginTransaction();
   site = (CmsSite) session.get(site.getClass(), site.getId());
   try {
     staticPageSvc.index(site);
   } catch (IOException e) {
     log.error("static index error!", e);
   } catch (TemplateException e) {
     log.error("static index error!", e);
   }
   session.flush();
   session.close();
 }
 private void unbindSession() {
   if (sessionFactory == null) {
     throw new IllegalStateException("No sessionFactory property provided");
   }
   SessionHolder sessionHolder =
       (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
   try {
     if (!FlushMode.MANUAL.equals(sessionHolder.getSession().getFlushMode())) {
       sessionHolder.getSession().flush();
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     TransactionSynchronizationManager.unbindResource(sessionFactory);
     SessionFactoryUtils.closeSession(sessionHolder.getSession());
   }
 }
 @Transactional
 private void createOrganismIfNecessary(
     String organismCommonName,
     String organismGenus,
     String organismSpecies,
     String organismStrain) {
   Session session = SessionFactoryUtils.getSession(sessionFactory, false);
   Organism organism = organismDao.getOrganismByCommonName(organismCommonName);
   if (organism != null) {
     logger.debug(String.format("Organism '%s' already exists", organismCommonName));
     return;
   }
   if (organismStrain != null) {
     organismSpecies += " " + organismStrain;
   }
   logger.debug(
       String.format(
           "Creating organism '%s' (%s %s)", organismCommonName, organismGenus, organismSpecies));
   organism =
       new Organism(organismGenus, organismSpecies, organismCommonName, organismCommonName, null);
   session.persist(organism);
   session.flush();
 }
Exemple #15
0
 /**
  * Close the given Hibernate Session, created via this DAO's SessionFactory, if it isn't bound to
  * the thread (i.e. isn't a transactional Session).
  *
  * <p>Typically used in plain Hibernate code, in combination with {@link #getSession} and {@link
  * #convertHibernateAccessException}.
  *
  * @param session the Session to close
  * @see org.springframework.orm.hibernate3.SessionFactoryUtils#releaseSession
  */
 protected final void releaseSession(Session session) {
   SessionFactoryUtils.releaseSession(session, getSessionFactory());
 }
  /* (non-Javadoc)
   * @see org.jobcenter.internalservice.SetUpHibernateSessionForNonWebRequestProcessing#openSession()
   */
  public void openSession() {

    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
  }
 private void closeAfterTimeout() {
   if (this.timeoutInProgress) {
     logger.debug("Closing Hibernate Session after async request timeout");
     SessionFactoryUtils.closeSession(sessionHolder.getSession());
   }
 }
  /**
   * This method reads all the task from an xml file and registers them with the MifosScheduler
   *
   * @param document Task configuration document
   * @throws TaskSystemException when something goes wrong
   */
  @Deprecated
  private void registerTasksOldConfigurationFile(Document document) throws TaskSystemException {
    try {
      logger.warn(
          "Old format task.xml configuration file is deprecated. Please configure scheduler using spring managed beans.");
      NodeList rootSchedulerTasks =
          document.getElementsByTagName(SchedulerConstants.SCHEDULER_TASKS);
      Element rootNodeName = (Element) rootSchedulerTasks.item(0);
      NodeList collectionOfScheduledTasks =
          rootNodeName.getElementsByTagName(SchedulerConstants.SCHEDULER);

      DataSource dataSource =
          SessionFactoryUtils.getDataSource(StaticHibernateUtil.getSessionFactory());
      SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);

      JobRegistry jobRegistry = new MapJobRegistry();
      this.jobLocator = jobRegistry;

      JdbcJobInstanceDao jobInstanceDao = new JdbcJobInstanceDao();
      jobInstanceDao.setJdbcTemplate(jdbcTemplate);
      jobInstanceDao.setJobIncrementer(
          new MySQLMaxValueIncrementer(dataSource, "BATCH_JOB_SEQ", "id"));
      jobInstanceDao.afterPropertiesSet();

      JdbcJobExecutionDao jobExecutionDao = new JdbcJobExecutionDao();
      jobExecutionDao.setJdbcTemplate(jdbcTemplate);
      jobExecutionDao.setJobExecutionIncrementer(
          new MySQLMaxValueIncrementer(dataSource, "BATCH_JOB_EXECUTION_SEQ", "id"));
      jobExecutionDao.afterPropertiesSet();

      JdbcStepExecutionDao stepExecutionDao = new JdbcStepExecutionDao();
      stepExecutionDao.setJdbcTemplate(jdbcTemplate);
      stepExecutionDao.setStepExecutionIncrementer(
          new MySQLMaxValueIncrementer(dataSource, "BATCH_STEP_EXECUTION_SEQ", "id"));
      stepExecutionDao.afterPropertiesSet();

      JdbcExecutionContextDao executionContextDao = new JdbcExecutionContextDao();
      executionContextDao.setJdbcTemplate(jdbcTemplate);
      executionContextDao.afterPropertiesSet();

      JobRepository jobRepository =
          new SimpleJobRepository(
              jobInstanceDao, jobExecutionDao, stepExecutionDao, executionContextDao);
      this.jobRepository = jobRepository;

      SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
      jobLauncher.setJobRepository(jobRepository);
      jobLauncher.setTaskExecutor(new SyncTaskExecutor());
      jobLauncher.afterPropertiesSet();
      this.jobLauncher = jobLauncher;

      JobExplorer jobExplorer =
          new SimpleJobExplorer(
              jobInstanceDao, jobExecutionDao, stepExecutionDao, executionContextDao);
      this.jobExplorer = jobExplorer;

      Map<String, Object> jobData = new HashMap<String, Object>();
      jobData.put("jobLocator", jobRegistry);
      jobData.put("jobLauncher", jobLauncher);
      jobData.put("jobExplorer", jobExplorer);
      jobData.put("jobRepository", jobRepository);

      JobRegistryBeanPostProcessor jobRegistryProcessor = new JobRegistryBeanPostProcessor();
      jobRegistryProcessor.setJobRegistry(jobRegistry);
      ResourcelessTransactionManager transactionManager = new ResourcelessTransactionManager();

      Date loanArrearsTaskInitialTime = null;
      Long loanArrearsTaskDelayTime = null;
      boolean portfolioAtRiskTaskExists = false;

      for (int i = 0; i < collectionOfScheduledTasks.getLength(); i++) {
        Element scheduledTask = (Element) collectionOfScheduledTasks.item(i);
        Element subNodeName1 =
            (Element)
                scheduledTask.getElementsByTagName(SchedulerConstants.TASK_CLASS_NAME).item(0);
        String taskName = ((Text) subNodeName1.getFirstChild()).getData().trim();
        Element subNodeName2 =
            (Element) scheduledTask.getElementsByTagName(SchedulerConstants.INITIAL_TIME).item(0);
        String initialTime = ((Text) subNodeName2.getFirstChild()).getData().trim();
        Element subNodeName3;
        String delayTime = null;
        if ((scheduledTask.getElementsByTagName(SchedulerConstants.DELAY_TIME)) != null) {
          subNodeName3 =
              (Element) scheduledTask.getElementsByTagName(SchedulerConstants.DELAY_TIME).item(0);
          if (subNodeName3.getFirstChild() != null) {
            delayTime = ((Text) subNodeName3.getFirstChild()).getData().trim();
          }
        }
        if (Long.parseLong(delayTime) < 86400) {
          throw new IllegalArgumentException("Please specify the delay time >= 86400(1 day)");
        }
        if (scheduler.getJobDetail(taskName, Scheduler.DEFAULT_GROUP) != null) {
          scheduler.unscheduleJob(taskName, Scheduler.DEFAULT_GROUP);
        }
        if ("LoanArrearsTask".equals(taskName)) {
          loanArrearsTaskInitialTime = parseInitialTime(initialTime);
          loanArrearsTaskDelayTime = Long.parseLong(delayTime) * 1000;
          continue;
        }
        if ("PortfolioAtRiskTask".equals(taskName)) {
          portfolioAtRiskTaskExists = true;
          continue;
        }
        schedule(
            taskName,
            parseInitialTime(initialTime),
            Long.parseLong(delayTime) * 1000,
            jobRegistry,
            jobRepository,
            jobData,
            transactionManager);
      }
      if (loanArrearsTaskInitialTime != null) {
        if (portfolioAtRiskTaskExists) {
          scheduleLoanArrearsAndPortfolioAtRisk(
              loanArrearsTaskInitialTime,
              loanArrearsTaskDelayTime,
              jobRegistry,
              jobRepository,
              jobData,
              transactionManager);
        } else {
          schedule(
              "LoanArrearsTask",
              loanArrearsTaskInitialTime,
              loanArrearsTaskDelayTime,
              jobRegistry,
              jobRepository,
              jobData,
              transactionManager);
        }
      }
    } catch (Exception e) {
      throw new TaskSystemException(e);
    }
  }
 public void setSessionFactory(SessionFactory sessionFactory) {
   this.sessionFactory = sessionFactory;
   this.session = SessionFactoryUtils.getSession(sessionFactory, true);
 }
 protected final Session getSession() {
   return SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
 }
  @Override
  protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    try {
      logger.debug("running offer update rules job:" + Calendar.getInstance().getTimeInMillis());

      // bind session to thread
      Session session = null;
      try {
        session = SessionFactoryUtils.getSession(sessionFactory, false);
      }
      // If not already bound the Create and Bind it!
      catch (java.lang.IllegalStateException ex) {
        session = SessionFactoryUtils.getSession(sessionFactory, true);
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
      }
      session.setFlushMode(FlushMode.AUTO);

      // find awards whose offers are expired only on bl failure
      // really should fire working memory rules against rater that has expired
      // awards

      List<Offer> expired = awardManagerService.findExpiredAwardOffers();

      logger.debug("number of expired offers:" + expired.size());

      /*for (AwardOffer awardOffer : expired) {
      	//logger.debug(awardOffer.getOffer().getExpireDateMillis());

      	//delete any expired offer
      	//remove the offer from the award
      	Award a = awardOffer.getAward();
      	a.getOffers().remove(awardOffer);
      	awardManagerService.saveAward(a);

      	awardManagerService.deleteAwardOffer(awardOffer);

      	if(awardOffer.getAward() != null)
      	{
      		//dont throw if one has a problem
      		try {
      			updateAwardOfferMessageProducer
      			.generateMessage(
      					awardOffer.getAward(),
      					awardOffer.getAwardType(),
      					awardOffer.getAward().getOwner());
      		} catch (JsonGenerationException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (JsonMappingException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (JMSException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (IOException e) {
      			logger.error("problem udating expired offer", e);
      		}
      	}


      }*/

    } catch (com.noi.utility.spring.service.BLServiceException e) {
      logger.error("problem updating expired offers", e);
      throw new JobExecutionException(e);
    } catch (Exception e) {
      logger.error("problem updating expired offers", e);
      throw new JobExecutionException(e);
    } finally {
      // unbind
      SessionHolder sessionHolder =
          (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
      if (!FlushMode.MANUAL.equals(sessionHolder.getSession().getFlushMode())) {
        sessionHolder.getSession().flush();
      }
      SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
  }
 /**
  * 获取hibernate session</br> 日期:2013-5-14 下午06:30:42
  *
  * @return hibernate session对象
  */
 public Session getSession() {
   return SessionFactoryUtils.getSession(getSessionFactory(), true);
 }
Exemple #23
0
 public Session getSession() {
   boolean allowCreate = true;
   return SessionFactoryUtils.getSession(sessionFactory, allowCreate);
 }