Java 类org.hibernate.context.internal.ManagedSessionContext 实例源码

项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkAspect.java   
public void afterEnd() {
    if (this.session == null) {
        return;
    }

    try {
        this.commitTransaction();
    } catch (final Exception e) {
        this.rollbackTransaction();
        throw e;
    } finally {
        this.session.close();
        this.session = null;
        ManagedSessionContext.unbind(this.sessionFactory);
        this.sessionHolders.remove(this);
    }

}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkApplicationListenerTest.java   
@Test
public void bindsAndUnbindsTheSessionToTheManagedContext() throws Exception {
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            assertThat(ManagedSessionContext
                    .hasBind(UnitOfWorkApplicationListenerTest.this.sessionFactory))
                            .isTrue();
            return null;
        }
    }).when(this.session).beginTransaction();

    this.execute();

    assertThat(ManagedSessionContext.hasBind(this.sessionFactory)).isFalse();
}
项目:dropwizard-db-sharding-bundle    文件:TransactionHandler.java   
public void afterEnd() {
    if (session == null) {
        return;
    }

    try {
        commitTransaction();
    } catch (Exception e) {
        rollbackTransaction();
        throw e;
    } finally {
        session.close();
        session = null;
        ManagedSessionContext.unbind(sessionFactory);
    }

}
项目:flux    文件:DbClearRule.java   
/** Clears all given tables which are mentioned using the given sessionFactory*/
private void clearDb(Class[] tables, SessionFactory sessionFactory) {
    Session session = sessionFactory.openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        sessionFactory.getCurrentSession().createSQLQuery("set foreign_key_checks=0").executeUpdate();
        for (Class anEntity : tables) {
            sessionFactory.getCurrentSession().createSQLQuery("delete from " + anEntity.getSimpleName() + "s").executeUpdate(); //table name is plural form of class name, so appending 's'
        }
        sessionFactory.getCurrentSession().createSQLQuery("set foreign_key_checks=1").executeUpdate();
        tx.commit();
    } catch (Exception e) {
        if(tx != null)
            tx.rollback();
        throw new RuntimeException("Unable to clear tables. Exception: "+e.getMessage(), e);
    } finally {
        if(session != null) {
            ManagedSessionContext.unbind(sessionFactory);
            session.close();
        }
    }
}
项目:flux    文件:EventSchedulerDaoTest.java   
@Before
public void setUp() throws Exception {
    sessionFactory.useDefault();
    Session session = sessionFactory.getSessionFactory().openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        sessionFactory.getSessionFactory().getCurrentSession().createSQLQuery("delete from ScheduledEvents").executeUpdate();
        tx.commit();
    } finally {
        if (session != null) {
            ManagedSessionContext.unbind(sessionFactory.getSessionFactory());
            session.close();
            sessionFactory.clear();
        }
    }
}
项目:flux    文件:MessageDaoTest.java   
@Before
public void setUp() throws Exception {
    sessionFactory.useDefault();
    Session session = sessionFactory.getSessionFactory().openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        sessionFactory.getSessionFactory().getCurrentSession().createSQLQuery("delete from ScheduledMessages").executeUpdate();
        tx.commit();
    } finally {
        if(session != null) {
            ManagedSessionContext.unbind(sessionFactory.getSessionFactory());
            session.close();
            sessionFactory.clear();
        }
    }
}
项目:Pinot    文件:AnomalyDetectionJob.java   
private void handleResults(List<AnomalyResult> results) {
  Session session = sessionFactory.openSession();
  try {
    ManagedSessionContext.bind(session);
    Transaction transaction = session.beginTransaction();
    try {
      for (AnomalyResult result : results) {
        result.setFunctionId(anomalyFunction.getSpec().getId());
        result.setFunctionType(anomalyFunction.getSpec().getType());
        result.setFunctionProperties(anomalyFunction.getSpec().getProperties());
        resultDAO.create(result);
      }
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw new RuntimeException(e);
    }
  } finally {
    session.close();
    ManagedSessionContext.unbind(sessionFactory);
  }
}
项目:Pinot    文件:HibernateSessionWrapper.java   
public V execute(Callable<V> callable) throws Exception {
  Session session = sessionFactory.openSession();
  Transaction transaction = session.beginTransaction();
  try {
    ManagedSessionContext.bind(session);
    V result = callable.call();
    transaction.commit();
    return result;
  } catch (Exception e) {
    transaction.rollback();
    throw e;
  } finally {
    session.close();
    ManagedSessionContext.unbind(sessionFactory);
  }
}
项目:amos-ss15-proj2    文件:AbstractScheduledTaskExecutor.java   
@Override
public void run() {
    Session session = null;
    try {
        session = sessionFactory.openSession();
        ManagedSessionContext.bind(session);
        logManager.d("Running " + getClass().getName());
        doRun();
    } catch (Exception e) {
        logManager.e(e, "failed to run " + getClass().getName());
    } finally {
        if (session != null) {
            session.flush();
            session.close();
        }
    }

}
项目:robe    文件:AuthenticatedWebSocket.java   
@Override
public String onConnect(Session session) {
    for (HttpCookie cookie : session.getUpgradeRequest().getCookies()) {
        if ("auth-token".equals(cookie.getName())) {
            String authToken = cookie.getValue();
            TokenAuthenticator authenticator = getAuthenticator();
            org.hibernate.Session hSession = sessionFactory.openSession();
            ManagedSessionContext.bind(hSession);
            Optional<BasicToken> token;
            try {
                token = authenticator.authenticate(authToken);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return null;
            }
            if (!token.isPresent()) {
                return null;
            }
            hSession.close();
            return token.get().getUserId();
        }
    }
    return null;
}
项目:robe    文件:SystemParameterCacheTest.java   
@Test
public void get() {

    SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
    ManagedSessionContext.bind(sessionFactory.openSession());
    SystemParameterDao dao = new SystemParameterDao(sessionFactory);

    SystemParameter parameter = new SystemParameter();
    parameter.setValue("ROBE");
    parameter.setKey("TEST");
    parameter = dao.create(parameter);
    dao.flush();

    Object value = SystemParameterCache.get("DEFAULT", "default"); // TODO GuiceBundle not initialized
    Assert.assertTrue(value.equals("default"));

    Object value2 = SystemParameterCache.get("TEST", "none");
    Assert.assertTrue(value2.equals("ROBE"));

    dao.detach(parameter);
    dao.delete(parameter);
    dao.flush();
}
项目:commafeed    文件:UnitOfWork.java   
public static <T> T call(SessionFactory sessionFactory, SessionRunnerReturningValue<T> sessionRunner) {
    final Session session = sessionFactory.openSession();
    if (ManagedSessionContext.hasBind(sessionFactory)) {
        throw new IllegalStateException("Already in a unit of work!");
    }
    T t = null;
    try {
        ManagedSessionContext.bind(session);
        session.beginTransaction();
        try {
            t = sessionRunner.runInSession();
            commitTransaction(session);
        } catch (Exception e) {
            rollbackTransaction(session);
            UnitOfWork.<RuntimeException> rethrow(e);
        }
    } finally {
        session.close();
        ManagedSessionContext.unbind(sessionFactory);
    }
    return t;
}
项目:stroom-stats    文件:StatisticConfigurationServiceImpl.java   
private <T> T executeInSession(Supplier<T> task) {

        try (Session session = sessionFactory.openSession()) {
            ManagedSessionContext.bind(session);
            session.beginTransaction();

            return task.get();
        } catch (Exception e) {
            throw new RuntimeException(String.format("Error executing task, %s", e.getMessage()), e);
        }
    }
项目:lams    文件:SessionFactoryImpl.java   
private CurrentSessionContext buildCurrentSessionContext() {
    String impl = properties.getProperty( Environment.CURRENT_SESSION_CONTEXT_CLASS );
    // for backward-compatibility
    if ( impl == null ) {
        if ( canAccessTransactionManager() ) {
            impl = "jta";
        }
        else {
            return null;
        }
    }

    if ( "jta".equals( impl ) ) {
        if ( ! transactionFactory().compatibleWithJtaSynchronization() ) {
            LOG.autoFlushWillNotWork();
        }
        return new JTASessionContext( this );
    }
    else if ( "thread".equals( impl ) ) {
        return new ThreadLocalSessionContext( this );
    }
    else if ( "managed".equals( impl ) ) {
        return new ManagedSessionContext( this );
    }
    else {
        try {
            Class implClass = serviceRegistry.getService( ClassLoaderService.class ).classForName( impl );
            return ( CurrentSessionContext ) implClass
                    .getConstructor( new Class[] { SessionFactoryImplementor.class } )
                    .newInstance( this );
        }
        catch( Throwable t ) {
            LOG.unableToConstructCurrentSessionContext( impl, t );
            return null;
        }
    }
}
项目:lams    文件:TransactionAwareSessionContext.java   
/**
    * Creates a new session context and sets the related session factory.
    *
    * @param theSessionFactory
    *            Context session factory. Cannot be null.
    */
   public TransactionAwareSessionContext(final SessionFactoryImplementor theSessionFactory) {
Validate.notNull(theSessionFactory, "The session factory cannot be null.");

defaultSessionContext = new SpringSessionContext(theSessionFactory);
localSessionContext = new ManagedSessionContext(theSessionFactory);
sessionFactory = theSessionFactory;
   }
项目:lams    文件:TransactionAwareSessionContext.java   
/**
    * Binds the configured session to Spring's transaction manager strategy if there's no session.
    *
    * @return Returns the configured session, or the one managed by Spring. Never returns null.
    */
   @Override
   public Session currentSession() {
try {
    Session s = defaultSessionContext.currentSession();
    return s;
} catch (HibernateException cause) {

    // There's no session bound to the current thread. Let's open one if
    // needed.
    if (ManagedSessionContext.hasBind(sessionFactory)) {
    return localSessionContext.currentSession();
    }

    Session session;
    session = sessionFactory.openSession();
    TransactionAwareSessionContext.logger.warn("No Session bound to current Thread. Opened new Session ["
        + session + "]. Transaction: " + session.getTransaction());

    if (registerSynchronization(session)) {
    // Normalizes Session flush mode, defaulting it to AUTO. Required for
    // synchronization.
    FlushMode flushMode = session.getFlushMode();

    if (FlushMode.isManualFlushMode(flushMode)
        && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
        session.setFlushMode(FlushMode.AUTO);
    }
    }
    ManagedSessionContext.bind(session);

    return session;
}
   }
项目:lams    文件:TransactionAwareSessionContext.java   
/**
    * Creates a transaction synchronization object for the specified session.
    *
    * @param session
    *            Session to synchronize using the created object. Cannot be null.
    * @return A valid transaction synchronization. Never returns null.
    */
   private TransactionSynchronization createTransactionSynchronization(final Session session) {
return new TransactionSynchronizationAdapter() {
    @Override
    public void afterCompletion(final int status) {
    session.close();
    ManagedSessionContext.unbind(sessionFactory);
    }
};
   }
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkAspect.java   
public void onError() {
    if (this.session == null) {
        return;
    }

    try {
        this.rollbackTransaction();
    } finally {
        this.session.close();
        this.session = null;
        ManagedSessionContext.unbind(this.sessionFactory);
        this.sessionHolders.remove(this);
    }
}
项目:dropwizard-db-sharding-bundle    文件:TransactionHandler.java   
public void beforeStart() {

        session = sessionFactory.openSession();
        try {
            configureSession();
            ManagedSessionContext.bind(session);
            beginTransaction();
        } catch (Throwable th) {
            session.close();
            session = null;
            ManagedSessionContext.unbind(sessionFactory);
            throw th;
        }
    }
项目:dropwizard-db-sharding-bundle    文件:TransactionHandler.java   
public void onError() {
    if (session == null) {
        return;
    }

    try {
        rollbackTransaction();
    } finally {
        session.close();
        session = null;
        ManagedSessionContext.unbind(sessionFactory);
    }
}
项目:Pinot    文件:AnomalyDetectionJob.java   
private List<AnomalyResult> getExistingAnomalies() {
  List<AnomalyResult> results = new ArrayList<>();

  Session session = sessionFactory.openSession();
  try {
    ManagedSessionContext.bind(session);
    Transaction transaction = session.beginTransaction();
    try {
      // The ones for this function
      results.addAll(resultDAO.findAllByCollectionTimeAndFunction(
          collection, windowStart, windowEnd, anomalyFunction.getSpec().getId()));

      // The ones for any related functions
      List<AnomalyFunctionRelation> relations = relationDAO.findByParent(anomalyFunction.getSpec().getId());
      for (AnomalyFunctionRelation relation : relations) {
        results.addAll(resultDAO.findAllByCollectionTimeAndFunction(
            collection, windowStart, windowEnd, relation.getChildId()));
      }

      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw new RuntimeException(e);
    }
  } finally {
    session.close();
    ManagedSessionContext.unbind(sessionFactory);
  }

  return results;
}
项目:robe    文件:JobPersister.java   
public JobPersister(ConcurrentHashMap<String, JobInfo> jobs) {
    SessionFactory sessionFactory = GuiceBundle.getInjector().getInstance(SessionFactory.class);
    ManagedSessionContext.bind(sessionFactory.openSession());
    JobDao jobDao = new JobDao(sessionFactory);
    TriggerDao triggerDao = new TriggerDao(sessionFactory);
    for (JobInfo info : jobs.values()) {
        insertOrUpdate(jobDao, info, triggerDao);
    }
    sessionFactory.getCurrentSession().flush();
    sessionFactory.getCurrentSession().close();
    ManagedSessionContext.unbind(sessionFactory);
}
项目:robe    文件:SystemParameterCache.java   
public static void fillCache() {

        SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
        ManagedSessionContext.bind(sessionFactory.openSession());
        SystemParameterDao dao = new SystemParameterDao(sessionFactory);

        List<SystemParameter> parameters = dao.findAllStrict();

        for (SystemParameter parameter : parameters) {
            cache.put(parameter.getKey(), parameter.getValue());
            dao.detach(parameter);// TODO
        }

    }
项目:robe    文件:RoleResourceTest.java   
@Test
public void getRolePermissions() throws IOException {
    SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
    ManagedSessionContext.bind(sessionFactory.openSession());
    RoleDao roleDao = new RoleDao(sessionFactory);
    Role role = roleDao.findByCode("all");
    Assert.assertTrue(role != null);
    TestRequest request = getRequestBuilder().endpoint(role.getId() + "/permissions").build();
    TestResponse response = client.get(request);
    Map result = response.get(Map.class);

    Assert.assertTrue(result.get("menu") != null);
    Assert.assertTrue(result.get("service") != null);
    ManagedSessionContext.unbind(sessionFactory);
}
项目:robe    文件:BaseDaoTest.java   
@Before
public void before() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    if (sessionFactory == null) {
        sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
        ManagedSessionContext.bind(sessionFactory.openSession());
        this.daoClazz = (Class<D>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        dao = daoClazz.getDeclaredConstructor(SessionFactory.class).newInstance(sessionFactory);
    }
}
项目:robe    文件:Transaction.java   
/**
 * If present, backup current the session in {@link ManagedSessionContext} and unbinds it.
 */
private void storePreviousSession() {
    if (ManagedSessionContext.hasBind(SESSION_FACTORY)) {
        SESSIONS.get().add(SESSION_FACTORY.getCurrentSession());
        ManagedSessionContext.unbind(SESSION_FACTORY);
    }
}
项目:robe    文件:Transaction.java   
/**
 * Closes and unbinds the current session. <br/>
 * If {@link ManagedSessionContext} had a session before the current session, re-binds it to {@link ManagedSessionContext}
 */
private void finish() {
    try {
        if (session != null) {
            session.close();
        }
    } finally {
        ManagedSessionContext.unbind(SESSION_FACTORY);
        if (!SESSIONS.get().isEmpty()) {
            ManagedSessionContext.bind(SESSIONS.get().pop());
        }
    }
}
项目:ueps    文件:DaoTools.java   
/**
 *
 *
 * @return
 */
protected synchronized Session getSession() {
  Session session = HibernateUtil.getSessionFactory().openSession();
  if (!session.isOpen()) {
    session = HibernateUtil.getSessionFactory().openSession();
  }

  session.setFlushMode(FlushMode.MANUAL);
  ManagedSessionContext.bind(session);
  return session;
}
项目:ueps    文件:DaoTools.java   
/**
 *
 *
 */
protected synchronized void endTransaction(Session session, boolean success) {
  if (session != null) {
    Transaction transaction = session.getTransaction();
    try {
      if (session.isOpen()) {
        if (transaction != null && transaction.isActive()) {
          ManagedSessionContext.unbind(HibernateUtil
                                       .getSessionFactory());
          session.flush();
          transaction.commit();
        } else if (!success) {
          if (transaction != null) {
            transaction.rollback();
          }
        }
      }
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      log.error("custom hibernate operation failed", e);
    } finally {
      if (session != null && session.isConnected()) {
        session.close();
      }
    }
  }
}
项目:hibernate-dynamic-dialects    文件:SessionFactoryImpl.java   
private CurrentSessionContext buildCurrentSessionContext() {
    String impl = properties
            .getProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS);
    // for backward-compatibility
    if (impl == null) {
        if (canAccessTransactionManager()) {
            impl = "jta";
        } else {
            return null;
        }
    }

    if ("jta".equals(impl)) {
        if (!transactionFactory().compatibleWithJtaSynchronization()) {
            LOG.autoFlushWillNotWork();
        }
        return new JTASessionContext(this);
    } else if ("thread".equals(impl)) {
        return new ThreadLocalSessionContext(this);
    } else if ("managed".equals(impl)) {
        return new ManagedSessionContext(this);
    } else {
        try {
            Class implClass = serviceRegistry.getService(
                    ClassLoaderService.class).classForName(impl);
            return (CurrentSessionContext) implClass.getConstructor(
                    new Class[] { SessionFactoryImplementor.class })
                    .newInstance(this);
        } catch (Throwable t) {
            LOG.unableToConstructCurrentSessionContext(impl, t);
            return null;
        }
    }
}
项目:jooby    文件:UnitOfWorkProvider.java   
@Override
public UnitOfWork get() {
  if (ManagedSessionContext.hasBind(sf)) {
    return new ChildUnitOfWork(sf.getCurrentSession());
  } else {
    return new RootUnitOfWork(sf.openSession());
  }
}
项目:jooby    文件:UnitOfWorkProviderTest.java   
private Block hasBind(final boolean b) {
  return unit -> {
    unit.mockStatic(ManagedSessionContext.class);

    expect(ManagedSessionContext.hasBind(unit.get(SessionFactory.class))).andReturn(b);
  };
}
项目:jooby    文件:SessionProviderTest.java   
private Block hasBind(final boolean b) {
  return unit -> {
    unit.mockStatic(ManagedSessionContext.class);

    expect(ManagedSessionContext.hasBind(unit.get(SessionFactory.class))).andReturn(b);
  };
}
项目:dropwizard-backbone-app    文件:DAO.java   
public void endSession() {

  if(!sessionFactory.getCurrentSession().isOpen())
    return;

  sessionFactory.getCurrentSession().close();
  ManagedSessionContext.unbind(sessionFactory);
}
项目:dropwizard-jaxws    文件:UnitOfWorkInvoker.java   
@Override
public Object invoke(Exchange exchange, Object o) {

    Object result;
    String methodname = this.getTargetMethod(exchange).getName();

    if (unitOfWorkMethods.containsKey(methodname)) {

        final Session session = sessionFactory.openSession();
        UnitOfWork unitOfWork = unitOfWorkMethods.get(methodname);

        try {
            configureSession(session, unitOfWork);
            ManagedSessionContext.bind(session);
            beginTransaction(session, unitOfWork);
            try {
                result = underlying.invoke(exchange, o);
                commitTransaction(session, unitOfWork);
                return result;
            } catch (Exception e) {
                rollbackTransaction(session, unitOfWork);
                this.<RuntimeException>rethrow(e); // unchecked rethrow
                return null; // avoid compiler warning
            }
        } finally {
            session.close();
            ManagedSessionContext.unbind(sessionFactory);
        }
    }
    else {
        return underlying.invoke(exchange, o);
    }
}
项目:dropwizard-routing    文件:RoutingUnitOfWorkApplicationListenerTest.java   
@Test
public void bindsAndUnbindsTheSessionToTheManagedContext() throws Exception {
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertThat(ManagedSessionContext.hasBind(sessionFactory)).isTrue();
            return null;
        }
    }).when(session).beginTransaction();

    execute();

    assertThat(ManagedSessionContext.hasBind(sessionFactory)).isFalse();
}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkAspect.java   
public void beforeStart(final UnitOfWork unitOfWork) {
    if (unitOfWork == null) {
        return;
    }
    this.unitOfWork = unitOfWork;

    this.bundle = this.bundles.get(unitOfWork.value());
    if (this.bundle == null) {
        // If the user didn't specify the name of a session factory,
        // and we have only one registered, we can assume that it's the
        // right one.
        if (unitOfWork.value().equals(RemoteCredentialHibernateBundle.DEFAULT_NAME)
                && this.bundles.size() == 1) {
            this.bundle = this.bundles.values().iterator().next();
        } else {
            throw new IllegalArgumentException(
                    "Unregistered Hibernate bundle: '" + unitOfWork.value() + "'");
        }
    }
    this.sessionHolders = this.bundle.getSessionHolders();
    this.sessionHolders.add(this);

    // We need to get the current session factory.
    this.sessionFactory = this.bundle.getSessionFactory();
    // Now that we have the session factory we set it in a thread local so
    // it's used by the BundleAbstractDAO.
    this.bundle.setCurrentThreadSessionFactory(this.sessionFactory);

    this.session = this.sessionFactory.openSession();
    try {
        this.configureSession();
        ManagedSessionContext.bind(this.session);
        this.beginTransaction();
    } catch (final Throwable th) {
        this.session.close();
        this.session = null;
        ManagedSessionContext.unbind(this.sessionFactory);
        this.sessionHolders.remove(this);
        throw th;
    }
}
项目:amos-ss15-proj2    文件:CroudTripApplication.java   
@Override
public void run(CroudTripConfig configuration, Environment environment) throws Exception {
    Injector injector = Guice.createInjector(
            new DbModule(hibernateBundle.getSessionFactory()),
               new DirectionsModule(configuration),
            new GcmModule(configuration.getGoogleAPIKey()),
            new TripsModule(),
            new PlacesModule( configuration ));

    // start managed instances (manually since deployment via WAR file does not seem to work)
    injector.getInstance(TripReservationGarbageCollectionExecutor.class).start();
    injector.getInstance(RunningTripQueryGarbageCollectionExecutor.class).start();
    injector.getInstance(DisableTripOffersExecutor.class).start();
       injector.getInstance(ExpireTripOffersExecutor.class).start();
    injector.getInstance(ExpireJoinTripRequestsExecutor.class).start();

    // setup REST api
       environment.jersey().register(injector.getInstance(UsersResource.class));
    environment.jersey().register(injector.getInstance(UsersHeadResource.class));
    environment.jersey().register(injector.getInstance(AvatarsResource.class));
    environment.jersey().register(injector.getInstance(TripsResource.class));
    environment.jersey().register(injector.getInstance(VehicleResource.class));
    environment.jersey().register(injector.getInstance(GcmRegistrationResource.class));
    environment.jersey().register(injector.getInstance(LogsResource.class));
    environment.jersey().register(injector.getInstance(NotFoundExceptionMapper.class));
    environment.jersey().register(injector.getInstance(JsonExceptionMapper.class));
    environment.jersey().register(injector.getInstance(RouteNotFoundExceptionMapper.class));
    environment.jersey().register(injector.getInstance(ThrowableExceptionMapper.class));
    environment.jersey().register(AuthFactory.binder(new BasicAuthFactory<>(
            injector.getInstance(BasicAuthenticator.class),
            "all secret",
            User.class)));

    // register a set of "default" users
    SessionFactory sessionFactory = injector.getInstance(SessionFactory.class);
    UserManager userManager = injector.getInstance(UserManager.class);

    Session session = null;
    try {
        session = sessionFactory.openSession();
        ManagedSessionContext.bind(session);
        for (UserDescription user : configuration.getUsers()) {
            if (!userManager.findUserByEmail(user.getEmail()).isPresent()) {
                userManager.addUser(user);
            }
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (session != null) {
            session.flush();
            session.close();
        }
    }
}
项目:robe    文件:Transaction.java   
/**
 * Opens a new session, sets flush mode and bind this session to {@link ManagedSessionContext}
 */
private void configureNewSession() {
    session = SESSION_FACTORY.openSession();
    session.setFlushMode(flushMode);
    ManagedSessionContext.bind(session);
}
项目:jooby    文件:RootUnitOfWork.java   
protected void bind(final Session session) {
  log.debug("session bound: {}", oid(session));
  ManagedSessionContext.bind(session);
}