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:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java

License:Open Source License

public static List<Collection<MetricStatistics>> getManyMetricStatistics(
        List<GetMetricStatisticsParams> getMetricStatisticsParamses) {
    if (getMetricStatisticsParamses == null)
        throw new IllegalArgumentException("getMetricStatisticsParamses can not be null");
    Date now = new Date();
    Map<GetMetricStatisticsParams, Collection<MetricStatistics>> resultMap = Maps.newHashMap();
    Multimap<Class, GetMetricStatisticsParams> hashGroupMap = LinkedListMultimap.create();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (getMetricStatisticsParams == null)
            throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
        getMetricStatisticsParams.validate(now);
        Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
                getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
        hashGroupMap.put(metricEntityClass, getMetricStatisticsParams);
    }//from  ww w  .  j ava  2s  .  c  o m
    for (Class metricEntityClass : hashGroupMap.keySet()) {
        try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
            // set some global criteria to start (for narrowing?)
            Date minDate = null;
            Date maxDate = null;
            Junction disjunction = Restrictions.disjunction();
            Map<GetMetricStatisticsParams, TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>> multiAggregationMap = Maps
                    .newHashMap();
            for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap.get(metricEntityClass)) {
                multiAggregationMap.put(getMetricStatisticsParams,
                        new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
                                GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE));
                Junction conjunction = Restrictions.conjunction();
                conjunction = conjunction
                        .add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
                conjunction = conjunction
                        .add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
                conjunction = conjunction
                        .add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
                conjunction = conjunction
                        .add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
                conjunction = conjunction
                        .add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
                conjunction = conjunction.add(
                        Restrictions.eq("dimensionHash", hash(getMetricStatisticsParams.getDimensionMap())));
                if (getMetricStatisticsParams.getUnits() != null) {
                    conjunction = conjunction
                            .add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
                }
                disjunction = disjunction.add(conjunction);
                if (minDate == null || getMetricStatisticsParams.getStartTime().before(minDate)) {
                    minDate = getMetricStatisticsParams.getStartTime();
                }
                if (maxDate == null || getMetricStatisticsParams.getEndTime().after(maxDate)) {
                    maxDate = getMetricStatisticsParams.getEndTime();
                }
            }
            Criteria criteria = Entities.createCriteria(metricEntityClass);
            criteria = criteria.add(Restrictions.lt("timestamp", maxDate));
            criteria = criteria.add(Restrictions.ge("timestamp", minDate));
            criteria = criteria.add(disjunction);

            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.max("sampleMax"));
            projectionList.add(Projections.min("sampleMin"));
            projectionList.add(Projections.sum("sampleSize"));
            projectionList.add(Projections.sum("sampleSum"));
            projectionList.add(Projections.groupProperty("units"));
            projectionList.add(Projections.groupProperty("timestamp"));
            projectionList.add(Projections.groupProperty("accountId"));
            projectionList.add(Projections.groupProperty("metricName"));
            projectionList.add(Projections.groupProperty("metricType"));
            projectionList.add(Projections.groupProperty("namespace"));
            projectionList.add(Projections.groupProperty("dimensionHash"));
            criteria.setProjection(projectionList);
            criteria.addOrder(Order.asc("timestamp"));

            ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
            while (results.next()) {
                MetricEntity me = getMetricEntity(results);
                for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap
                        .get(metricEntityClass)) {
                    if (metricDataMatches(getMetricStatisticsParams, me)) {
                        Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = multiAggregationMap
                                .get(getMetricStatisticsParams);
                        GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensionHash());
                        MetricStatistics item = new MetricStatistics(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensions());
                        if (!aggregationMap.containsKey(key)) {
                            aggregationMap.put(key, item);
                        } else {
                            MetricStatistics totalSoFar = aggregationMap.get(key);
                            totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax()));
                            totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin()));
                            totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize());
                            totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum());
                        }
                    }
                }
            }
            for (GetMetricStatisticsParams getMetricStatisticsParams : multiAggregationMap.keySet()) {
                resultMap.put(getMetricStatisticsParams,
                        multiAggregationMap.get(getMetricStatisticsParams).values());
            }
        }
    }
    List<Collection<MetricStatistics>> resultList = Lists.newArrayList();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (resultMap.get(getMetricStatisticsParams) == null) {
            resultList.add(new ArrayList<MetricStatistics>());
        } else {
            resultList.add(resultMap.get(getMetricStatisticsParams));
        }
    }
    return resultList;
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java

License:Open Source License

public static Collection<MetricStatistics> getMetricStatistics(
        GetMetricStatisticsParams getMetricStatisticsParams) {
    if (getMetricStatisticsParams == null)
        throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
    Date now = new Date();
    getMetricStatisticsParams.validate(now);
    Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
            getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
    Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
            GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE);
    try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
        Criteria criteria = Entities.createCriteria(metricEntityClass);
        criteria = criteria.add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
        criteria = criteria.add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
        criteria = criteria.add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
        criteria = criteria.add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
        criteria = criteria.add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
        criteria = criteria.add(Restrictions.eq("dimensionHash", getMetricStatisticsParams.getDimensionHash()));
        if (getMetricStatisticsParams.getUnits() != null) {
            criteria = criteria.add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
        }//from   w  ww  .  j a va  2 s. c om

        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.max("sampleMax"));
        projectionList.add(Projections.min("sampleMin"));
        projectionList.add(Projections.sum("sampleSize"));
        projectionList.add(Projections.sum("sampleSum"));
        projectionList.add(Projections.groupProperty("units"));
        projectionList.add(Projections.groupProperty("timestamp"));
        criteria.setProjection(projectionList);
        criteria.addOrder(Order.asc("timestamp"));
        ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
        while (results.next()) {
            MetricEntity me = getMetricEntity(getMetricStatisticsParams.getAccountId(),
                    getMetricStatisticsParams.getMetricName(), getMetricStatisticsParams.getNamespace(),
                    getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash(),
                    results);
            GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me,
                    getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                    getMetricStatisticsParams.getDimensionHash());
            MetricStatistics item = new MetricStatistics(me, getMetricStatisticsParams.getStartTime(),
                    getMetricStatisticsParams.getPeriod(), getMetricStatisticsParams.getDimensions());
            if (!aggregationMap.containsKey(key)) {
                aggregationMap.put(key, item);
            } else {
                MetricStatistics totalSoFar = aggregationMap.get(key);
                totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax()));
                totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin()));
                totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize());
                totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum());
            }
        }
    }
    return Lists.newArrayList(aggregationMap.values());
}

From source file:com.eucalyptus.cluster.callback.reporting.FullTableScanAbsoluteMetricConverter.java

License:Open Source License

protected static List<AbsoluteMetricQueueItem> dealWithAbsoluteMetrics(
        Iterable<AbsoluteMetricQueueItem> dataBatch) {
    List<AbsoluteMetricQueueItem> regularMetrics = Lists.newArrayList();
    List<SimpleAbsoluteMetricHistory> absoluteMetricsToInsert = Lists.newArrayList();
    SortedAbsoluteMetrics sortedAbsoluteMetrics = sortAbsoluteMetrics(dataBatch);
    regularMetrics.addAll(sortedAbsoluteMetrics.getRegularMetrics());
    AbsoluteMetricMap absoluteMetricMap = sortedAbsoluteMetrics.getAbsoluteMetricMap();
    try (final TransactionResource db = Entities.transactionFor(AbsoluteMetricHistory.class)) {
        int count = 0;
        Criteria criteria = Entities.createCriteria(AbsoluteMetricHistory.class);
        ScrollableResults absoluteMetrics = criteria.setCacheMode(CacheMode.IGNORE)
                .scroll(ScrollMode.FORWARD_ONLY);
        while (absoluteMetrics.next()) {
            AbsoluteMetricHistory absoluteMetricHistory = (AbsoluteMetricHistory) absoluteMetrics.get(0);
            if (absoluteMetricMap.containsKey(absoluteMetricHistory.getNamespace(),
                    absoluteMetricHistory.getMetricName(), absoluteMetricHistory.getDimensionName(),
                    absoluteMetricHistory.getDimensionValue())) {
                MetricsAndOtherFields metricsAndOtherFields = absoluteMetricMap.getMetricsAndOtherFields(
                        absoluteMetricHistory.getNamespace(), absoluteMetricHistory.getMetricName(),
                        absoluteMetricHistory.getDimensionName(), absoluteMetricHistory.getDimensionValue());
                Map<TimestampAndMetricValue, MetricDatum> metricDatumMap = metricsAndOtherFields
                        .getMetricDatumMap();
                SequentialMetrics sequentialMetrics = calculateSequentialMetrics(absoluteMetricHistory,
                        metricDatumMap, metricsAndOtherFields.getAccountId(),
                        metricsAndOtherFields.getRelativeMetricName());
                absoluteMetricMap.removeEntries(absoluteMetricHistory.getNamespace(),
                        absoluteMetricHistory.getMetricName(), absoluteMetricHistory.getDimensionName(),
                        absoluteMetricHistory.getDimensionValue());
                for (AbsoluteMetricQueueItem regularMetric : sequentialMetrics.getRegularMetrics()) {
                    if (AbsoluteMetricHelper.AWS_EBS_NAMESPACE.equals(regularMetric.getNamespace())) {
                        if (AbsoluteMetricHelper.VOLUME_READ_OPS_METRIC_NAME
                                .equals(regularMetric.getMetricDatum().getMetricName())) { // special case
                            regularMetrics.add(AbsoluteMetricHelper.createVolumeThroughputMetric(
                                    regularMetric.getAccountId(), regularMetric.getNamespace(),
                                    regularMetric.getMetricDatum()));
                        } else if (AbsoluteMetricHelper.VOLUME_TOTAL_READ_WRITE_TIME_METRIC_NAME
                                .equals(regularMetric.getMetricDatum().getMetricName())) {
                            AbsoluteMetricHelper.convertVolumeTotalReadWriteTimeToVolumeIdleTime(
                                    regularMetric.getMetricDatum());
                        }//w ww  .  j  av a 2  s.  com
                    }
                    regularMetrics.add(regularMetric);
                }
                absoluteMetricHistory.setTimestamp(sequentialMetrics.getUpdateTimestamp());
                absoluteMetricHistory.setLastMetricValue(sequentialMetrics.getUpdateValue());
                if (++count % AbsoluteMetricQueue.ABSOLUTE_METRIC_NUM_DB_OPERATIONS_UNTIL_SESSION_FLUSH == 0) {
                    Entities.flushSession(AbsoluteMetricHistory.class);
                    Entities.clearSession(AbsoluteMetricHistory.class);
                }
            }
        }
        db.commit();
    }
    // Now parse entries only in the map...
    for (AbsoluteMetricMap.NamespaceMetricNameAndDimension namespaceMetricNameAndDimension : absoluteMetricMap
            .keySet()) {
        AbsoluteMetricHistory absoluteMetricHistory = new AbsoluteMetricHistory();
        absoluteMetricHistory.setNamespace(namespaceMetricNameAndDimension.getNamespace());
        absoluteMetricHistory.setMetricName(namespaceMetricNameAndDimension.getMetricName());
        absoluteMetricHistory.setDimensionName(namespaceMetricNameAndDimension.getDimensionName());
        absoluteMetricHistory.setDimensionValue(namespaceMetricNameAndDimension.getDimensionValue());
        MetricsAndOtherFields metricsAndOtherFields = absoluteMetricMap.get(namespaceMetricNameAndDimension);
        Map<TimestampAndMetricValue, MetricDatum> metricDataMap = metricsAndOtherFields.getMetricDatumMap();
        if (metricDataMap.size() == 0)
            continue;
        TimestampAndMetricValue firstValue = metricDataMap.keySet().iterator().next();
        metricDataMap.remove(firstValue);
        absoluteMetricHistory.setLastMetricValue(firstValue.getMetricValue());
        absoluteMetricHistory.setTimestamp(firstValue.getTimestamp());
        if (metricDataMap.size() != 0) {
            SequentialMetrics sequentialMetrics = calculateSequentialMetrics(absoluteMetricHistory,
                    metricDataMap, metricsAndOtherFields.getAccountId(),
                    metricsAndOtherFields.getRelativeMetricName());
            for (AbsoluteMetricQueueItem regularMetric : sequentialMetrics.getRegularMetrics()) {
                if (AbsoluteMetricHelper.AWS_EBS_NAMESPACE.equals(regularMetric.getNamespace())) {
                    if (AbsoluteMetricHelper.VOLUME_READ_OPS_METRIC_NAME
                            .equals(regularMetric.getMetricDatum().getMetricName())) { // special case
                        regularMetrics.add(
                                AbsoluteMetricHelper.createVolumeThroughputMetric(regularMetric.getAccountId(),
                                        regularMetric.getNamespace(), regularMetric.getMetricDatum()));
                    } else if (AbsoluteMetricHelper.VOLUME_TOTAL_READ_WRITE_TIME_METRIC_NAME
                            .equals(regularMetric.getMetricDatum().getMetricName())) {
                        AbsoluteMetricHelper.convertVolumeTotalReadWriteTimeToVolumeIdleTime(
                                regularMetric.getMetricDatum());
                    }
                }
                regularMetrics.add(regularMetric);
            }
            absoluteMetricHistory.setTimestamp(sequentialMetrics.getUpdateTimestamp());
            absoluteMetricHistory.setLastMetricValue(sequentialMetrics.getUpdateValue());
        }
        absoluteMetricsToInsert.add(convertToSimpleAbsoluteMetricHistory(absoluteMetricHistory));
    }

    // insert all new points
    try (final TransactionResource db = Entities.transactionFor(AbsoluteMetricHistory.class)) {
        int count = 0;
        for (SimpleAbsoluteMetricHistory simpleAbsoluteMetricHistory : absoluteMetricsToInsert) {
            Entities.persist(convertToAbsoluteMetricHistory(simpleAbsoluteMetricHistory));
            if (++count % AbsoluteMetricQueue.ABSOLUTE_METRIC_NUM_DB_OPERATIONS_UNTIL_SESSION_FLUSH == 0) {
                Entities.flushSession(AbsoluteMetricHistory.class);
                Entities.clearSession(AbsoluteMetricHistory.class);
            }
        }
        db.commit();
    }
    return regularMetrics;
}

From source file:com.eucalyptus.reporting.art.generator.AbstractArtGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
protected <ET> void foreach(final Class<ET> eventClass, final Criterion criterion, final boolean ascending,
        final Predicate<? super ET> callback) {
    final EntityTransaction transaction = Entities.get(eventClass);
    ScrollableResults results = null;/*w  w w  .j  a  v a 2  s . co m*/
    try {
        results = Entities.createCriteria(eventClass).setReadOnly(true).setCacheable(false)
                .setCacheMode(CacheMode.IGNORE).setFetchSize(100).add(criterion)
                .addOrder(ascending ? Order.asc(TIMESTAMP_MS) : Order.desc(TIMESTAMP_MS))
                .scroll(ScrollMode.FORWARD_ONLY);

        while (results.next()) {
            final ET event = (ET) results.get(0);
            if (!callback.apply(event)) {
                break;
            }
            Entities.evict(event);
        }
    } finally {
        if (results != null)
            try {
                results.close();
            } catch (Exception e) {
            }
        transaction.rollback();
    }
}

From source file:com.eucalyptus.reporting.dw.commands.StatusCommand.java

License:Open Source License

private long timestamp(final Class<? extends ReportingEventSupport> entityClass, final Projection projection,
        final long defaultValue) {
    final Number value = (Number) Entities.createCriteria(entityClass).setReadOnly(true).setCacheable(false)
            .setCacheMode(CacheMode.IGNORE).setProjection(projection).uniqueResult();
    return value == null ? defaultValue : value.longValue();
}

From source file:com.eucalyptus.reporting.export.Export.java

License:Open Source License

private static Criteria criteriaFor(final Class<?> persistentClass, final Criterion criterion) {
    return Entities.createCriteria(persistentClass).setReadOnly(true).setCacheable(false)
            .setCacheMode(CacheMode.IGNORE).setFetchSize(500).add(criterion);
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query./*from   w w  w  .  j  a va  2s  . co  m*/
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.humber.java.dao.AlbumDAO.java

public List<Album> getAllAlbums() {
    List<Album> albums = new ArrayList<Album>();
    Transaction trns = null;//  w w w  . ja  v a 2s .c o m
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        albums = session.createQuery("from Album").list();
        session.setCacheMode(CacheMode.IGNORE);
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return albums;
}

From source file:com.ikon.servlet.admin.RebuildIndexesServlet.java

License:Open Source License

/**
 * FlushToIndexes implementation//from w  ww.  j  av a2  s.c  om
 */
@SuppressWarnings("rawtypes")
private void luceneIndexesFlushToIndexes(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("luceneIndexesFlushToIndexes({}, {})", request, response);
    PrintWriter out = response.getWriter();
    response.setContentType(MimeTypeConfig.MIME_HTML);
    header(out, "Rebuild Lucene indexes", breadcrumb);
    out.flush();

    FullTextSession ftSession = null;
    Session session = null;
    Transaction tx = null;

    try {
        Config.SYSTEM_MAINTENANCE = true;
        Config.SYSTEM_READONLY = true;
        out.println("<ul>");
        out.println("<li>System into maintenance mode</li>");
        FileLogger.info(BASE_NAME, "BEGIN - Rebuild Lucene indexes");

        session = HibernateUtil.getSessionFactory().openSession();
        ftSession = Search.getFullTextSession(session);
        ftSession.setFlushMode(FlushMode.MANUAL);
        ftSession.setCacheMode(CacheMode.IGNORE);
        tx = ftSession.beginTransaction();
        Map<String, Long> total = new HashMap<String, Long>();

        // Calculate number of entities
        for (Class cls : classes) {
            String nodeType = cls.getSimpleName();
            out.println("<li>Calculate " + nodeType + "</li>");
            out.flush();
            long partial = NodeBaseDAO.getInstance().getCount(nodeType);
            FileLogger.info(BASE_NAME, "Number of {0}: {1}", nodeType, partial);
            out.println("<li>Number of " + nodeType + ": " + partial + "</li>");
            out.flush();
            total.put(nodeType, partial);
        }

        // Rebuild indexes
        out.println("<li>Rebuilding indexes</li>");
        out.flush();

        // Scrollable results will avoid loading too many objects in memory
        for (Class cls : classes) {
            String nodeType = cls.getSimpleName();
            out.println("<li>Indexing " + nodeType + "</li>");
            out.flush();

            ProgressMonitor monitor = new ProgressMonitor(out, total.get(nodeType));
            ScrollableResults results = ftSession.createCriteria(cls)
                    .setFetchSize(Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS)
                    .scroll(ScrollMode.FORWARD_ONLY);
            int index = 0;

            while (results.next()) {
                monitor.documentsAdded(1);
                ftSession.index(results.get(0)); // Index each element

                if (index++ % Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS == 0) {
                    ftSession.flushToIndexes(); // Apply changes to indexes
                    ftSession.clear(); // Free memory since the queue is processed
                }
            }
        }

        tx.commit();

        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        out.println("<li>System out of maintenance mode</li>");
        out.flush();

        // Finalized
        FileLogger.info(BASE_NAME, "END - Rebuild Lucene indexes");
        out.println("<li>Index rebuilding completed!</li>");
        out.println("</ul>");
        out.flush();
    } catch (Exception e) {
        tx.rollback();
        out.println("<div class=\"warn\">Exception: " + e.getMessage() + "</div>");
        out.flush();
    } finally {
        HibernateUtil.close(ftSession);
        HibernateUtil.close(session);
    }

    // End page
    footer(out);
    out.flush();
    out.close();

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_FORCE_REBUILD_INDEXES", null, null, null);
    log.debug("luceneIndexesFlushToIndexes: void");
}

From source file:com.kanjiportal.portal.admin.LuceneManagementAction.java

License:Open Source License

public void reIndexKanji() {
    FullTextSession fullTextSession = (FullTextSession) entityManager.getDelegate();
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    log.debug("Indexing kanjis ....");
    long beforeKanjis = System.currentTimeMillis();

    //Scrollable results will avoid loading too many objects in memory
    ScrollableResults results = fullTextSession.createCriteria(Kanji.class).setFetchSize(BATCH_SIZE)
            .setFetchMode("meanings", FetchMode.JOIN).setFetchMode("meanings.meaning.language", FetchMode.JOIN)
            .scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while (results.next()) {
        index++;//w  w  w.j a  v  a2  s  .c o m
        fullTextSession.index(results.get(0)); //index each element
        if (index % BATCH_SIZE == 0) {
            entityManager.flush();
            entityManager.clear();
            log.debug("flush()");
        }
    }

    log.debug("Indexing kanjis done");
    long afterKanjis = System.currentTimeMillis();

    facesMessages.add("Kanji Indexing done in #0 ms", afterKanjis - beforeKanjis);
}