Example usage for org.hibernate SessionFactory getCurrentSession

List of usage examples for org.hibernate SessionFactory getCurrentSession

Introduction

In this page you can find the example usage for org.hibernate SessionFactory getCurrentSession.

Prototype

Session getCurrentSession() throws HibernateException;

Source Link

Document

Obtains the current session.

Usage

From source file:my.dao.HibernateUtil.java

public static Session getSession(SessionFactory sessionFactory) {
    Session session = null;/*from  w  w w . j  a  v a2  s .  com*/
    try {
        session = sessionFactory.getCurrentSession();
    } catch (HibernateException hex) {
        hex.printStackTrace();
    }
    if (session == null && session.isOpen()) {
        session = sessionFactory.openSession();
    }
    return session;
}

From source file:net.lizalab.util.jasypt.h4.ext.connectionprovider.EncryptedConnectionProviderImplIT.java

License:Apache License

private void doTest(Configuration configuration) {
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    // Try to initialize session factory. Since we have db entity creation
    // configured it should happen here.
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    // Test that we have a non-null session factory.
    assertNotNull("Expected a non-null session factory!", sessionFactory);
    // For some reason db entity creation errors don't get propagated so
    // we are still not guaranteed to be up and running, so lets do a 
    // simple test transaction to confirm everything worked and we are
    // indeed connected to the database.
    Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();//from  w  w  w  .  j av  a  2  s . c  o m
    try {
        TestEntity testEntity = new TestEntity(
                "Encrypted c3p0 connection provider implementation Integration Test.");
        session.persist(testEntity);
        session.getTransaction().commit();
    } finally {
        try {
            session.getTransaction().rollback();
        } catch (Exception e) {
        }
    }
}

From source file:openones.oopms.dms.dao.BaseDao.java

License:Apache License

public BaseDao() {

    SessionFactory factory = HibernateUtil.getSessionFactory();
    this.session = factory.getCurrentSession();
}

From source file:openones.oopms.requirement.dao.AssignmentDao.java

License:Apache License

public AssignmentDao() {
    SessionFactory factory = HibernateUtil.getSessionFactory();
    this.session = factory.getCurrentSession();
}

From source file:openones.oopms.requirement.dao.DeveloperDao.java

License:Apache License

public DeveloperDao() {
    SessionFactory factory = HibernateUtil.getSessionFactory();
    this.session = factory.getCurrentSession();
}

From source file:org.cgiar.ccafs.marlo.utils.SendEmails.java

License:Open Source License

public static void main(String[] args) {

    users = new ArrayList<>();
    usersEmail = new ArrayList<>();
    ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
    SessionFactory sessionFactory = ctx.getBean(SessionFactory.class);
    sessionFactory.getCurrentSession().beginTransaction();
    userDAO = ctx.getBean(UserDAO.class);
    roleDAO = ctx.getBean(RoleDAO.class);
    dao = ctx.getBean(ProjectDAO.class);
    sendMail = ctx.getBean(SendMailS.class);
    action = ctx.getBean(ReportingSummaryAction.class);
    validateProjectSectionAction = ctx.getBean(ValidateProjectSectionAction.class);
    projectLeaderEditAction = ctx.getBean(ProjectLeaderEditAction.class);
    globalUnitManager = ctx.getBean(GlobalUnitManager.class);
    globalUnitProjectManager = ctx.getBean(GlobalUnitProjectManager.class);
    action.setUsersToActive(new ArrayList<Map<String, Object>>());
    AuditLogContextProvider.push(new AuditLogContext());
    List<Map<String, Object>> list = userDAO.findCustomQuery(
            " select p.id from  projects p  inner join global_unit_projects gp on gp.project_id=p.id where p.id_consolidado is not null  and gp.global_unit_id=21  and p.id>880; ");
    action.setSession(new HashMap<>());
    action.loadProvider(action.getSession());
    action.getSession().put(APConstants.CRP_ADMIN_ROLE, "83");
    action.getSession().put(APConstants.CRP_EMAIL_CC_FL_FM_CL, true);
    action.getSession().put(APConstants.CRP_PMU_ROLE, "84");
    action.getSession().put(APConstants.CRP_PL_ROLE, "91");
    action.getSession().put(APConstants.CRP_PL_ROLE, "91");
    action.getSession().put(APConstants.CRP_LESSONS_ACTIVE, true);
    action.setPhaseID(new Long(7));
    List<Phase> phases = globalUnitManager.getGlobalUnitById(21L).getPhases().stream().filter(c -> c.isActive())
            .collect(Collectors.toList());
    phases.sort((p1, p2) -> p1.getStartDate().compareTo(p2.getStartDate()));
    Map<Long, Phase> allPhasesMap = new HashMap<>();
    for (Phase phase : phases) {
        allPhasesMap.put(phase.getId(), phase);
    }//  w  ww . j  a  v  a  2s  .  c  o m
    action.getSession().put(APConstants.ALL_PHASES, allPhasesMap);
    Long plRoleID = Long.parseLong((String) action.getSession().get(APConstants.CRP_PL_ROLE));
    Role plRole = roleDAO.find(plRoleID);
    for (Map<String, Object> map : list) {
        Long id = Long.parseLong(map.get("id").toString());
        Project project = dao.find(id);
        for (ProjectPartner projectPartner : project.getProjectPartners().stream().filter(
                c -> c.isActive() && c.getPhase().getId().longValue() == action.getPhaseID().longValue())
                .collect(Collectors.toList())) {
            for (ProjectPartnerPerson projectPartnerPerson : projectPartner.getProjectPartnerPersons().stream()
                    .filter(c -> c.isActive()).collect(Collectors.toList())) {
                if (projectPartnerPerson.getContactType().equals("PL")) {
                    if (!usersEmail.contains(projectPartnerPerson.getUser().getEmail())) {
                        notifyNewUserCreated(projectPartnerPerson.getUser());
                    }
                    notifyRoleAssigned(projectPartnerPerson.getUser(), plRole, project,
                            globalUnitProjectManager.findByProjectId(project.getId()).getGlobalUnit());
                }
            }
        }
        for (Phase phase : phases) {
            if (phase.getYear() == 2017 || phase.getYear() == 2018) {
                System.out.println("VALIDATE PROJECT " + project.getId());
                validateProjectSectionAction.setProjectID(project.getId());
                validateProjectSectionAction.setSession(action.getSession());
                validateProjectSectionAction.setValidSection(true);
                validateProjectSectionAction.setExistProject(true);
                validateProjectSectionAction.setInvalidFields(new HashMap<>());
                validateProjectSectionAction.setValidationMessage(new StringBuilder());
                validateProjectSectionAction.loadProvider(action.getSession());
                validateProjectSectionAction.setPhaseID(phase.getId());
                validateProjectSectionAction.setCrpID(
                        globalUnitProjectManager.findByProjectId(project.getId()).getGlobalUnit().getId());
                validateProjectSectionAction.setMissingFields(new StringBuilder());
                validateProjectSectionAction.setSectionName(ProjectSectionStatusEnum.DESCRIPTION.getStatus());
                try {
                    validateProjectSectionAction.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                validateProjectSectionAction.setMissingFields(new StringBuilder());
                validateProjectSectionAction.setSectionName(ProjectSectionStatusEnum.PARTNERS.getStatus());
                try {
                    validateProjectSectionAction.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                validateProjectSectionAction.setMissingFields(new StringBuilder());
                validateProjectSectionAction.setSectionName(ProjectSectionStatusEnum.BUDGET.getStatus());
                try {
                    validateProjectSectionAction.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                projectLeaderEditAction.setProjectId(project.getId());
                projectLeaderEditAction.setProjectStatus(true);
                projectLeaderEditAction.setSession(action.getSession());
                projectLeaderEditAction.setInvalidFields(new HashMap<>());
                projectLeaderEditAction.setValidationMessage(new StringBuilder());
                projectLeaderEditAction.loadProvider(action.getSession());
                projectLeaderEditAction.setPhaseID(phase.getId());
                projectLeaderEditAction.setCrpID(
                        globalUnitProjectManager.findByProjectId(project.getId()).getGlobalUnit().getId());
                projectLeaderEditAction.setMissingFields(new StringBuilder());
                try {
                    if (projectLeaderEditAction.isCompletePreProject(project.getId())) {
                        projectLeaderEditAction.execute();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    list = userDAO.findCustomQuery(
            " select p.id from  projects p  inner join global_unit_projects gp on gp.project_id=p.id where p.id_consolidado is not null  and gp.global_unit_id=22  ; ");
    action.setSession(new HashMap<>());
    action.loadProvider(action.getSession());
    action.getSession().put(APConstants.CRP_ADMIN_ROLE, "98");
    action.getSession().put(APConstants.CRP_EMAIL_CC_FL_FM_CL, true);
    action.getSession().put(APConstants.CRP_PMU_ROLE, "99");
    action.getSession().put(APConstants.CRP_PL_ROLE, "106");
    action.setPhaseID(new Long(8));
    action.getSession().put(APConstants.CRP_LESSONS_ACTIVE, true);
    phases = globalUnitManager.getGlobalUnitById(22L).getPhases().stream().filter(c -> c.isActive())
            .collect(Collectors.toList());
    phases.sort((p1, p2) -> p1.getStartDate().compareTo(p2.getStartDate()));
    allPhasesMap = new HashMap<>();
    for (Phase phase : phases) {
        allPhasesMap.put(phase.getId(), phase);
    }
    action.getSession().put(APConstants.ALL_PHASES, allPhasesMap);
    plRoleID = Long.parseLong((String) action.getSession().get(APConstants.CRP_PL_ROLE));
    plRole = roleDAO.find(plRoleID);
    for (Map<String, Object> map : list) {
        Long id = Long.parseLong(map.get("id").toString());
        Project project = dao.find(id);
        for (ProjectPartner projectPartner : project.getProjectPartners().stream().filter(
                c -> c.isActive() && c.getPhase().getId().longValue() == action.getPhaseID().longValue())
                .collect(Collectors.toList())) {
            for (ProjectPartnerPerson projectPartnerPerson : projectPartner.getProjectPartnerPersons().stream()
                    .filter(c -> c.isActive()).collect(Collectors.toList())) {
                if (projectPartnerPerson.getContactType().equals("PL")) {
                    if (!usersEmail.contains(projectPartnerPerson.getUser().getEmail())) {
                        notifyNewUserCreated(projectPartnerPerson.getUser());
                    }
                    notifyRoleAssigned(projectPartnerPerson.getUser(), plRole, project,
                            globalUnitProjectManager.findByProjectId(project.getId()).getGlobalUnit());
                }
            }
        }
        for (Phase phase : phases) {
            if (phase.getYear() == 2017
                    || phase.getYear() == 2018 && phase.getDescription().equals("Planning")) {
                System.out.println("VALIDATE PROJECT " + project.getId());
                validateProjectSectionAction.setProjectID(project.getId());
                validateProjectSectionAction.setSession(action.getSession());
                validateProjectSectionAction.setValidSection(true);
                validateProjectSectionAction.setExistProject(true);
                validateProjectSectionAction.setInvalidFields(new HashMap<>());
                validateProjectSectionAction.setValidationMessage(new StringBuilder());
                validateProjectSectionAction.loadProvider(action.getSession());
                validateProjectSectionAction.setPhaseID(phase.getId());
                validateProjectSectionAction.setCrpID(
                        globalUnitProjectManager.findByProjectId(project.getId()).getGlobalUnit().getId());
                validateProjectSectionAction.setMissingFields(new StringBuilder());
                validateProjectSectionAction.setSectionName(ProjectSectionStatusEnum.DESCRIPTION.getStatus());
                try {
                    validateProjectSectionAction.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                validateProjectSectionAction.setMissingFields(new StringBuilder());
                validateProjectSectionAction.setSectionName(ProjectSectionStatusEnum.PARTNERS.getStatus());
                try {
                    validateProjectSectionAction.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                validateProjectSectionAction.setMissingFields(new StringBuilder());
                validateProjectSectionAction.setSectionName(ProjectSectionStatusEnum.BUDGET.getStatus());
                try {
                    validateProjectSectionAction.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    action.addUsers();
    sessionFactory.getCurrentSession().getTransaction().commit();

}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * Sets the target object to read-only using the given SessionFactory instance. This
 * avoids Hibernate performing any dirty checking on the object
 *
 * @see #setObjectToReadWrite(Object, org.hibernate.SessionFactory)
 *
 * @param target The target object//  w  w  w.  ja v a 2s .  c o  m
 * @param sessionFactory The SessionFactory instance
 */
public static void setObjectToReadyOnly(Object target, SessionFactory sessionFactory) {
    Session session = sessionFactory.getCurrentSession();
    if (canModifyReadWriteState(session, target)) {
        if (target instanceof HibernateProxy) {
            target = ((HibernateProxy) target).getHibernateLazyInitializer().getImplementation();
        }
        session.setReadOnly(target, true);
        session.setFlushMode(FlushMode.MANUAL);
    }
}

From source file:org.directwebremoting.hibernate.H3SessionAjaxFilter.java

License:Apache License

public Object doFilter(Object object, Method method, Object[] params, AjaxFilterChain chain) throws Exception {
    ServletContext context = WebContextFactory.get().getServletContext();
    SessionFactory sessionFactory = (SessionFactory) context.getAttribute(ATTRIBUTE_SESSION);

    Transaction transaction = null;/*from  ww  w .j av  a 2s  .  c om*/
    if (sessionFactory != null) {
        Session session = sessionFactory.getCurrentSession();
        transaction = session.beginTransaction();
    } else {
        log.error(
                "SessionFactory not initialized for this web application. Use: H3SessionAjaxFilter.setSessionFactory(servletContext, sessionFactory);");
    }

    Object reply = chain.doFilter(object, method, params);

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

    return reply;
}

From source file:org.directwebremoting.hibernate.H3SessionAjaxFilter.java

License:Apache License

/**
 * Get access to a Session, given the {@link SessionFactory} linked in
 * {@link #setSessionFactory(ServletContext, SessionFactory)}
 * @param context The webapp to link the calls together
 * @return A Session from the {@link SessionFactory} or null if
 * {@link #setSessionFactory(ServletContext, SessionFactory)} has not been
 * called for this {@link ServletContext}
 *//*from   w w  w.  j a v  a2  s  .co m*/
public static Session getCurrentSession(ServletContext context) {
    SessionFactory sessionFactory = (SessionFactory) context.getAttribute(ATTRIBUTE_SESSION);
    if (sessionFactory == null) {
        return null;
    }

    return sessionFactory.getCurrentSession();
}

From source file:org.directwebremoting.hibernate.H4SessionAjaxFilter.java

License:Apache License

public Object doFilter(Object object, Method method, Object[] params, AjaxFilterChain chain) throws Exception {
    ServletContext context = WebContextFactory.get().getServletContext();
    SessionFactory sessionFactory = (SessionFactory) context.getAttribute(ATTRIBUTE_SESSION);

    Transaction transaction = null;//from   w w  w .j a v a  2s.  c o  m
    if (sessionFactory != null) {
        Session session = sessionFactory.getCurrentSession();
        transaction = session.beginTransaction();
    } else {
        log.error(
                "SessionFactory not initialized for this web application. Use: H4SessionAjaxFilter.setSessionFactory(servletContext, sessionFactory);");
    }

    Object reply = chain.doFilter(object, method, params);

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

    return reply;
}