Example usage for org.hibernate CacheMode IGNORE

List of usage examples for org.hibernate CacheMode IGNORE

Introduction

In this page you can find the example usage for org.hibernate CacheMode IGNORE.

Prototype

CacheMode IGNORE

To view the source code for org.hibernate CacheMode IGNORE.

Click Source Link

Document

The session will never interact with the cache, except to invalidate cache items when updates occur.

Usage

From source file:onl.netfishers.netshot.work.tasks.CheckGroupComplianceTask.java

License:Open Source License

@Override
public void run() {
    logger.debug("Starting check compliance task for group {}.", deviceGroup.getId());
    this.logIt(String.format("Check compliance task for group %s.", deviceGroup.getName()), 5);

    Session session = Database.getSession();
    try {/*from  ww  w .j av a2s.c  om*/
        @SuppressWarnings("unchecked")
        List<Policy> policies = session.createCriteria(Policy.class).list();

        session.beginTransaction();
        session.createQuery(
                "delete from CheckResult c where c.key.device.id in (select d.id as id from DeviceGroup g1 join g1.cachedDevices d where g1.id = :id)")
                .setLong("id", deviceGroup.getId()).executeUpdate();
        for (Policy policy : policies) {
            ScrollableResults devices = session.createQuery(
                    "from Device d join fetch d.lastConfig where d.id in (select d.id as id from DeviceGroup g1 join g1.cachedDevices d join d.ownerGroups g2 join g2.appliedPolicies p where g1.id = :id and p.id = :pid)")
                    .setLong("id", deviceGroup.getId()).setLong("pid", policy.getId())
                    .setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
            while (devices.next()) {
                Device device = (Device) devices.get(0);
                policy.check(device, session);
                session.flush();
                session.evict(device);
            }
        }
        session.getTransaction().commit();
        this.status = Status.SUCCESS;
    } catch (Exception e) {
        try {
            session.getTransaction().rollback();
        } catch (Exception e1) {

        }
        logger.error("Error while checking compliance.", e);
        this.logIt("Error while checking compliance: " + e.getMessage(), 2);
        this.status = Status.FAILURE;
        return;
    } finally {
        session.close();
    }
}

From source file:onl.netfishers.netshot.work.tasks.CheckGroupSoftwareTask.java

License:Open Source License

@Override
public void run() {
    logger.debug("Starting check software compliance and hardware support status task for group {}.",
            deviceGroup.getId());// ww w.ja  v  a2s .  com
    this.logIt(String.format("Check software compliance task for group %s.", deviceGroup.getName()), 5);

    Session session = Database.getSession();
    try {
        logger.debug("Retrieving the software rules");
        @SuppressWarnings("unchecked")
        List<SoftwareRule> softwareRules = session.createCriteria(SoftwareRule.class)
                .addOrder(Property.forName("priority").asc()).list();
        logger.debug("Retrieving the hardware rules");
        @SuppressWarnings("unchecked")
        List<HardwareRule> hardwareRules = session.createCriteria(HardwareRule.class).list();

        session.beginTransaction();
        ScrollableResults devices = session
                .createQuery("select d from DeviceGroup g join g.cachedDevices d where g.id = :id")
                .setLong("id", deviceGroup.getId()).setCacheMode(CacheMode.IGNORE)
                .scroll(ScrollMode.FORWARD_ONLY);
        while (devices.next()) {
            Device device = (Device) devices.get(0);
            device.setSoftwareLevel(ConformanceLevel.UNKNOWN);
            for (SoftwareRule rule : softwareRules) {
                rule.check(device);
                if (device.getSoftwareLevel() != ConformanceLevel.UNKNOWN) {
                    break;
                }
            }
            device.resetEoX();
            for (HardwareRule rule : hardwareRules) {
                rule.check(device);
            }
            session.save(device);
            session.flush();
            session.evict(device);
        }
        session.getTransaction().commit();
        this.status = Status.SUCCESS;
    } catch (Exception e) {
        try {
            session.getTransaction().rollback();
        } catch (Exception e1) {

        }
        logger.error("Error while checking compliance.", e);
        this.logIt("Error while checking compliance: " + e.getMessage(), 2);
        this.status = Status.FAILURE;
        return;
    } finally {
        session.close();
    }
}

From source file:onl.netfishers.netshot.work.tasks.PurgeDatabaseTask.java

License:Open Source License

@Override
public void run() {
    logger.debug("Starting cleanup process.");

    {//from  www.  j  a v a  2  s .  c  om
        Session session = Database.getSession();
        try {
            session.beginTransaction();
            logger.trace("Cleaning up tasks finished more than {} days ago...", days);
            this.logIt(String.format("Cleaning up tasks more than %d days ago...", days), 5);
            Calendar when = Calendar.getInstance();
            when.add(Calendar.DATE, -1 * days);
            ScrollableResults tasks = session
                    .createQuery("from Task t where (t.status = :cancelled or t.status = :failure "
                            + "or t.status = :success) and (t.executionDate < :when)")
                    .setParameter("cancelled", Task.Status.CANCELLED)
                    .setParameter("failure", Task.Status.FAILURE).setParameter("success", Task.Status.SUCCESS)
                    .setDate("when", when.getTime()).setCacheMode(CacheMode.IGNORE)
                    .scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (tasks.next()) {
                Task task = (Task) tasks.get(0);
                session.delete(task);
                if (++count % 50 == 0) {
                    session.flush();
                    session.clear();
                }
            }
            session.getTransaction().commit();
            logger.trace("Cleaning up done on tasks, {} entries affected.", count);
            this.logIt(String.format("Cleaning up done on tasks, %d entries affected.", count), 5);
        } catch (HibernateException e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Database error while purging the old tasks from the database.", e);
            this.logIt("Database error during the task purge.", 1);
            this.status = Status.FAILURE;
            return;
        } catch (Exception e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Error while purging the old tasks from the database.", e);
            this.logIt("Error during the task purge.", 1);
            this.status = Status.FAILURE;
            return;
        } finally {
            session.close();
        }
    }

    if (configDays > 0) {
        Session session = Database.getSession();
        try {
            session.beginTransaction();
            logger.trace("Cleaning up configurations taken more than {} days ago...", configDays);
            this.logIt(String.format("Cleaning up configurations older than %d days...", configDays), 5);
            Calendar when = Calendar.getInstance();
            when.add(Calendar.DATE, -1 * configDays);
            Query query;
            if (configSize > 0) {
                query = session.createQuery(
                        "select c from Config c join c.attributes a where (a.class = ConfigLongTextAttribute) group by c.id having (max(length(a.longText.text)) > :size) and (c.changeDate < :when) order by c.device asc, c.changeDate desc")
                        .setInteger("size", configSize * 1024);
            } else {
                query = session.createQuery(
                        "from Config c where (c.changeDate < :when) order by c.device asc, c.changeDate desc");
            }
            ScrollableResults configs = query.setCalendar("when", when).setCacheMode(CacheMode.IGNORE)
                    .scroll(ScrollMode.FORWARD_ONLY);
            long dontDeleteDevice = -1;
            Date dontDeleteBefore = null;
            int count = 0;
            while (configs.next()) {
                try {
                    Config config = (Config) configs.get(0);
                    if ((config.getDevice().getLastConfig() != null
                            && config.getDevice().getLastConfig().getId() == config.getId())
                            || (dontDeleteBefore != null && config.getChangeDate().before(dontDeleteBefore))
                            || (configKeepDays > 0 && dontDeleteDevice != config.getDevice().getId())) {
                        if (configKeepDays > 0) {
                            Calendar limitCalendar = Calendar.getInstance();
                            limitCalendar.setTime(config.getChangeDate());
                            limitCalendar.add(Calendar.DATE, -1 * configKeepDays);
                            dontDeleteBefore = limitCalendar.getTime();
                        }
                    } else {
                        session.delete(config);
                        if (++count % 30 == 0) {
                            session.flush();
                            session.clear();
                        }
                    }
                    dontDeleteDevice = config.getDevice().getId();
                } catch (NullPointerException e1) {
                }
            }
            session.getTransaction().commit();
            logger.trace("Cleaning up done on configurations, {} entries affected.", count);
            this.logIt(String.format("Cleaning up done on configurations, %d entries affected.", count), 5);
        } catch (HibernateException e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Database error while purging the old configurations from the database.", e);
            this.logIt("Database error during the configuration purge.", 1);
            this.status = Status.FAILURE;
            return;
        } catch (Exception e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Error while purging the old configurations from the database.", e);
            this.logIt("Error during the configuration purge.", 1);
            this.status = Status.FAILURE;
            return;
        } finally {
            session.close();
        }
    }

    this.status = Status.SUCCESS;
    logger.trace("Cleaning up process finished.");
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots on the target date.
 *
 * @param targetDate/*from  w w w  . ja v a 2s  .  c o m*/
 *  The date for which to retrieve compliance snapshots. If null, the current date will be used
 *  instead.
 *
 * @param consumerUuids
 *  A list of consumer UUIDs to use to filter the results. If provided, only compliances for
 *  consumers in the list will be retrieved.
 *
 * @param ownerFilters
 *  A list of owners to use to filter the results. If provided, only compliances for consumers
 *  belonging to the specified owners (orgs) will be retrieved.
 *
 * @param statusFilters
 *  A list of statuses to use to filter the results. If provided, only compliances with a status
 *  matching the list will be retrieved.
 *
 * @param productNameFilters
 *  A list of product names to use to filter compliances. If provided, only compliances for
 *  consumers having installed the specified products will be retrieved.
 *
 * @param subscriptionSkuFilters
 *  A list of subscription skus to use to filter compliances. If provided, only compliances for
 *  the specified subscription skus will be retrieved.
 *
 * @param subscriptionNameFilters
 *  A list of subscription names to use to filter compliances. If provided, only compliances for
 *  the specified subscription names will be retrieved.
 *
 * @param attributeFilters
 *  A map of entitlement attributes to use to filter compliances. If provided, only compliances
 *  for entitlements having the specified values for the given attributes will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the compliance snapshots for the target date and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIterator(Date targetDate, List<String> consumerUuids,
        List<String> ownerFilters, List<String> statusFilters, List<String> productNameFilters,
        List<String> subscriptionSkuFilters, List<String> subscriptionNameFilters,
        Map<String, String> attributeFilters, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class);
    subquery.createAlias("consumer", "c");
    subquery.createAlias("c.consumerState", "state");

    // https://hibernate.atlassian.net/browse/HHH-2776
    if (consumerUuids != null && !consumerUuids.isEmpty()) {
        subquery.add(Restrictions.in("c.uuid", consumerUuids));
    }

    Date toCheck = targetDate == null ? new Date() : targetDate;
    subquery.add(
            Restrictions.or(Restrictions.isNull("state.deleted"), Restrictions.gt("state.deleted", toCheck)));
    subquery.add(Restrictions.le("state.created", toCheck));

    if (ownerFilters != null && !ownerFilters.isEmpty()) {
        subquery.createAlias("c.owner", "o");
        subquery.add(Restrictions.in("o.key", ownerFilters));
    }

    subquery.add(Restrictions.le("date", toCheck));

    subquery.setProjection(
            Projections.projectionList().add(Projections.max("date")).add(Projections.groupProperty("c.uuid")));

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp").createAlias("comp.consumer", "cs")
            .add(Subqueries.propertiesIn(new String[] { "comp.date", "cs.uuid" }, subquery))
            .setCacheMode(CacheMode.IGNORE).setReadOnly(true);

    if ((statusFilters != null && !statusFilters.isEmpty())
            || (attributeFilters != null && attributeFilters.containsKey("management_enabled"))
            || (productNameFilters != null && !productNameFilters.isEmpty())) {

        query.createAlias("comp.status", "stat");

        if (statusFilters != null && !statusFilters.isEmpty()) {
            query.add(Restrictions.in("stat.status", statusFilters));
        }

        if (attributeFilters != null && attributeFilters.containsKey("management_enabled")) {
            boolean managementEnabledFilter = PropertyConverter
                    .toBoolean(attributeFilters.get("management_enabled"));
            query.add(Restrictions.eq("stat.managementEnabled", managementEnabledFilter));
        }

        if (productNameFilters != null && !productNameFilters.isEmpty()) {
            query.createAlias("stat.compliantProducts", "cprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.partiallyCompliantProducts", "pcprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.nonCompliantProducts", "ncprod", JoinType.LEFT_OUTER_JOIN);

            DetachedCriteria prodQuery = DetachedCriteria.forClass(Compliance.class, "comp2");
            prodQuery.createAlias("comp2.consumer", "cons2");
            prodQuery.createAlias("cons2.installedProducts", "installed");
            prodQuery.add(Restrictions.and(Restrictions.in("installed.productName", productNameFilters),
                    Restrictions.eqProperty("comp2.id", "comp.id")));
            prodQuery.setProjection(Projections.property("installed.productId"));

            query.add(Restrictions.or(Property.forName("cprod.productId").in(prodQuery),
                    Property.forName("pcprod.productId").in(prodQuery),
                    Property.forName("ncprod.productId").in(prodQuery)));
        }
    }

    // Add subscription filters, if necessary
    if ((subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty())
            || (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty())) {

        // Impl note: We have to be very careful with alias names, as Hibernate has a tendancy
        // to errorneously truncate "long" ones. Actual property/field names are safe, though.
        query.createAlias("comp.entitlements", "entsnap");

        if (subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productId", subscriptionSkuFilters));
        }

        if (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productName", subscriptionNameFilters));
        }
    }

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots for the specified consumer.
 *
 * @param consumerUUID//  w ww  .  java2 s  . c o  m
 *  The UUID for the consumer for which to retrieve compliance snapshots.
 *
 * @param startDate
 *  The start date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  after the start date, and the snapshot immediately preceding it, will be retrieved.
 *
 * @param endDate
 *  The end date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  before the end date will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the snapshots for the specified consumer, and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate,
        Date endDate, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp1");
    query.createAlias("comp1.consumer", "cons1");

    query.add(Restrictions.eq("cons1.uuid", consumerUUID));

    if (startDate != null) {
        DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2");
        subquery.createAlias("comp2.consumer", "cons2");
        subquery.createAlias("cons2.consumerState", "state2");

        subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"),
                Restrictions.gt("state2.deleted", startDate)));

        subquery.add(Restrictions.lt("state2.created", startDate));
        subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid"));
        subquery.add(Restrictions.lt("comp2.date", startDate));

        subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date")));

        query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate))
                .add(Subqueries.propertyEq("comp1.date", subquery)));
    }

    if (endDate != null) {
        query.add(Restrictions.le("comp1.date", endDate));
    }

    query.setCacheMode(CacheMode.IGNORE);
    query.setReadOnly(true);

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.castafiore.persistence.LoadHibernateSessionFilter.java

License:Open Source License

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    SessionFactory factory = SpringUtil.getBeanOfType(SessionFactory.class);
    Map castaSession = SpringUtil.getBean("casta_session");
    Session s = null;//from  www.  ja  v a  2  s. com
    if (!castaSession.containsKey("hibernate.session")) {
        s = factory.openSession();
        s.setFlushMode(FlushMode.COMMIT);
        s.setCacheMode(CacheMode.IGNORE);
        castaSession.put("hibernate.session", s);

    } else {
        s = (Session) castaSession.get("hibernate.session");
    }

    //t = null;
    try {
        if (t == null) {
            t = s.beginTransaction();
            creatorHash = request.hashCode();
        }

        if (!t.isActive()) {
            t.begin();
            creatorHash = request.hashCode();
        }

        chain.doFilter(request, response);

        //s.flush();
        if (t.isActive()) {
            if (creatorHash == request.hashCode()) {
                s.flush();
                t.commit();
                s.clear();

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        if (t != null && t.isActive()) {
            if (creatorHash == request.hashCode()) {
                t.rollback();
                s.clear();
            }
        }

        if (s != null) {

        }
    }

}

From source file:org.compass.gps.device.hibernate.indexer.PaginationHibernateIndexEntitiesIndexer.java

License:Apache License

public void performIndex(CompassSession session, IndexEntity[] entities) {
    for (IndexEntity entity : entities) {
        EntityInformation entityInfo = (EntityInformation) entity;
        int fetchCount = device.getFetchCount();
        int current = 0;
        while (true) {
            if (!device.isRunning()) {
                return;
            }//from   w  w w  .  j  ava  2  s.c  o m
            Session hibernateSession = device.getSessionFactory().openSession();
            hibernateSession.setCacheMode(CacheMode.IGNORE);
            Transaction hibernateTransaction = null;
            try {
                hibernateTransaction = hibernateSession.beginTransaction();
                if (log.isDebugEnabled()) {
                    log.debug(device.buildMessage("Indexing entity [" + entityInfo.getName() + "] range ["
                            + current + "-" + (current + fetchCount) + "]"));
                }
                List values;
                Criteria criteria = entityInfo.getQueryProvider().createCriteria(hibernateSession, entityInfo);
                if (criteria != null) {
                    criteria.setFetchSize(device.getFetchCount());
                    criteria.setFirstResult(current);
                    criteria.setMaxResults(fetchCount);
                    values = criteria.list();
                } else {
                    Query query = entityInfo.getQueryProvider().createQuery(hibernateSession, entityInfo)
                            .setFirstResult(current).setMaxResults(fetchCount);
                    values = query.list();
                }
                for (Object value : values) {
                    session.create(value);
                }
                session.evictAll();
                hibernateTransaction.commit();
                session.close();
                current += fetchCount;
                if (values.size() < fetchCount) {
                    break;
                }
            } catch (Exception e) {
                log.error(device.buildMessage("Failed to index the database"), e);
                if (hibernateTransaction != null) {
                    try {
                        hibernateTransaction.rollback();
                    } catch (Exception e1) {
                        log.warn("Failed to rollback Hibernate", e1);
                    }
                }
                if (!(e instanceof HibernateGpsDeviceException)) {
                    throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"),
                            e);
                }
                throw (HibernateGpsDeviceException) e;
            } finally {
                hibernateSession.close();
            }
        }
    }
}

From source file:org.compass.gps.device.hibernate.indexer.ScrollableHibernateIndexEntitiesIndexer.java

License:Apache License

public void performIndex(CompassSession session, IndexEntity[] entities) {
    for (IndexEntity entity : entities) {
        EntityInformation entityInformation = (EntityInformation) entity;
        if (device.isFilteredForIndex(entityInformation.getName())) {
            continue;
        }/*  w ww. j a v a 2  s. c om*/
        if (!device.isRunning()) {
            return;
        }
        ScrollableResults cursor = null;
        Session hibernateSession = device.getSessionFactory().openSession();
        hibernateSession.setCacheMode(CacheMode.IGNORE);
        Transaction hibernateTransaction = null;
        try {
            hibernateTransaction = hibernateSession.beginTransaction();
            if (log.isDebugEnabled()) {
                log.debug(device.buildMessage("Indexing entities [" + entityInformation.getName()
                        + "] using query [" + entityInformation.getQueryProvider() + "]"));
            }

            Criteria criteria = entityInformation.getQueryProvider().createCriteria(hibernateSession,
                    entityInformation);
            if (criteria != null) {
                if (performOrderById) {
                    Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName());
                    if (performOrder == null || performOrder) {
                        ClassMetadata metadata = hibernateSession.getSessionFactory()
                                .getClassMetadata(entityInformation.getName());
                        String idPropName = metadata.getIdentifierPropertyName();
                        if (idPropName != null) {
                            criteria.addOrder(Order.asc(idPropName));
                        }
                    }
                }
                criteria.setFetchSize(device.getFetchCount());
                cursor = criteria.scroll(ScrollMode.FORWARD_ONLY);
            } else {
                Query query = entityInformation.getQueryProvider().createQuery(hibernateSession,
                        entityInformation);
                cursor = query.scroll(ScrollMode.FORWARD_ONLY);
            }

            // store things in row buffer to allow using batch fetching in Hibernate
            RowBuffer buffer = new RowBuffer(session, hibernateSession, device.getFetchCount());
            Object prev = null;
            while (true) {
                try {
                    if (!cursor.next()) {
                        break;
                    }
                } catch (ObjectNotFoundException e) {
                    continue;
                }
                Object item = cursor.get(0);
                if (prev != null && item != prev) {
                    buffer.put(prev);
                }
                prev = item;
                if (buffer.shouldFlush()) {
                    // put also the item/prev since we are clearing the session
                    // in the flush process
                    buffer.put(prev);
                    buffer.flush();
                    prev = null;
                }
            }
            if (prev != null) {
                buffer.put(prev);
            }
            buffer.close();
            cursor.close();

            hibernateTransaction.commit();
        } catch (Exception e) {
            log.error(device.buildMessage("Failed to index the database"), e);
            if (cursor != null) {
                try {
                    cursor.close();
                } catch (Exception e1) {
                    log.warn(device.buildMessage("Failed to close cursor on error, ignoring"), e1);
                }
            }
            if (hibernateTransaction != null) {
                try {
                    hibernateTransaction.rollback();
                } catch (Exception e1) {
                    log.warn("Failed to rollback Hibernate", e1);
                }
            }
            if (!(e instanceof HibernateGpsDeviceException)) {
                throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e);
            }
            throw (HibernateGpsDeviceException) e;
        } finally {
            hibernateSession.close();
            session.close();
        }
    }
}

From source file:org.compass.gps.device.hibernate.scrollable.Hibernate3ScrollableResultsGpsDevice.java

License:Apache License

/**
 * Indexes the data//  ww w .  j ava2  s .  c o m
 */
protected void doIndex(CompassSession session) throws CompassException {
    // reset the snapshot data before we perform the index operation
    snapshot = new HibernateSnapshot();
    for (Iterator it = mappings.iterator(); it.hasNext();) {
        ResultSetToResourceMapping mapping = (ResultSetToResourceMapping) it.next();
        if (mapping.supportsVersioning()) {
            HibernateAliasSnapshot aliasSnapshot = new HibernateAliasSnapshot(mapping.getAlias());
            snapshot.putAliasSnapshot(aliasSnapshot);
        }
    }

    if (log.isInfoEnabled()) {
        log.info(buildMessage("Indexing the database with fetch count [" + fetchCount + "]"));
    }

    IndexExecution[] indexExecutions = doGetIndexExecutions();
    for (int i = 0; i != indexExecutions.length; i++) {
        IndexExecution indexExecution = indexExecutions[i];

        HibernateSessionWrapper sessionWrapper = doGetHibernateSessionWrapper();

        try {
            sessionWrapper.open();

            Session hibernateSession = ((Hibernate3SessionWrapper) sessionWrapper).getSession();

            String queryString = indexExecution.getStatementQuery();

            if (log.isDebugEnabled()) {
                log.debug("queryString: " + queryString);
            }

            Query query = hibernateSession.createQuery(queryString).setCacheMode(CacheMode.IGNORE);
            String[] returnAliases = query.getReturnAliases();

            ScrollableResults rs = query.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (rs.next()) {
                processRow(indexExecution.getDescription(), rs, returnAliases, session);
                if (++count % fetchCount == 0) {
                    // release memory
                    hibernateSession.flush();
                    hibernateSession.clear();
                }
            }
            rs.close();

        } catch (Exception e) {
            log.error(buildMessage("Failed to index the database"), e);
            sessionWrapper.closeOnError();
            if (!(e instanceof HibernateGpsDeviceException)) {
                throw new HibernateGpsDeviceException(buildMessage("Failed to index the database"), e);
            }
            throw (HibernateGpsDeviceException) e;
        }

    }

    if (log.isInfoEnabled()) {
        log.info(buildMessage("Finished indexing the database"));
    }

    // save the sanpshot data
    getSnapshotPersister().save(snapshot);
}

From source file:org.compass.gps.device.hibernate.scrollable.Hibernate3ScrollableResultsGpsDevice.java

License:Apache License

/**
 * Performs the data change mirroring operation.
 *//* w w w  .  j  a v  a2  s  .c  o  m*/
public synchronized void performMirroring() throws HibernateGpsDeviceException {
    if (!shouldMirrorDataChanges() || isPerformingIndexOperation()) {
        return;
    }
    if (snapshot == null) {
        throw new IllegalStateException(buildMessage(
                "Versioning data was not properly initialized, did you index the device or loaded the data?"));
    }

    HibernateSessionWrapper sessionWrapper = doGetHibernateSessionWrapper();

    try {
        sessionWrapper.open();
        for (Iterator it = mappings.iterator(); it.hasNext();) {
            ResultSetToResourceMapping mapping = (ResultSetToResourceMapping) it.next();
            if (!mapping.supportsVersioning()) {
                continue;
            }
            HibernateAliasSnapshot oldAliasSnapshot = snapshot.getAliasSnapshot(mapping.getAlias());
            if (oldAliasSnapshot == null) {
                log.warn(buildMessage("No snapshot for alias [" + mapping.getAlias()
                        + "] even though there should be support for versioning ignoring the alias"));
                continue;
            }
            HibernateAliasSnapshot newAliasSnapshot = new HibernateAliasSnapshot(mapping.getAlias());
            ArrayList createdRows = new ArrayList();
            ArrayList updatedRows = new ArrayList();
            ArrayList deletedRows = new ArrayList();
            if (log.isDebugEnabled()) {
                log.debug(buildMessage("Executing version query [" + mapping.getVersionQuery() + "]"));
            }

            String[] returnAliases = null;

            Session hibernateSession = ((Hibernate3SessionWrapper) sessionWrapper).getSession();

            String queryString = mapping.getVersionQuery();

            if (log.isDebugEnabled()) {
                log.debug("queryString: " + queryString);
            }

            Query query = hibernateSession.createQuery(queryString).setCacheMode(CacheMode.IGNORE);
            returnAliases = query.getReturnAliases();

            ScrollableResults rs = query.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (rs.next()) {
                if (log.isDebugEnabled()) {
                    StringBuffer sb = new StringBuffer();
                    sb.append(buildMessage("Version row with values "));
                    for (int i = 0; i != returnAliases.length; i++) {
                        sb.append("[").append(returnAliases[i]).append(":");
                        Object value = rs.get(i);
                        sb.append(value);
                        sb.append("] ");
                    }
                    log.debug(sb.toString());
                }

                HibernateAliasRowSnapshot newRowSnapshot = new HibernateAliasRowSnapshot();
                Hibernate3ScrollableResultsRowMarshallHelper marshallHelper = new Hibernate3ScrollableResultsRowMarshallHelper(
                        mapping, newRowSnapshot, compassGps.getMirrorCompass());
                marshallHelper.marshallResultSet(rs, returnAliases);

                // new and old have the same ids
                HibernateAliasRowSnapshot oldRowSnapshot = oldAliasSnapshot.getRow(newRowSnapshot);

                // new row or updated row
                if (oldRowSnapshot == null) {
                    createdRows.add(newRowSnapshot);
                } else if (oldRowSnapshot.isOlderThan(newRowSnapshot)) {
                    updatedRows.add(newRowSnapshot);
                }

                newAliasSnapshot.putRow(newRowSnapshot);

                if (++count % fetchCount == 0) {
                    // release memory
                    hibernateSession.flush();
                    hibernateSession.clear();
                }
            }
            rs.close();

            for (Iterator oldRowIt = oldAliasSnapshot.rowSnapshotIt(); oldRowIt.hasNext();) {
                HibernateAliasRowSnapshot tmpRow = (HibernateAliasRowSnapshot) oldRowIt.next();
                // deleted row
                if (newAliasSnapshot.getRow(tmpRow) == null) {
                    deletedRows.add(tmpRow);
                }
            }
            if (!createdRows.isEmpty() || !updatedRows.isEmpty()) {
                getSnapshotEventListener().onCreateAndUpdate(new CreateAndUpdateSnapshotEvent(hibernateSession,
                        mapping, createdRows, updatedRows, compassGps));
            }
            if (!deletedRows.isEmpty()) {
                getSnapshotEventListener()
                        .onDelete(new DeleteSnapshotEvent(hibernateSession, mapping, deletedRows, compassGps));
            }
            snapshot.putAliasSnapshot(newAliasSnapshot);
        }
    } catch (Exception e) {
        throw new HibernateGpsDeviceException(buildMessage("Failed while mirroring data changes"), e);
    } finally {
        sessionWrapper.close();
    }
    if (isSaveSnapshotAfterMirror()) {
        getSnapshotPersister().save(snapshot);
    }
}