Example usage for org.hibernate.context.internal ManagedSessionContext unbind

List of usage examples for org.hibernate.context.internal ManagedSessionContext unbind

Introduction

In this page you can find the example usage for org.hibernate.context.internal ManagedSessionContext unbind.

Prototype

public static Session unbind(SessionFactory factory) 

Source Link

Document

Unbinds the session (if one) current associated with the context for the given session.

Usage

From source file:beans.TransacaoSistemaBiblioteca.java

public void finalizarRequisicao() {
    if (sessaoHibernate.isOpen() && sessaoHibernate.getTransaction().isActive())
        sessaoHibernate.getTransaction().commit();
    ManagedSessionContext.unbind(HibernateUtil.getSessionFactory());
}

From source file:br.eb.ime.pfc.filters.HibernateSessionRequestFilter.java

License:Open Source License

private void doAfterProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
    if (debug) {//from ww  w . j  a  v a  2  s .  co m
        log("TransactionHandlerFilter:DoAfterProcessing");
    }
    ManagedSessionContext.unbind(this.session.getSessionFactory());
    this.session.flush();
    try {
        this.session.getTransaction().commit();
    } catch (HibernateException e) {
        this.session.getTransaction().rollback();
    } finally {
        this.session.close();
    }
}

From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkRequestDispatcher.java

License:Apache License

@Override
public void dispatch(Object resource, HttpContext context) {
    final Session session = route().openSession();
    try {//from  ww w .ja  v a2 s  .  c  o m
        configureSession(session);
        ManagedSessionContext.bind(session);
        beginTransaction(session);
        try {
            dispatcher.dispatch(resource, context);
            commitTransaction(session);
        } catch (Exception e) {
            rollbackTransaction(session);
            this.<RuntimeException>rethrow(e);
        }
    } finally {
        session.close();
        ManagedSessionContext.unbind(route());
    }
}

From source file:com.cgi.poc.dw.api.service.impl.EventFloodAPICallerServiceImpl.java

public void mapAndSave(JsonNode eventJson, JsonNode geoJson) {
    ObjectMapper mapper = new ObjectMapper();
    EventFlood retEvent;//www .java 2 s .  c  o  m

    Session session = sessionFactory.openSession();
    try {
        EventFlood event = mapper.readValue(eventJson.toString(), EventFlood.class);

        event.setGeometry(geoJson.toString());
        ManagedSessionContext.bind(session);

        Transaction transaction = session.beginTransaction();
        EventFlood eventFromDB = eventDAO.selectForUpdate(event);
        boolean isNewEvent = false;
        try {
            event.setLastModified(eventFromDB.getLastModified());
        } catch (Exception ex) {
            LOG.info("Event is new");
            // row doesn't exist it's new... nothing wrong..
            // just ignore the exectoion
            isNewEvent = true;
        }
        LOG.info("Event to save : {}", event.toString());
        // Archive users based on last login date
        retEvent = eventDAO.save(event);
        transaction.commit();
        // for flood events.. only new entries will be processed.
        if (isNewEvent) {
            LOG.info("Event for notifications");

            GeoCoordinates geo = new GeoCoordinates();
            geo.setLatitude(event.getLatitude().doubleValue());
            geo.setLongitude(event.getLongitude().doubleValue());

            List<User> users = userDao.getGeoWithinRadius(Arrays.asList(geo), 15.00);

            EventNotification eventNotification = new EventNotification();
            // <waterbody> near <location>
            eventNotification.setTitle(event.getWaterbody() + " near " + event.getLocation());
            eventNotification.setType("Flood");
            eventNotification.setCitizensAffected(users.size());
            eventNotification.setDescription(
                    "Emergency alert: " + eventNotification.getType() + " - " + eventNotification.getTitle()
                            + ". Please log in at https://mycalerts.com/ for more information.");
            eventNotification.setGenerationDate(new Date());
            eventNotification.setGeometry(event.getGeometry());
            eventNotification.setUrl1(event.getUrl());
            eventNotification.setType("Flood");
            eventNotification.setUserId(userDao.getAdminUser());

            if (users.size() > 0) {

                LOG.info("Send notifications to : {}", users.toString());
                for (User user : users) {
                    EventNotificationUser currENUser = new EventNotificationUser();
                    currENUser.setUserId(user);
                    eventNotification.addNotifiedUser(currENUser);

                    if (user.getSmsNotification()) {
                        textMessageService.send(user.getPhone(), eventNotification.getDescription());
                    }
                    if (user.getEmailNotification()) {
                        emailService.send(
                                null, Arrays.asList(user.getEmail()), "Emergency alert from MyCAlerts: "
                                        + eventNotification.getType() + " - " + eventNotification.getTitle(),
                                eventNotification.getDescription());
                    }
                }
            }
            eventNotificationDAO.save(eventNotification);
        }
    } catch (IOException ex) {
        LOG.error("Unable to parse the result for the flood event : error: {}", ex.getMessage());
    } finally {
        session.close();
        ManagedSessionContext.unbind(sessionFactory);
    }
}

From source file:com.cgi.poc.dw.api.service.impl.EventWeatherAPICallerServiceImpl.java

public void mapAndSave(JsonNode eventJson, JsonNode geoJson) {
    ObjectMapper mapper = new ObjectMapper();
    EventWeather retEvent;/*from w  w  w. j a va  2s  . c o m*/

    Session session = sessionFactory.openSession();
    try {
        EventWeather event = mapper.readValue(eventJson.toString(), EventWeather.class);

        event.setGeometry(geoJson.toString());
        ManagedSessionContext.bind(session);

        Transaction transaction = session.beginTransaction();
        EventWeather eventFromDB = eventDAO.selectForUpdate(event);
        boolean isNewEvent = false;
        try {
            event.setLastModified(eventFromDB.getLastModified());
        } catch (Exception ex) {
            LOG.info("Event is new");
            // row doesn't exist it's new... nothing wrong..
            // just ignore the exectoion
            isNewEvent = true;
        }
        LOG.info("Event to save : {}", event.toString());
        // Archive users based on last login date
        retEvent = eventDAO.update(event);
        transaction.commit();

        if (isNewEvent || isChangedEvent(retEvent, eventFromDB)) {
            LOG.info("Event for notifications");

            List<User> users = userDao.getGeoWithinRadius(geoJson, 15.00);

            EventNotification eventNotification = new EventNotification();
            // prod type for the title
            eventNotification.setTitle(event.getProdType());
            eventNotification.setType("Weather");
            eventNotification.setCitizensAffected(users.size());
            eventNotification.setDescription(
                    "Emergency alert: " + eventNotification.getType() + " - " + eventNotification.getTitle()
                            + ". Please log in at https://mycalerts.com/ for more information.");
            eventNotification.setGenerationDate(new Date());
            eventNotification.setGeometry(event.getGeometry());
            eventNotification.setUrl1(event.getUrl());
            eventNotification.setUserId(userDao.getAdminUser());

            if (users.size() > 0) {

                LOG.info("Send notifications to : {}", users.toString());
                for (User user : users) {
                    EventNotificationUser currENUser = new EventNotificationUser();
                    currENUser.setUserId(user);
                    eventNotification.addNotifiedUser(currENUser);

                    if (user.getSmsNotification()) {
                        textMessageService.send(user.getPhone(), eventNotification.getDescription());
                    }
                    if (user.getEmailNotification()) {
                        emailService.send(
                                null, Arrays.asList(user.getEmail()), "Emergency alert from MyCAlerts: "
                                        + eventNotification.getType() + " - " + eventNotification.getTitle(),
                                eventNotification.getDescription());
                    }
                }
            }
            eventNotificationDAO.save(eventNotification);
        }
    } catch (IOException ex) {
        LOG.error("Unable to parse the result for the weather event : error: {}", ex.getMessage());
    } finally {
        session.close();
        ManagedSessionContext.unbind(sessionFactory);
    }

}

From source file:com.cgi.poc.dw.api.service.impl.FireEventAPICallerServiceImpl.java

public void mapAndSave(JsonNode eventJson, JsonNode geoJson) {
    ObjectMapper mapper = new ObjectMapper();
    FireEvent retEvent;/*from   ww w. jav  a 2  s .com*/

    Session session = sessionFactory.openSession();
    try {
        FireEvent event = mapper.readValue(eventJson.toString(), FireEvent.class);

        event.setGeometry(geoJson.toString());
        ManagedSessionContext.bind(session);

        Transaction transaction = session.beginTransaction();
        FireEvent eventFromDB = eventDAO.selectForUpdate(event);
        boolean isNewEvent = false;
        try {
            event.setLastModified(eventFromDB.getLastModified());
            //this is to protect from the Hibernate ObjectNotFoundException when the eventFromDB is a proxy object
        } catch (Exception ex) {
            LOG.info("Event is new");
            // row doesn't exist it's new... nothing wrong..
            // just ignore the exception
            isNewEvent = true;
        }
        LOG.info("Event to save : {}", event.toString());
        // Archive users based on last login date
        retEvent = eventDAO.save(event);
        transaction.commit();

        if (isNewEvent || isChangedEvent(retEvent, eventFromDB)) {
            LOG.info("Event for notifications");

            GeoCoordinates geo = new GeoCoordinates();
            geo.setLatitude(event.getLatitude().doubleValue());
            geo.setLongitude(event.getLongitude().doubleValue());

            List<User> users = userDao.getGeoWithinRadius(Arrays.asList(geo), 15.00);

            EventNotification eventNotification = new EventNotification();
            // <state> - <incident name>
            eventNotification.setTitle(event.getState() + " - " + event.getIncidentname());
            eventNotification.setType("Fire");
            eventNotification.setCitizensAffected(users.size());
            // Emergency alert: ? + Event title + . Please log in at https://mycalerts.com/ for more information.?
            eventNotification.setDescription(
                    "Emergency alert: " + eventNotification.getType() + " - " + eventNotification.getTitle()
                            + ". Please log in at https://mycalerts.com/ for more information.");
            eventNotification.setGenerationDate(new Date());
            eventNotification.setGeometry(event.getGeometry());
            eventNotification.setUrl1(event.getHotlink());
            eventNotification.setUserId(userDao.getAdminUser());

            if (users.size() > 0) {

                LOG.info("Send notifications to : {}", users.toString());
                for (User user : users) {
                    EventNotificationUser currENUser = new EventNotificationUser();
                    currENUser.setUserId(user);
                    eventNotification.addNotifiedUser(currENUser);

                    if (user.getSmsNotification()) {
                        textMessageService.send(user.getPhone(), eventNotification.getDescription());
                    }
                    if (user.getEmailNotification()) {
                        // Emergency alert from MyCAlerts: ? + Event type (camel case)
                        emailService.send(
                                null, Arrays.asList(user.getEmail()), "Emergency alert from MyCAlerts: "
                                        + eventNotification.getType() + " - " + eventNotification.getTitle(),
                                eventNotification.getDescription());
                    }
                }
            }
            eventNotificationDAO.save(eventNotification);
        }
    } catch (IOException ex) {
        LOG.error("Unable to parse the result for the fire event : error: {}", ex.getMessage());
    } finally {
        session.close();
        ManagedSessionContext.unbind(sessionFactory);
    }

}

From source file:com.flipkart.flux.guice.interceptor.TransactionInterceptor.java

License:Apache License

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {

    Transaction transaction = null;//from w  w w .j a  v a 2s .  c  o  m
    Session session = null;
    SessionFactoryContext context = contextProvider.get();

    try {
        SessionFactory currentSessionFactory = context.getSessionFactory();
        if (currentSessionFactory != null) {
            session = currentSessionFactory.getCurrentSession();
        }
    } catch (HibernateException e) {
    }

    if (session == null) {
        //start a new session and transaction if current session is null
        //get DataSourceType first
        SelectDataSource selectedDS = invocation.getMethod().getAnnotation(SelectDataSource.class);
        if (selectedDS == null) {
            context.useDefault();
        } else {
            context.useSessionFactory(selectedDS.value());
        }
        session = context.getSessionFactory().openSession();
        ManagedSessionContext.bind(session);
        transaction = session.getTransaction();
        transaction.begin();
    }

    try {

        Object result = invocation.proceed();

        if (transaction != null) {
            transaction.commit();
        }

        return result;

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        throw e;
    } finally {
        if (transaction != null && session != null) {
            ManagedSessionContext.unbind(context.getSessionFactory());
            session.close();
            context.clear();
        }
    }
}

From source file:com.flipkart.flux.redriver.dao.MessageDaoTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    sessionFactory.useDefault();/*from   w w  w.j  a  v a  2  s. c  om*/
    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();
        }
    }
}

From source file:com.flipkart.flux.rule.DbClearRule.java

License:Apache License

/** 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 {/* w  ww . j  a  v a 2 s. c om*/
        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();
        }
    }
}

From source file:com.javaeeeee.dropbookmarks.auth.DBAuthenticator.java

License:Open Source License

/**
 * Implementation of the authenticate method.
 *
 * @param credentials An instance of the BasicCredentials class containing
 * username and password.//from   www.  j  a v  a 2 s.  c o  m
 * @return An Optional containing the user characterized by credentials or
 * an empty optional otherwise.
 * @throws AuthenticationException throws an exception in the case of
 * authentication problems.
 */
@UnitOfWork
@Override
public final Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
    Session session = sessionFactory.openSession();
    Optional<User> result;
    try {
        ManagedSessionContext.bind(session);

        result = userDAO.findByUsername(credentials.getUsername());

        if (!result.isPresent()) {
            return result;
        } else {
            if (passwordEncryptor.checkPassword(credentials.getPassword(), result.get().getPassword())) {
                return result;
            } else {
                return Optional.empty();
            }
        }

    } catch (Exception e) {
        throw new AuthenticationException(e);
    } finally {
        ManagedSessionContext.unbind(sessionFactory);
        session.close();
    }

}