Example usage for org.hibernate Session setCacheMode

List of usage examples for org.hibernate Session setCacheMode

Introduction

In this page you can find the example usage for org.hibernate Session setCacheMode.

Prototype

void setCacheMode(CacheMode cacheMode);

Source Link

Document

Set the cache mode.

Usage

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

boolean isKnownInDB(URI location, String queueName) {
    boolean known = false;

    Session session = null;
    Transaction transaction = null;/* w  ww  .j  a v a 2s.c o  m*/
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session
                .createQuery(
                        String.format("SELECT count(location) FROM %s as cmd WHERE location = ?", queueName))
                .setParameter(0, location);
        Long result = (Long) query.setReadOnly(true).uniqueResult();
        known = (result != null && result.longValue() > 0);

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error(String.format("Unexpected '%s' while testing if location '%s' is known.",
                e.getClass().getName(), location.toASCIIString()), e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return known;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

private List<ICommand> fetchNextCommands(int limit) {
    List<ICommand> result = new ArrayList<ICommand>();

    Session session = null;
    Transaction transaction = null;//from  ww  w. ja v a  2s.co  m
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session.createQuery("FROM EnqueuedCommand as cmd");
        query.setFetchSize(limit); // this is important for derby because there is no limit support
        query.setMaxResults(limit); // restricting number of returned results
        query.setReadOnly(true); // read-only query
        ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

        final Key key = new Key();
        final DynamicBloomFilter bloomFilter = this.bloomFilter;
        final Cache urlExistsCache = this.urlExistsCache;

        // loop through the available commands
        while (sr.next() && result.size() < limit) {
            ICommand cmd = (ICommand) sr.get()[0];

            /* mark command as enqueued */
            session.delete("EnqueuedCommand", cmd);
            session.saveOrUpdate("CrawledCommand", cmd);

            // add command-location into caches
            key.set(cmd.getLocation().toString().getBytes(UTF8), 1.0);
            bloomFilter.add(key);
            Element element = new Element(cmd.getLocation(), null);
            urlExistsCache.put(element);

            result.add(cmd);
        }
        sr.close();

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error("Error while fetching commands", e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return result;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

/**
 * First queries the DB to remove all known locations from the list and then updates
 * it with the new list.// ww  w.  java  2  s . com
 * 
 * @param profileID the ID of the {@link ICommandProfile}, newly created 
 * commands should belong to
 * @param depth depth of the new {@link ICommand} 
 * @param locations the locations to add to the DB
 * @return the number of known locations in the given list
 */
int storeUnknownLocations(int profileID, int depth, LinkedList<URI> locations) {
    if (locations == null || locations.size() == 0)
        return 0;

    int known = 0;
    Session session = null;
    Transaction transaction = null;
    try {
        // open session and transaction
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        // check the cache for URL existance and put the ones not known to the
        // cache into another list and remove them from the list which is checked
        // against the DB below
        known += storeUnknownInDoubleCache(profileID, depth, locations, session);

        // check which URLs are already known against the DB
        if (locations.size() > 0)
            known += storeUnknownInDB(profileID, depth, locations, session, 10);

        transaction.commit();

        // signal writer that a new URL is available
        this.writerThread.signalNewDbData();

        return known;
    } catch (Throwable e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error(String.format("Unexpected '%s' while writing %d new commands to db.",
                e.getClass().getName(), Integer.valueOf(locations.size())), e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return 0;
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public void createDatasource(IDatasource newDatasource)
        throws DuplicateDatasourceException, DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    if (newDatasource != null) {
        if (getDatasource(newDatasource.getName()) == null) {
            try {
                session.setCacheMode(CacheMode.REFRESH);
                IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                        null);//from  w  ww  . ja va 2  s.com
                newDatasource.setPassword(passwordService.encrypt(newDatasource.getPassword()));
                session.save(newDatasource);
            } catch (ObjectFactoryException objface) {
                throw new DatasourceMgmtServiceException(Messages
                        .getErrorString("DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE")); //$NON-NLS-1$
            } catch (PasswordServiceException pse) {
                session.evict(newDatasource);
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0007_UNABLE_TO_ENCRYPT_PASSWORD"), //$NON-NLS-1$
                        pse);
            } catch (HibernateException ex) {
                session.evict(newDatasource);
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0001_UNABLE_TO_CREATE_DATASOURCE", //$NON-NLS-1$
                                newDatasource.getName()),
                        ex);
            } finally {
                session.setCacheMode(CacheMode.NORMAL);
            }
        } else {
            throw new DuplicateDatasourceException(Messages.getErrorString(
                    "DatasourceMgmtService.ERROR_0005_DATASOURCE_ALREADY_EXIST", newDatasource.getName()));//$NON-NLS-1$
        }
    } else {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0010_NULL_DATASOURCE_OBJECT"));//$NON-NLS-1$
    }
    session.setCacheMode(CacheMode.NORMAL);
    HibernateUtil.flushSession();
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public void deleteDatasource(IDatasource datasource)
        throws NonExistingDatasourceException, DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    if (datasource != null) {
        try {//from  w w w. j a v a  2  s .c  o m
            session.setCacheMode(CacheMode.REFRESH);
            session.delete(session.merge(datasource));
        } catch (HibernateException ex) {
            throw new DatasourceMgmtServiceException(ex.getMessage(), ex);
        } finally {
            session.setCacheMode(CacheMode.NORMAL);
        }
    } else {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0010_NULL_DATASOURCE_OBJECT"));//$NON-NLS-1$
    }

    HibernateUtil.flushSession();
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public IDatasource getDatasource(String jndiName) throws DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    IDatasource datasource = null;//from w w w .  j  av  a 2  s.  c om
    try {
        session.setCacheMode(CacheMode.REFRESH);
        IDatasource pentahoDatasource = (IDatasource) session.get(Datasource.class, jndiName);
        if (pentahoDatasource != null) {
            datasource = clone(pentahoDatasource);
            IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                    null);
            datasource.setPassword(passwordService.decrypt(datasource.getPassword()));
        }
        return datasource;
    } catch (ObjectFactoryException objface) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE"), //$NON-NLS-1$
                objface);
    } catch (PasswordServiceException pse) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0008_UNABLE_TO_DECRYPT_PASSWORD"), pse);//$NON-NLS-1$
    } catch (HibernateException ex) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0004_UNABLE_TO_RETRIEVE_DATASOURCE"), ex);//$NON-NLS-1$
    } finally {
        session.setCacheMode(CacheMode.NORMAL);
    }
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public List<IDatasource> getDatasources() throws DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    try {/* w  w  w  .jav  a  2s. c  om*/
        session.setCacheMode(CacheMode.REFRESH);
        String nameQuery = "org.pentaho.platform.repository.datasource.Datasource.findAllDatasources"; //$NON-NLS-1$
        Query qry = session.getNamedQuery(nameQuery).setCacheable(true);
        List<IDatasource> pentahoDatasourceList = qry.list();
        List<IDatasource> datasourceList = new ArrayList<IDatasource>();
        for (IDatasource pentahoDatasource : pentahoDatasourceList) {
            IDatasource datasource = clone(pentahoDatasource);
            IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                    null);
            datasource.setPassword(passwordService.decrypt(datasource.getPassword()));
            datasourceList.add(datasource);
        }
        return datasourceList;
    } catch (PasswordServiceException pse) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0007_UNABLE_TO_ENCRYPT_PASSWORD"), pse);//$NON-NLS-1$
    } catch (ObjectFactoryException objface) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE"), //$NON-NLS-1$
                objface);
    } catch (HibernateException ex) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0004_UNABLE_TO_RETRIEVE_DATASOURCE", ""), //$NON-NLS-1$//$NON-NLS-2$
                ex);
    } finally {
        session.setCacheMode(CacheMode.NORMAL);
    }
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public void updateDatasource(IDatasource datasource)
        throws NonExistingDatasourceException, DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    if (datasource != null) {
        IDatasource tmpDatasource = getDatasource(datasource.getName());
        if (tmpDatasource != null) {
            try {
                session.setCacheMode(CacheMode.REFRESH);
                IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                        null);//from  w w  w . ja  v a2s  .c o  m
                // Store the new encrypted password in the datasource object
                datasource.setPassword(passwordService.encrypt(datasource.getPassword()));

                // BISERVER-5677 - clear the old datasource from the datasource service cache so updates will be available
                // without having to restart the server
                IDatasourceService datasourceService = PentahoSystem.getObjectFactory()
                        .get(IDatasourceService.class, null);
                datasourceService.clearDataSource(datasource.getName());

                session.update(session.merge(datasource));
            } catch (ObjectFactoryException objface) {
                throw new DatasourceMgmtServiceException(Messages.getErrorString(
                        "DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE"), objface);//$NON-NLS-1$
            } catch (PasswordServiceException pse) {
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0007_UNABLE_TO_ENCRYPT_PASSWORD"), //$NON-NLS-1$
                        pse);
            } catch (HibernateException ex) {
                throw new DatasourceMgmtServiceException(Messages.getErrorString(
                        "DatasourceMgmtService.ERROR_0004_UNABLE_TO_RETRIEVE_DATASOURCE", datasource.getName()), //$NON-NLS-1$
                        ex);
            } finally {
                session.setCacheMode(CacheMode.NORMAL);
            }
        } else {
            throw new NonExistingDatasourceException(Messages.getErrorString(
                    "DatasourceMgmtService.ERROR_0006_DATASOURCE_DOES_NOT_EXIST", datasource.getName()));//$NON-NLS-1$
        }
    } else {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0010_NULL_DATASOURCE_OBJECT"));//$NON-NLS-1$
    }
}

From source file:org.unitime.timetable.solver.exam.ExamDatabaseLoader.java

License:Open Source License

public void load() throws Exception {
    iProgress.setStatus("Loading input data ...");
    org.hibernate.Session hibSession = new ExamDAO().getSession();
    hibSession.setCacheMode(CacheMode.IGNORE);
    Transaction tx = null;//  ww w. java 2  s .co m
    try {
        tx = hibSession.beginTransaction();
        TravelTime.populateTravelTimes(getModel().getDistanceMetric(), iSessionId, hibSession);
        loadPeriods();
        loadRooms();

        RoomAvailabilityInterface availability = null;
        if (SolverServerImplementation.getInstance() != null)
            availability = SolverServerImplementation.getInstance().getRoomAvailability();
        else
            availability = RoomAvailability.getInstance();
        if (availability != null)
            loadRoomAvailability(availability);

        loadExams();
        loadStudents();
        loadDistributions();
        ExamType type = ExamTypeDAO.getInstance().get(iExamTypeId, hibSession);
        if (ApplicationProperty.ExaminationConsiderEventConflicts.isTrue(type.getReference()))
            loadAvailabilitiesFromEvents();
        if (ApplicationProperty.ExaminationCreateSameRoomConstraints.isTrue(type.getReference()))
            makeupSameRoomConstraints();
        getModel().init();
        getModel().clearAssignmentContexts(getAssignment());
        checkConsistency();
        assignInitial();
        tx.commit();
    } catch (Exception e) {
        iProgress.fatal("Unable to load examination problem, reason: " + e.getMessage(), e);
        if (tx != null)
            tx.rollback();
        throw e;
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession != null && hibSession.isOpen())
            hibSession.close();
    }
}

From source file:org.unitime.timetable.solver.exam.ExamDatabaseSaver.java

License:Open Source License

public void save() {
    iProgress.setStatus("Saving solution ...");
    org.hibernate.Session hibSession = new ExamDAO().getSession();
    hibSession.setCacheMode(CacheMode.IGNORE);
    Transaction tx = null;/*  ww  w .ja v  a2s.  c  o m*/
    try {
        tx = hibSession.beginTransaction();
        saveSolution(hibSession);
        tx.commit();

        iProgress.setPhase("Refreshing solution ...", 1);
        try {
            if (SolverServerImplementation.getInstance() != null)
                SolverServerImplementation.getInstance().refreshExamSolution(iSessionId, iExamTypeId);
            iProgress.incProgress();
        } catch (Exception e) {
            iProgress.warn("Unable to refresh solution, reason:" + e.getMessage(), e);
        }
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        iProgress.fatal("Unable to save a solution, reason: " + e.getMessage(), e);
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession != null && hibSession.isOpen())
            hibSession.close();
    }
}