List of usage examples for org.hibernate.context.internal ManagedSessionContext bind
public static Session bind(Session session)
From source file:beans.TransacaoSistemaBiblioteca.java
public void iniciarRequisicao() { ManagedSessionContext.bind(sessaoHibernate); if (!sessaoHibernate.getTransaction().isActive()) sessaoHibernate.beginTransaction(); }
From source file:br.eb.ime.pfc.filters.AuthenticationFilter.java
License:Open Source License
protected boolean authenticateUser(HttpServletRequest request, HttpServletResponse response, String username, String password) {/*from www.j a va2s .c o m*/ SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); final Session session = sessionFactory.openSession(); session.beginTransaction(); ManagedSessionContext.bind(session); final UserManager userManager = new UserManager(session); if (username.equals("")) {//cannot be empty return false; } String passwordDB = null; Set<String> layersIds = new HashSet<>(); try { final User user = userManager.getById(username); for (Layer layer : user.getAccessLevel().getLayers()) { layersIds.add(layer.getWmsId()); } passwordDB = user.getPassword(); session.getTransaction().commit(); } catch (HibernateException | ObjectNotFoundException e) { session.getTransaction().rollback(); } finally { session.close(); } if (passwordDB != null && passwordDB.equals(password)) { //CACHE LAYERS request.getSession().setAttribute("user", username); request.getSession().setAttribute("layers", layersIds); return true; } else { return false; } }
From source file:br.eb.ime.pfc.filters.HibernateSessionRequestFilter.java
License:Open Source License
private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (debug) {/*ww w. ja va 2 s . c o m*/ log("TransactionHandlerFilter:DoBeforeProcessing"); } SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); this.session = sessionFactory.openSession(); this.session.beginTransaction(); ManagedSessionContext.bind(session); }
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 {// w w w .j a v a 2 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;//ww w . j a v a 2 s.c om 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;// w ww .j a v a2s.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 www. j av a 2 s.c o m*/ 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;/* w w w. ja v a 2 s. c om*/ 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 ww w .ja v a 2 s . c o m 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 {/* ww w . j av a2 s . com*/ 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(); } } }