Example usage for org.hibernate SessionFactory close

List of usage examples for org.hibernate SessionFactory close

Introduction

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

Prototype

void close() throws HibernateException;

Source Link

Document

Destroy this SessionFactory and release all resources (caches, connection pools, etc).

Usage

From source file:com.oncloud6.atd.maintenances.MaintenancesAddServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w w  w .  j a v a  2s  . c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    SessionFactory factory = new HibernateConnector().getSessionFactory();
    Session hibernateSession = factory.openSession();
    Transaction tx = null;
    Integer onderhoudID = null;
    HttpSession session = request.getSession(true);
    RequestDispatcher rd = null;
    if (!RightsControl.checkBoolean("maintenances_add", "true", session)) {
        rd = request.getRequestDispatcher("error/403error.jsp");
        rd.forward(request, response);
        return;
    }
    try {
        tx = hibernateSession.beginTransaction();
        Onderhoud onderhoud = new Onderhoud();
        Auto auto = new Auto();
        hibernateSession.load(auto, Integer.parseInt(request.getParameter("auto")));
        onderhoud.setAuto(auto);

        Date date = new SimpleDateFormat("dd-MM-yyyy").parse(request.getParameter("datum"));

        onderhoud.setDatum(date);
        onderhoud.setStatus("added");
        onderhoud.setBeschrijving(request.getParameter("beschrijving"));
        onderhoudID = (Integer) hibernateSession.save(onderhoud);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    } catch (ParseException ex) {
        Logger.getLogger(MaintenancesAddServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        hibernateSession.close();
        factory.close();
    }

    rd = request.getRequestDispatcher("maintenances/add.jsp");

    rd.forward(request, response);

}

From source file:com.oncloud6.atd.schedules.SchedulesAddServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w ww  .j  a v a  2  s  .c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    RequestDispatcher rd = null;
    if (!RightsControl.checkBoolean("schedules_add", "true", session)) {
        rd = request.getRequestDispatcher("error/403error.jsp");
        rd.forward(request, response);
        return;
    }
    SessionFactory factory = new HibernateConnector().getSessionFactory();
    Session hibernateSession = factory.openSession();
    Transaction tx = null;
    Integer planningID = null;
    try {
        tx = hibernateSession.beginTransaction();
        Planning planning = new Planning();
        Onderhoud onderhoud = new Onderhoud();
        hibernateSession.load(onderhoud, Integer.parseInt(request.getParameter("onderhoud")));
        planning.setOnderhoud(onderhoud);

        Monteur monteur = new Monteur();
        hibernateSession.load(monteur, Integer.parseInt(request.getParameter("monteur")));
        planning.setMonteur(monteur);

        Date dateStart = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(request.getParameter("datum_start"));
        Date dateEinde = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(request.getParameter("datum_einde"));

        planning.setDatumStart(dateStart);
        planning.setDatumEind(dateEinde);

        planningID = (Integer) hibernateSession.save(planning);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    } catch (ParseException ex) {
        Logger.getLogger(SchedulesAddServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        hibernateSession.close();
        factory.close();
    }

    doGet(request, response);

}

From source file:com.persistent.cloudninja.dao.impl.TaskCompletionDaoImpl.java

License:Apache License

/**
 * Method retrieves the list for completed tasks
 * //from  w w  w  . j a  v a 2s. c  om
 * @returns List : TaskCompletion
 **/
@SuppressWarnings("unchecked")
@Override
public List<TaskCompletion> getTaskCompletionList() {
    LOGGER.info("Start of TaskCompletionDaoImpl : getTaskCompletionList ");
    List<TaskCompletion> list = null;
    SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
        org.hibernate.Query query = session.createQuery("from TaskCompletion order by CompletionTime desc");
        query.setFirstResult(0);
        query.setMaxResults(500);
        list = query.list();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        try {
            sessionFactory.close();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    LOGGER.info("End of TaskCompletionDaoImpl : getTaskCompletionList ");
    return list;
}

From source file:com.persistent.cloudninja.dao.impl.TaskListDaoImpl.java

License:Apache License

/**
 * Gets tenant task list.//from   w  w  w .  ja  v  a 2 s  .c om
 * @param tenantDb is the tenant specific database name
 * @return list of TaskList that is Tenant task list
 * @throws SystemException 
 */
@SuppressWarnings("unchecked")
public List<TaskList> getTaskList(String tenantDb) throws SystemException {

    Session session = null;
    SessionFactory sessionfactory = null;
    List<TaskList> list = null;
    try {
        sessionfactory = sessionFactoryConfigurer.createSessionFactoryForTenant(tenantDb);
        session = sessionfactory.openSession();
        session.beginTransaction();

        try {
            Query query = session.createQuery("from TaskList");
            list = query.list();
            session.getTransaction().commit();
        } catch (DataAccessException exception) {
            LOGGER.error(exception);
            throw new SystemException(exception);
        }

    } catch (DataAccessException exception) {
        LOGGER.error(exception);
        throw new SystemException(exception);
    } finally {

        try {
            if (session != null) {
                session.close();
            }
        } catch (DataAccessException exception) {
            LOGGER.error(exception);
            throw new SystemException(exception);
        }
        try {
            sessionfactory.close();
        } catch (DataAccessException exception) {
            LOGGER.error(exception);
            throw new SystemException(exception);
        }

    }
    return list;
}

From source file:com.persistent.cloudninja.dao.impl.TaskListDaoImpl.java

License:Apache License

@Override
public void createList(TaskList taskList, String tenantDb) throws SystemException {

    Session session = null;//  www  .  j  a  v a  2  s.c  om
    SessionFactory sessionfactory = null;
    try {
        sessionfactory = sessionFactoryConfigurer.createSessionFactoryForTenant(tenantDb);
        session = sessionfactory.openSession();
        session.beginTransaction();
        session.saveOrUpdate(taskList);
        session.getTransaction().commit();
    } catch (DataAccessException exception) {
        LOGGER.error(exception);
        throw new SystemException(exception);
    } finally {

        try {
            if (session != null) {
                session.close();
            }
        } catch (DataAccessException exception) {
            LOGGER.error(exception);
            throw new SystemException(exception);
        }

        try {
            sessionfactory.close();
        } catch (DataAccessException exception) {
            LOGGER.error(exception);
            throw new SystemException(exception);
        }

    }

}

From source file:com.persistent.cloudninja.dao.impl.TaskListDaoImpl.java

License:Apache License

@Override
public void deleteTaskList(TaskList taskList, String tenantDb) throws SystemException {

    Session session = null;/*from w  w  w  .  j a v  a 2  s  .  c o  m*/
    SessionFactory sessionfactory = null;
    try {
        sessionfactory = sessionFactoryConfigurer.createSessionFactoryForTenant(tenantDb);
        session = sessionfactory.openSession();
        session.beginTransaction();
        session.delete(taskList);
        session.getTransaction().commit();
    } catch (DataAccessException exception) {
        LOGGER.error(exception);
        throw new SystemException(exception);
    }

    finally {

        try {
            if (session != null) {
                session.close();
            }
        } catch (DataAccessException exception) {
            LOGGER.error(exception);
            throw new SystemException(exception);
        }

        try {
            sessionfactory.close();
        } catch (DataAccessException exception) {
            LOGGER.error(exception);
            throw new SystemException(exception);
        }

    }
}

From source file:com.pfm.personalfinancemanagergrid.mainClasses.DataGridDataManager.java

public String getData() {
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();
    try {/*from w  w w .  j a  v  a  2 s  . c  o  m*/

        Class<?> cls = Class.forName(cache.getEntity());
        Table table = cls.getAnnotation(javax.persistence.Table.class);
        char firstLetter = cache.getEntity().charAt(0);
        Query query = this.buildQuery(session, params, false);
        Query q = this.buildQuery(session, params, true);
        List<Serializable> allResults = query.list();
        List<Serializable> resultList = q.list();
        List<List<String>> resultArray = new ArrayList<>();
        for (Serializable serializable : resultList) {
            Field[] fields = cls.getDeclaredFields();
            List<String> innerResult = new ArrayList<>();
            for (GridCacheColumnObject column : cache.getColumns()) {
                if (!column.isOptionsColumn()) {
                    for (Field field : fields) {
                        field.setAccessible(true);
                        String cachedFieldName = column.getColumnName();
                        String rootEntityField;
                        if (cachedFieldName.contains(".")) {
                            String[] innerObjects = cachedFieldName.split("\\.");
                            rootEntityField = innerObjects[0];
                        } else {
                            rootEntityField = cachedFieldName;
                        }
                        if (!field.getName().equals(rootEntityField)) {
                            continue;
                        }
                        String value = "";
                        if (column.getColumnName().contains(".")) {
                            String[] innerObjects = cachedFieldName.split("\\.");
                            Field currentField;
                            Class currentEntity = cls;
                            Object valueHolder = serializable;
                            for (String innerObject : innerObjects) {
                                currentField = currentEntity.getDeclaredField(innerObject);
                                currentField.setAccessible(true);
                                valueHolder = currentField.get(valueHolder);
                                currentEntity = valueHolder.getClass();
                            }
                            value = valueHolder.toString();
                        } else {
                            value = field.get(serializable).toString();
                        }
                        innerResult.add(value);
                    }
                }
            }
            resultArray.add(innerResult);
        }
        Integer itemsCount = allResults.size();
        session.close();
        factory.close();
        Gson gson = new Gson();
        DataGridResponseObject<Serializable> resp = new DataGridResponseObject<>();
        resp.setData(resultArray);
        resp.setDraw(params.getDraw());
        resp.setRecordsFiltered(itemsCount);
        resp.setRecordsTotal(itemsCount);
        String json = gson.toJson(resp);
        return json;
    } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InstantiationException
            | NoSuchFieldException | SecurityException | ParseException | HibernateException ex) {
        session.close();
        factory.close();
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.picocontainer.persistence.hibernate.AbstractConfigurationTestCase.java

License:Open Source License

protected void assertPojoCanBeSaved(SessionFactory sessionFactory, Fooable pojo) {
    Session session = null;// w w  w.  ja v a 2 s .c  o m
    try {
        session = sessionFactory.openSession();
        Integer result = (Integer) session.save(pojo);
        assertNotNull(result);
        session.close();

        session = sessionFactory.openSession();
        Fooable pojo2 = (Fooable) session.load(pojo.getClass(), result);
        assertNotNull(pojo);
        assertEquals(pojo.getId(), pojo2.getId());
        assertEquals(pojo.getFoo(), pojo2.getFoo());
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
        sessionFactory.close();
    }
}

From source file:com.picocontainer.persistence.hibernate.ScopedSessionTestCase.java

License:Open Source License

@Test
public void canSavePojo() {
    Pojo pojo = new Pojo();
    pojo.setFoo("This is a test");
    SessionFactory factory = (new ConstructableConfiguration("/hibernate.cfg.xml")).buildSessionFactory();
    ScopedSession session = new ScopedSession(factory);

    try {/*from w w w .  j  a  va2 s. c  o  m*/
        Integer result = (Integer) session.save(pojo);
        assertNotNull(result);

        // Normally Close will force a new session to be created in the
        // background the next time it is used.
        session.close();

        // We're just doing it this way to show that it works with normal
        // hibenate procedures.
        session = new ScopedSession(factory);

        Fooable pojo2 = (Fooable) session.load(pojo.getClass(), result);
        assertNotNull(pojo);
        assertEquals(pojo.getId(), pojo2.getId());
        assertEquals(pojo.getFoo(), pojo2.getFoo());
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
        factory.close();
    }
}

From source file:com.referencelogic.xmlormupload.main.XmlormuploadMain.java

License:Open Source License

public void run() {
    try {//from w w w  . jav a  2 s.  co  m
        XMLConfiguration config = new XMLConfiguration(configFileName);
        String sourceDir = config.getString("source.path");
        List allowedExtensions = config.getList("source.extensions");
        int poolSize = config.getInt("threadpool.size");

        String groovySourceDir = config.getString("domainclasses.path");
        List groovyAllowedExtensions = config.getList("domainclasses.extensions");

        if (isDebugging) {
            log.debug("Loaded configuration successfully. Reading groovy class list from: " + groovySourceDir
                    + " with allowed extensions " + groovyAllowedExtensions);
        }

        if (isDebugging) {
            log.debug("Loaded configuration successfully. Reading file list from: " + sourceDir
                    + " with allowed extensions " + allowedExtensions);
        }
        Iterator iter = FileUtils.iterateFiles(new File(sourceDir),
                (String[]) allowedExtensions.toArray(new String[allowedExtensions.size()]), true);
        if (poolSize < 1) {
            poolSize = 5;
        }

        exec = Executors.newFixedThreadPool(poolSize);

        GroovyClassLoader gcl = new GroovyClassLoader();

        ClassLoader ojcl = Thread.currentThread().getContextClassLoader();

        boolean allFilesResolved = false;
        while (!allFilesResolved) {
            Iterator groovyIter = FileUtils.iterateFiles(new File(groovySourceDir),
                    (String[]) groovyAllowedExtensions.toArray(new String[groovyAllowedExtensions.size()]),
                    true);

            allFilesResolved = true;

            while (groovyIter.hasNext()) {
                File groovyFile = (File) groovyIter.next();
                log.info("Trying to parse file " + groovyFile);
                try {
                    Class clazz = gcl.parseClass(groovyFile);
                } catch (IOException ioe) {
                    log.error("Unable to read file " + groovyFile + " to parse class ", ioe);
                } catch (Exception e) {
                    log.error("Unable to parse file " + groovyFile + " ex:" + e);
                    allFilesResolved = false;
                }
            }

        }

        Thread.currentThread().setContextClassLoader(gcl);

        Configuration hibernateConfig = new Configuration();

        SessionFactory sf;
        if (!matchRegex) {
            sf = hibernateConfig.configure(new File("hibernate.config.xml")).buildSessionFactory();
        } else {
            sf = hibernateConfig.configure(new File("hibernate.update.config.xml")).buildSessionFactory();
        }

        log.info("Opened session");

        while (iter.hasNext()) {
            File file = (File) iter.next();
            String filePath = "";
            try {
                filePath = file.getCanonicalPath();
                log.debug("Canonical path being processed is: " + filePath);
            } catch (IOException ioe) {
                log.warn("Unable to get canonical path from file", ioe);
            }
            log.debug("Is matchRegex true? " + matchRegex);
            log.debug("Does filePath match regexStr?" + filePath.matches(matchRegexStr));
            if ((!matchRegex) || (matchRegex && filePath.matches(matchRegexStr))) {
                exec.execute(new Xmlormuploader(file, config, gcl, sf));
            }
        }

        exec.shutdown();
        try {
            while (!exec.isTerminated()) {
                exec.awaitTermination(30, TimeUnit.SECONDS);
            }
        } catch (InterruptedException ie) {
            // Do nothing, going to close database connection anyway        
        }

        sf.close();

    } catch (ConfigurationException cex) {
        log.fatal("Unable to load config file " + configFileName + " to determine configuration.", cex);
    }
}