org.hibernate.search.FullTextSession - java examples

Here are the examples of the java api org.hibernate.search.FullTextSession taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

76 Examples 7

19 View Complete Implementation : HibernateCompatUtils.java
Copyright GNU General Public License v3.0
Author : micromata
public static void setFlushMode(FullTextSession fullTextSession, FlushMode flushMode) {
    fullTextSession.setFlushMode(flushMode);
}

19 View Complete Implementation : DatabaseDao.java
Copyright GNU General Public License v3.0
Author : micromata
/**
 * @param clazz
 */
private long reindexMreplacedIndexer(final Clreplaced<?> clazz) {
    final Session session = getSession();
    final Criteria criteria = createCriteria(session, clazz, null, true);
    // Get number of objects to re-index (select count(*) from).
    final Long number = (Long) criteria.uniqueResult();
    log.info("Starting (mreplaced) re-indexing of " + number + " entries of type " + clazz.getName() + "...");
    final FullTextSession fullTextSession = Search.getFullTextSession(session);
    try {
        // 
        fullTextSession.createIndexer(clazz).batchSizeToLoadObjects(// 
        25).threadsToLoadObjects(// 
        5).threadsForSubsequentFetching(// 
        20).startAndWait();
    } catch (final InterruptedException ex) {
        log.error("Exception encountered while reindexing: " + ex.getMessage(), ex);
    }
    final SearchFactory searchFactory = fullTextSession.getSearchFactory();
    searchFactory.optimize(clazz);
    log.info("Re-indexing of " + number + " objects of type " + clazz.getName() + " done.");
    return number;
}

19 View Complete Implementation : LiveRunningTest.java
Copyright Apache License 2.0
Author : infinispan
private void writeOnMaster() {
    try (FullTextSession fullTextSession = master.openFullTextSession()) {
        Transaction transaction = fullTextSession.beginTransaction();
        SimpleEmail simpleEmail = new SimpleEmail();
        simpleEmail.to = "outher space";
        simpleEmail.message = "anybody out there?";
        fullTextSession.save(simpleEmail);
        transaction.commit();
        storedEmailsCount++;
    }
}

19 View Complete Implementation : WebDSLFacetTool.java
Copyright Apache License 2.0
Author : webdsl
public static <T> FacetingRequest toFacetingRequest(String field, String rangereplacedtring, Clreplaced<?> enreplacedyClreplaced, Clreplaced<T> type, FullTextSession fts) {
    List<FacetRange<T>> facetRangeList = new ArrayList<FacetRange<T>>();
    DoreplacedentBuilderIndexedEnreplacedy<?> doreplacedentBuilder = ContextHelper.getSearchFactory(fts).getDoreplacedentBuilderIndexedEnreplacedy(enreplacedyClreplaced);
    Matcher matcher = p.matcher(rangereplacedtring);
    FacetRange<T> range;
    T min, max;
    Clreplaced<?> targetClreplaced;
    boolean includeMin, includeMax;
    while (matcher.find()) {
        includeMin = matcher.group(1).equals("[");
        min = (matcher.group(2).isEmpty()) ? null : (T) stringToTypedObject(matcher.group(2).trim(), type);
        max = (matcher.group(3).isEmpty()) ? null : (T) stringToTypedObject(matcher.group(3).trim(), type);
        includeMax = matcher.group(4).equals("]");
        targetClreplaced = (min != null) ? min.getClreplaced() : max.getClreplaced();
        range = new FacetRange<T>(targetClreplaced, min, max, includeMin, includeMax, field, doreplacedentBuilder);
        facetRangeList.add(range);
    }
    FacetingRequestImpl rfr = new RangeFacetRequest<T>(facetName(field), field, facetRangeList, doreplacedentBuilder);
    rfr.setSort(FacetSortOrder.RANGE_DEFINITION_ODER);
    rfr.setIncludeZeroCounts(false);
    rfr.setMaxNumberOfFacets(facetRangeList.size());
    return rfr;
}

19 View Complete Implementation : AbstractSearchQuery.java
Copyright Apache License 2.0
Author : querydsl
/**
 * Abstract base clreplaced for Hibernate Search query clreplacedes
 *
 * @param <T> result type
 * @param <Q> concrete subtype
 */
public abstract clreplaced AbstractSearchQuery<T, Q extends AbstractSearchQuery<T, Q>> implements SimpleQuery<Q>, Fetchable<T> {

    private final EnreplacedyPath<T> path;

    private final QueryMixin<Q> queryMixin;

    private final LuceneSerializer serializer;

    private final FullTextSession session;

    @SuppressWarnings("unchecked")
    public AbstractSearchQuery(FullTextSession session, EnreplacedyPath<T> path) {
        this.queryMixin = new QueryMixin<Q>((Q) this);
        this.session = session;
        this.path = path;
        this.serializer = SearchSerializer.DEFAULT;
        queryMixin.from(path);
    }

    public AbstractSearchQuery(Session session, EnreplacedyPath<T> path) {
        this(Search.getFullTextSession(session), path);
    }

    @Override
    public long fetchCount() {
        return createQuery(true).getResultSize();
    }

    private FullTextQuery createQuery(boolean forCount) {
        QueryMetadata metadata = queryMixin.getMetadata();
        org.apache.lucene.search.Query query;
        if (metadata.getWhere() != null) {
            query = serializer.toQuery(metadata.getWhere(), metadata);
        } else {
            query = new MatchAllDocsQuery();
        }
        FullTextQuery fullTextQuery = session.createFullTextQuery(query, path.getType());
        // order
        if (!metadata.getOrderBy().isEmpty() && !forCount) {
            fullTextQuery.setSort(serializer.toSort(metadata.getOrderBy()));
        }
        // paging
        QueryModifiers modifiers = metadata.getModifiers();
        if (modifiers.isRestricting() && !forCount) {
            Integer limit = modifiers.getLimitAsInteger();
            Integer offset = modifiers.getOffsetAsInteger();
            if (limit != null) {
                fullTextQuery.setMaxResults(limit.intValue());
            }
            if (offset != null) {
                fullTextQuery.setFirstResult(offset.intValue());
            }
        }
        return fullTextQuery;
    }

    @Override
    public Q distinct() {
        return queryMixin.distinct();
    }

    @Override
    @SuppressWarnings("unchecked")
    public CloseableIterator<T> iterate() {
        return new IteratorAdapter<T>(createQuery(false).iterate());
    }

    @Override
    public Q limit(long limit) {
        return queryMixin.limit(limit);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> fetch() {
        return createQuery(false).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public QueryResults<T> fetchResults() {
        FullTextQuery query = createQuery(false);
        return new QueryResults<T>(query.list(), queryMixin.getMetadata().getModifiers(), query.getResultSize());
    }

    @Override
    public Q offset(long offset) {
        return queryMixin.offset(offset);
    }

    @Override
    public Q orderBy(OrderSpecifier<?>... o) {
        return queryMixin.orderBy(o);
    }

    @Override
    public Q restrict(QueryModifiers modifiers) {
        return queryMixin.restrict(modifiers);
    }

    @Override
    public <P> Q set(ParamExpression<P> param, P value) {
        return queryMixin.set(param, value);
    }

    @Override
    public T fetchFirst() {
        return limit(1).fetchOne();
    }

    @SuppressWarnings("unchecked")
    @Override
    public T fetchOne() throws NonUniqueResultException {
        try {
            return (T) createQuery(false).uniqueResult();
        } catch (org.hibernate.NonUniqueResultException e) {
            throw new NonUniqueResultException(e);
        }
    }

    @Override
    public Q where(Predicate... e) {
        return queryMixin.where(e);
    }
}

19 View Complete Implementation : AsyncLiveRunningTest.java
Copyright Apache License 2.0
Author : infinispan
private void writeOnMaster() {
    FullTextSession fullTextSession = master.openFullTextSession();
    try {
        Transaction transaction = fullTextSession.beginTransaction();
        SimpleEmail simpleEmail = new SimpleEmail();
        simpleEmail.to = "outher space";
        simpleEmail.message = "anybody out there?";
        fullTextSession.save(simpleEmail);
        transaction.commit();
        storedEmailsCount++;
    } finally {
        fullTextSession.close();
    }
}

19 View Complete Implementation : HibernateSearchDependentObjectsReindexer.java
Copyright GNU General Public License v3.0
Author : micromata
private void reindexDependents(final HibernateTemplate hibernateTemplate, final Session session, final BaseDO<?> obj, final Set<String> alreadyReindexed) {
    if (alreadyReindexed.contains(getReindexId(obj)) == true) {
        if (log.isDebugEnabled() == true) {
            log.debug("Object already re-indexed (skipping): " + getReindexId(obj));
        }
        return;
    }
    // Needed to flush the object changes!
    session.flush();
    final FullTextSession fullTextSession = Search.getFullTextSession(session);
    fullTextSession.setFlushMode(FlushMode.AUTO);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    try {
        BaseDO<?> dbObj = (BaseDO<?>) session.get(obj.getClreplaced(), obj.getId());
        if (dbObj == null) {
            dbObj = (BaseDO<?>) session.load(obj.getClreplaced(), obj.getId());
        }
        fullTextSession.index(dbObj);
        alreadyReindexed.add(getReindexId(dbObj));
        if (log.isDebugEnabled() == true) {
            log.debug("Object added to index: " + getReindexId(dbObj));
        }
    } catch (final Exception ex) {
        // Don't fail if any exception while re-indexing occurs.
        log.info("Fail to re-index " + obj.getClreplaced() + ": " + ex.getMessage());
    }
    // session.flush(); // clear every batchSize since the queue is processed
    final List<Entry> entryList = map.get(obj.getClreplaced());
    reindexDependents(hibernateTemplate, session, obj, entryList, alreadyReindexed);
}

19 View Complete Implementation : SimpleEntityMassIndexingTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
private void purgeAll(Clreplaced<?> enreplacedyType) throws IOException {
    FullTextSession session = Search.getFullTextSession(openSession());
    session.purgeAll(enreplacedyType);
    session.flushToIndexes();
    final int numDocs;
    try (IndexReader indexReader = session.getSearchFactory().getIndexReaderAccessor().open(enreplacedyType)) {
        numDocs = indexReader.numDocs();
    }
    session.close();
    replacedertThat(numDocs).isEqualTo(0);
}

19 View Complete Implementation : IndexHelper.java
Copyright GNU General Public License v2.0
Author : openkm
protected int doRebuildIndex() throws Exception {
    FullTextSession fullTextSession = (FullTextSession) enreplacedyManager.getDelegate();
    fullTextSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
    fullTextSession.setCacheMode(org.hibernate.CacheMode.IGNORE);
    fullTextSession.purgeAll(NodeDoreplacedentVersion.clreplaced);
    fullTextSession.getSearchFactory().optimize(NodeDoreplacedentVersion.clreplaced);
    String query = "select ndv from NodeDoreplacedentVersion ndv";
    ScrollableResults cursor = fullTextSession.createQuery(query).scroll();
    cursor.last();
    int count = cursor.getRowNumber() + 1;
    log.warn("Re-building Wine index for " + count + " objects.");
    if (count > 0) {
        int batchSize = 300;
        // Reset to first result row
        cursor.first();
        int i = 0;
        while (true) {
            fullTextSession.index(cursor.get(0));
            if (++i % batchSize == 0) {
                fullTextSession.flushToIndexes();
                // Clear persistence context for each batch
                fullTextSession.clear();
                log.info("Flushed index update " + i + " from Thread " + Thread.currentThread().getName());
            }
            if (cursor.isLast()) {
                break;
            }
            cursor.next();
        }
    }
    cursor.close();
    fullTextSession.flushToIndexes();
    // Clear persistence context for each batch
    fullTextSession.clear();
    fullTextSession.getSearchFactory().optimize(NodeDoreplacedentVersion.clreplaced);
    return count;
}

19 View Complete Implementation : StoredIndexTest.java
Copyright Apache License 2.0
Author : infinispan
/**
 * Verifies a query on a specific term returns an expected amount of results. We do actually load enreplacedies from
 * database, so both database and index are tested.
 *
 * @param termMatch
 * @param expectedMatches
 */
private void replacedertEmailsFound(String termMatch, int expectedMatches) {
    FullTextSession fullTextSession = node.openFullTextSession();
    try {
        TermQuery termQuery = new TermQuery(new Term("message", termMatch));
        FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(termQuery, SimpleEmail.clreplaced);
        List<SimpleEmail> list = fullTextQuery.getResultList();
        replacedert.replacedertEquals(expectedMatches, list.size());
        if (expectedMatches != 0) {
            replacedert.replacedertEquals("[email protected]", list.get(0).to);
        }
    } finally {
        fullTextSession.close();
    }
}

19 View Complete Implementation : AbstractBaseService.java
Copyright GNU Affero General Public License v3.0
Author : StadtBern
@PermitAll
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public void updateLuceneIndex(Clreplaced<? extends AbstractEnreplacedy> clazz, String id) {
    // Den Lucene-Index manuell nachführen, da es bei unidirektionalen Relationen nicht automatisch geschieht!
    Session session = persistence.getEnreplacedyManager().unwrap(Session.clreplaced);
    FullTextSession fullTextSession = Search.getFullTextSession(session);
    // Den Index loeschen...
    fullTextSession.purge(clazz, id);
    // ... und neu erstellen
    Object customer = fullTextSession.load(clazz, id);
    fullTextSession.index(customer);
}

19 View Complete Implementation : HibernateIndexer.java
Copyright Apache License 2.0
Author : servicecatalog
private void handleObjectIndexing(Object parameter, Session session) {
    if (parameter == null || session == null) {
        return;
    }
    FullTextSession fts = Search.getFullTextSession(session);
    fts.index(parameter);
}

19 View Complete Implementation : Query.java
Copyright Apache License 2.0
Author : krasserm
private FullTextQuery createFullTextQuery(String query) {
    FullTextSession fullTextSession = Search.createFullTextSession(session);
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(createLuceneQuery(query), domainClreplaced);
    return fullTextQuery.setResultTransformer(Criteria.DISTINCT_ROOT_ENreplacedY);
}

19 View Complete Implementation : HibernateCompatUtils.java
Copyright GNU General Public License v3.0
Author : micromata
public static void setCacheMode(FullTextSession fullTextSession, CacheMode flushMode) {
    fullTextSession.setCacheMode(flushMode);
}

19 View Complete Implementation : SimpleEntityMassIndexingTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
private void startAndWaitMreplacedIndexing(Clreplaced<?> enreplacedyType) throws InterruptedException, IOException {
    FullTextSession session = Search.getFullTextSession(openSession());
    session.createIndexer(enreplacedyType).purgeAllOnStart(true).startAndWait();
    final int numDocs;
    try (IndexReader indexReader = session.getSearchFactory().getIndexReaderAccessor().open(enreplacedyType)) {
        numDocs = indexReader.numDocs();
    }
    replacedertThat(numDocs).isGreaterThan(0);
}

19 View Complete Implementation : HibernateCompatUtils.java
Copyright GNU General Public License v3.0
Author : micromata
public static void index(FullTextSession fullTextSession, Object dbObj) {
    fullTextSession.index(dbObj);
}

19 View Complete Implementation : LiveRunningTest.java
Copyright Apache License 2.0
Author : infinispan
private void replacedertView(FullTextSessionBuilder node) {
    replacedertEquals(slaves.size() + 1, clusterSize(node, EMAIL_TYPE));
    FullTextSession session = node.openFullTextSession();
    try {
        FullTextQuery fullTextQuery = session.createFullTextQuery(new MatchAllDocsQuery());
        int resultSize = fullTextQuery.getResultSize();
        replacedertEquals(storedEmailsCount, resultSize);
    } finally {
        session.close();
    }
}

19 View Complete Implementation : DatabaseDao.java
Copyright GNU General Public License v3.0
Author : micromata
private long reindexObjects(final Clreplaced<?> clazz, final ReindexSettings settings) {
    final Session session = getSession();
    Criteria criteria = createCriteria(session, clazz, settings, true);
    // Get number of objects to re-index (select count(*) from).
    final Long number = (Long) criteria.uniqueResult();
    final boolean scrollMode = number > MIN_REINDEX_ENTRIES_4_USE_SCROLL_MODE ? true : false;
    log.info("Starting re-indexing of " + number + " entries (total number) of type " + clazz.getName() + " with scrollMode=" + scrollMode + "...");
    // NumberUtils.createInteger(System.getProperty("hibernate.search.worker.batch_size")
    final int batchSize = 1000;
    final FullTextSession fullTextSession = Search.getFullTextSession(session);
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    long index = 0;
    if (scrollMode == true) {
        // Scroll-able results will avoid loading too many objects in memory
        criteria = createCriteria(fullTextSession, clazz, settings, false);
        final ScrollableResults results = criteria.scroll(ScrollMode.FORWARD_ONLY);
        while (results.next() == true) {
            final Object obj = results.get(0);
            if (obj instanceof ExtendedBaseDO<?>) {
                ((ExtendedBaseDO<?>) obj).recalculate();
            }
            // index each element
            fullTextSession.index(obj);
            if (index++ % batchSize == 0)
                // clear every batchSize since the queue is processed
                session.flush();
        }
    } else {
        criteria = createCriteria(session, clazz, settings, false);
        final List<?> list = criteria.list();
        for (final Object obj : list) {
            if (obj instanceof ExtendedBaseDO<?>) {
                ((ExtendedBaseDO<?>) obj).recalculate();
            }
            fullTextSession.index(obj);
            if (index++ % batchSize == 0)
                // clear every batchSize since the queue is processed
                session.flush();
        }
    }
    final SearchFactory searchFactory = fullTextSession.getSearchFactory();
    searchFactory.optimize(clazz);
    log.info("Re-indexing of " + index + " objects of type " + clazz.getName() + " done.");
    return index;
}

19 View Complete Implementation : ReadConcernPropagationTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
private void purgeAll(Clreplaced<?> enreplacedyType) throws IOException {
    FullTextSession session = Search.getFullTextSession(sessions.openSession());
    session.purgeAll(enreplacedyType);
    session.flushToIndexes();
}

19 View Complete Implementation : NodeMailDAO.java
Copyright GNU General Public License v2.0
Author : openkm
/**
 * Check if this uuid represents a mail node.
 *
 * Used in SearchDAO, and should exposed in other method should make Security Check
 */
public boolean isMail(FullTextSession ftSession, String uuid) throws HibernateException {
    log.debug("isMail({}, {})", ftSession, uuid);
    boolean ret = ftSession.get(NodeMail.clreplaced, uuid) instanceof NodeMail;
    log.debug("isMail: {}", ret);
    return ret;
}

19 View Complete Implementation : SharedIndexTest.java
Copyright Apache License 2.0
Author : infinispan
@Test
public void testSingleResultFromDeviceIndex() {
    replacedertEquals(1, clusterSize(node, Toaster.clreplaced));
    // index an enreplacedy:
    {
        FullTextSession fullTextSession = node.openFullTextSession();
        Transaction transaction = fullTextSession.beginTransaction();
        Toaster toaster = new Toaster("A1");
        fullTextSession.save(toaster);
        transaction.commit();
        fullTextSession.close();
        verifyResult(node);
    }
}

19 View Complete Implementation : RebuildIndexesServlet.java
Copyright GNU General Public License v2.0
Author : openkm
/**
 * Do real indexes optimization.
 */
public static void optimizeIndexes() throws Exception {
    FullTextSession ftSession = null;
    Session session = null;
    if (optimizeIndexesRunning) {
        log.warn("*** Optimize indexes already running ***");
    } else {
        optimizeIndexesRunning = true;
        log.debug("*** Begin optimize indexes ***");
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            ftSession = Search.getFullTextSession(session);
            // Optimize indexes
            SearchFactory searchFactory = ftSession.getSearchFactory();
            searchFactory.optimize();
        } catch (Exception e) {
            throw e;
        } finally {
            optimizeIndexesRunning = false;
            HibernateUtil.close(ftSession);
            HibernateUtil.close(session);
        }
        log.debug("*** End optimize indexes ***");
    }
}

19 View Complete Implementation : FullTextSearchQueryTranslator.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Override
public List<?> list(SharedSessionContractImplementor session, QueryParameters queryParameters) throws HibernateException {
    FullTextSession fullTextSession = Search.getFullTextSession((Session) session);
    LuceneQueryParsingResult parsingResult = getLuceneQuery(queryParameters, fullTextSession);
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(parsingResult.getQuery(), parsingResult.getTargetEnreplacedy());
    if (requiresProjections(parsingResult.getProjections())) {
        fullTextQuery.setProjection(parsingResult.getProjections().toArray(new String[parsingResult.getProjections().size()]));
    }
    fullTextQuery.setSort(parsingResult.getSort());
    if (queryParameters.getRowSelection().getFirstRow() != null) {
        fullTextQuery.setFirstResult(queryParameters.getRowSelection().getFirstRow());
    }
    if (queryParameters.getRowSelection().getMaxRows() != null) {
        fullTextQuery.setMaxResults(queryParameters.getRowSelection().getMaxRows());
    }
    return fullTextQuery.list();
}

19 View Complete Implementation : HibernateIndexer.java
Copyright Apache License 2.0
Author : servicecatalog
@Asynchronous
@TransactionAttribute(value = TransactionAttributeType.REQUIRED)
public void initIndexForFulltextSearch(final boolean force) {
    FullTextSession fullTextSession = Search.getFullTextSession(getSession());
    // check if index is already present (via query)
    boolean isIndexEmpty;
    SearchFactory searchFactory = fullTextSession.getSearchFactory();
    IndexReader reader = searchFactory.getIndexReaderAccessor().open(Product.clreplaced, Subscription.clreplaced);
    try {
        isIndexEmpty = reader.numDocs() == 0;
    } finally {
        searchFactory.getIndexReaderAccessor().close(reader);
    }
    if (!isIndexEmpty) {
        if (!force) {
            // if so and force is NOT set, return without
            // indexing
            return;
        } else {
            // otherwise delete previous index
            fullTextSession.purgeAll(Product.clreplaced);
            fullTextSession.purgeAll(Subscription.clreplaced);
        }
    }
    // index all enreplacedies relevant for full text search
    // for it: get all products from all global marketplaces
    // (full text search only available for global marketplaces
    // by definition)
    Query query = dm.createNamedQuery("Marketplace.getAll");
    List<Marketplace> globalMps = ParameterizedTypes.list(query.getResultList(), Marketplace.clreplaced);
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    for (Marketplace mp : globalMps) {
        // call find to ensure enreplacedy manager is registered
        dm.find(mp);
        StringBuffer nativeQueryString = new StringBuffer();
        nativeQueryString.append("SELECT p FROM Product p WHERE EXISTS (SELECT c FROM CatalogEntry c WHERE c.marketplace.key = ").append(mp.getKey()).append(" AND c.dataContainer.visibleInCatalog=TRUE AND c.product.key = p.key AND p.dataContainer.status = :status)");
        org.hibernate.Query productsOnMpQuery = fullTextSession.createQuery(nativeQueryString.toString());
        productsOnMpQuery.setParameter("status", ServiceStatus.ACTIVE);
        ScrollableResults results = productsOnMpQuery.scroll(ScrollMode.FORWARD_ONLY);
        int index = 0;
        while (results.next()) {
            index++;
            fullTextSession.index(results.get(0));
            if (index % BATCH_SIZE == 0) {
                fullTextSession.flushToIndexes();
                fullTextSession.clear();
            }
        }
        results.close();
    }
    // index all active subscriptions
    org.hibernate.Query objectQuery = fullTextSession.createQuery("SELECT s FROM Subscription s WHERE s.dataContainer.status NOT IN (:statuses)");
    objectQuery.setParameterList("statuses", new Object[] { SubscriptionStatus.DEACTIVATED, SubscriptionStatus.INVALID });
    ScrollableResults results = objectQuery.scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while (results.next()) {
        index++;
        fullTextSession.index(results.get(0));
        if (index % BATCH_SIZE == 0) {
            fullTextSession.flushToIndexes();
            fullTextSession.clear();
        }
    }
    results.close();
}

19 View Complete Implementation : StoredIndexTest.java
Copyright Apache License 2.0
Author : infinispan
/**
 * This test uses and Infinispan CacheLoader writing in $tmp directory. Make sure we at least clear the index so that
 * subsequent runs of the same test won't fail.
 */
private void cleanupStoredIndex() {
    FullTextSession fullTextSession = node.openFullTextSession();
    try {
        Transaction transaction = fullTextSession.beginTransaction();
        fullTextSession.purgeAll(SimpleEmail.clreplaced);
        transaction.commit();
    } finally {
        fullTextSession.close();
    }
}

19 View Complete Implementation : SearchServiceBean.java
Copyright Apache License 2.0
Author : servicecatalog
/**
 * Performs a search in Lucene and puts the resulting product object ids in
 * a corresponding map.
 *
 * @param query
 *            the Lucene query
 * @param fts
 *            the Hibernate Search FullTextSession
 * @param map
 *            the map for the search results
 * @throws HibernateException
 */
private void searchViaLucene(org.apache.lucene.search.Query query, FullTextSession fts, LinkedHashMap<Long, VOService> map) throws HibernateException {
    FullTextQuery ftQuery = fts.createFullTextQuery(query, Product.clreplaced);
    ftQuery.setProjection("key");
    List<?> result = ftQuery.list();
    if (result != null) {
        for (Object item : result) {
            map.put((Long) ((Object[]) item)[0], null);
        }
    }
}

19 View Complete Implementation : HibernateIndexer.java
Copyright Apache License 2.0
Author : servicecatalog
private void handleListIndexing(Collection<? extends DomainObject<?>> list, Session session) {
    if (list == null || session == null) {
        return;
    }
    FullTextSession fts = Search.getFullTextSession(session);
    for (DomainObject<?> obj : list) {
        if (obj != null) {
            fts.index(obj);
        }
    }
}

19 View Complete Implementation : TwoNodesTest.java
Copyright Apache License 2.0
Author : infinispan
@Test
public void testSomething() {
    replacedertEquals(2, clusterSize(nodea, EMAIL_TYPE));
    // index an enreplacedy:
    {
        FullTextSession fullTextSession = nodea.openFullTextSession();
        Transaction transaction = fullTextSession.beginTransaction();
        SimpleEmail mail = new SimpleEmail();
        mail.to = to;
        mail.message = messageText;
        fullTextSession.save(mail);
        transaction.commit();
        fullTextSession.close();
    }
    // verify nodeb is able to find it:
    verifyNodeSeesUpdatedIndex(nodeb);
    // now start a new node, it will join the cluster and receive the current index state:
    FullTextSessionBuilder nodeC = createClusterNode();
    replacedertEquals(3, clusterSize(nodea, EMAIL_TYPE));
    try {
        // verify the new node is able to perform the same searches:
        verifyNodeSeesUpdatedIndex(nodeC);
    } finally {
        nodeC.close();
    }
    waitMembersCount(nodea, EMAIL_TYPE, 2);
    replacedertEquals(2, clusterSize(nodea, EMAIL_TYPE));
    verifyNodeSeesUpdatedIndex(nodea);
    verifyNodeSeesUpdatedIndex(nodeb);
}

19 View Complete Implementation : SystemService.java
Copyright Apache License 2.0
Author : tagbangers
@Async
@Transactional(propagation = Propagation.SUPPORTS)
public void reIndex() throws Exception {
    logger.info("Re-Index started");
    FullTextSession fullTextSession = Search.getFullTextSession((enreplacedyManager.unwrap(Session.clreplaced)));
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    for (Clreplaced persistentClreplaced : fullTextSession.getSearchFactory().getIndexedTypes()) {
        Transaction transaction = fullTextSession.beginTransaction();
        // Scrollable results will avoid loading too many objects in memory
        ScrollableResults results = fullTextSession.createCriteria(persistentClreplaced).setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY);
        int index = 0;
        while (results.next()) {
            index++;
            // index each element
            fullTextSession.index(results.get(0));
            if (index % BATCH_SIZE == 0) {
                // apply changes to indexes
                fullTextSession.flushToIndexes();
                // free memory since the queue is processed
                fullTextSession.clear();
            }
        }
        transaction.commit();
    }
    logger.info("Re-Index finished");
}

19 View Complete Implementation : AsyncLiveRunningTest.java
Copyright Apache License 2.0
Author : infinispan
private void replacedertView(FullTextSessionBuilder node, final long failTime, boolean printTimings) {
    replacedertEquals(slaves.size() + 1, clusterSize(node, EMAIL_TYPE));
    long remainingTime = 1;
    while (true) {
        if (remainingTime < 0) {
            org.junit.replacedert.fail("Timeout excedded, index state still not consistent across nodes");
        }
        FullTextSession session = node.openFullTextSession();
        try {
            FullTextQuery fullTextQuery = session.createFullTextQuery(new MatchAllDocsQuery());
            int resultSize = fullTextQuery.getResultSize();
            // stopwatch after query execution
            remainingTime = failTime - System.currentTimeMillis();
            if (resultSize == storedEmailsCount) {
                if (printTimings)
                    printout("Matching data found on first slave in less than ms: " + remainingTime);
                // All good
                return;
            }
        } finally {
            session.close();
        }
    }
}

19 View Complete Implementation : FullTextSearchQueryTranslator.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
private LuceneProcessingChain createProcessingChain(Map<String, Object> namedParameters, FullTextSession fullTextSession) {
    SearchIntegrator searchFactory = fullTextSession.getSearchFactory().unwrap(SearchIntegrator.clreplaced);
    return new LuceneProcessingChain.Builder(searchFactory, enreplacedyNamesResolver).namedParameters(namedParameters).buildProcessingChainForClreplacedBasedEnreplacedies();
}

19 View Complete Implementation : FullTextSearchQueryTranslator.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
private LuceneQueryParsingResult getLuceneQuery(QueryParameters queryParameters, FullTextSession fullTextSession) {
    CacheKey cacheKey = new CacheKey(queryParameters.getNamedParameters());
    LuceneQueryParsingResult parsingResult = luceneQueryCache.get(cacheKey);
    if (parsingResult == null) {
        parsingResult = new QueryParser().parseQuery(getQueryString(), createProcessingChain(getNamedParameterValues(queryParameters), fullTextSession));
        LuceneQueryParsingResult cached = luceneQueryCache.putIfAbsent(cacheKey, parsingResult);
        if (cached != null) {
            parsingResult = cached;
        }
    }
    return parsingResult;
}

19 View Complete Implementation : ReadConcernPropagationTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
private void startAndWaitMreplacedIndexing(Clreplaced<?> enreplacedyType) throws InterruptedException, IOException {
    FullTextSession session = Search.getFullTextSession(sessions.openSession());
    session.createIndexer(enreplacedyType).purgeAllOnStart(true).startAndWait();
}

19 View Complete Implementation : StoredIndexTest.java
Copyright Apache License 2.0
Author : infinispan
/**
 * Saves a new test email
 */
private void storeEmail(String content) {
    SimpleEmail email = new SimpleEmail();
    email.to = "[email protected]";
    email.message = content;
    FullTextSession fullTextSession = node.openFullTextSession();
    Transaction transaction = fullTextSession.beginTransaction();
    fullTextSession.save(email);
    transaction.commit();
    fullTextSession.close();
}

19 View Complete Implementation : SearchServiceBean.java
Copyright Apache License 2.0
Author : servicecatalog
public VOServiceListResult searchServices(String marketplaceId, String locale, String searchPhrase, PerformanceHint performanceHint) throws InvalidPhraseException, ObjectNotFoundException {
    ArgumentValidator.notEmptyString("marketplaceId", marketplaceId);
    ArgumentValidator.notEmptyString("locale", locale);
    ArgumentValidator.notEmptyString("searchPhrase", searchPhrase);
    // Load marketplace
    loadMarketplace(marketplaceId);
    List<VOService> voList = new ArrayList<>();
    VOServiceListResult listResult = new VOServiceListResult();
    listResult.setResultSize(voList.size());
    listResult.setServices(voList);
    try {
        Session session = getDm().getSession();
        if (session != null) {
            LinkedHashMap<Long, VOService> map = new LinkedHashMap<>();
            FullTextSession fts = Search.getFullTextSession(session);
            // (1) search in actual locale
            org.apache.lucene.search.Query query = getLuceneQuery(searchPhrase, marketplaceId, locale, false);
            searchViaLucene(query, fts, map);
            if (!DEFAULT_LOCALE.equals(locale)) {
                // (2) search in default locale
                query = getLuceneQuery(searchPhrase, marketplaceId, locale, true);
                searchViaLucene(query, fts, map);
            }
            Set<Long> keySet = new HashSet<>(map.keySet());
            if (keySet.size() > 0) {
                KeyRestrictedListCriteria listCriteria = new KeyRestrictedListCriteria(keySet);
                listCriteria.setLimit(100);
                VOServiceListResult services = getServicesByCriteria(marketplaceId, locale, listCriteria, performanceHint);
                for (VOService svc : services.getServices()) {
                    Long key = Long.valueOf(svc.getKey());
                    if (map.containsKey(key)) {
                        map.put(key, svc);
                    }
                }
            }
            for (Long key : map.keySet()) {
                if (map.get(key) != null) {
                    voList.add(map.get(key));
                }
            }
        }
    } catch (SyntaxError | QueryNodeException e) {
        InvalidPhraseException ipe = new InvalidPhraseException(e, searchPhrase);
        logger.logDebug(ipe.getMessage());
        throw ipe;
    } finally {
        listResult.setResultSize(voList.size());
        listResult.setServices(voList);
    }
    return listResult;
}

18 View Complete Implementation : PostDaoImpl.java
Copyright Apache License 2.0
Author : Anstoner
@Override
public void resetIndexs() {
    FullTextSession fullTextSession = Search.getFullTextSession(super.session());
    // 异步
    fullTextSession.createIndexer(PostPO.clreplaced).start();
}

18 View Complete Implementation : HibernateSearch5InstrumentationTest.java
Copyright Apache License 2.0
Author : elastic
private org.hibernate.search.FullTextQuery createNonJpaFullTextQuery(Query query) {
    FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession(enreplacedyManager.unwrap(Session.clreplaced));
    return fullTextSession.createFullTextQuery(query, Dog.clreplaced);
}

18 View Complete Implementation : Searcher.java
Copyright GNU Affero General Public License v3.0
Author : headsupdev
public ArrayList<Result> calculateResults() {
    results = new ArrayList<Result>();
    if (StringUtil.isEmpty(query) || (appFilter != null && appFilter.size() == 0)) {
        return results;
    }
    Session session = ((HibernateStorage) Manager.getStorageInstance()).getHibernateSession();
    FullTextSession fullTextSession = org.hibernate.search.Search.createFullTextSession(((SessionProxy) session).getRealSession());
    MultiFieldQueryParser parser = new MultiFieldQueryParser(new ArrayList<String>(HibernateUtil.getSearchFields()).toArray(new String[HibernateUtil.getSearchFields().size()]), new Standardreplacedyzer());
    try {
        Query q = parser.parse(query);
        newFrom = from;
        boolean more = true;
        while (more && results.size() < PAGE_SIZE) {
            more = addResults(q, fullTextSession, newFrom);
        }
    } catch (Exception e) {
        Manager.getLogger("Search").error("Failed to run search", e);
    }
    return results;
}

18 View Complete Implementation : HibernateSearchAtopOgmTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Test
public void testHibernateSearchNativeAPIUsage() throws Exception {
    final EnreplacedyManager enreplacedyManager = getFactory().createEnreplacedyManager();
    final FullTextSession ftSession = org.hibernate.search.Search.getFullTextSession(enreplacedyManager.unwrap(Session.clreplaced));
    enreplacedyManager.getTransaction().begin();
    final Insurance insurance = new Insurance();
    insurance.setName("Macif");
    ftSession.persist(insurance);
    enreplacedyManager.getTransaction().commit();
    ftSession.clear();
    enreplacedyManager.getTransaction().begin();
    final QueryBuilder b = ftSession.getSearchFactory().buildQueryBuilder().forEnreplacedy(Insurance.clreplaced).get();
    final Query lq = b.keyword().onField("name").matching("Macif").createQuery();
    final org.hibernate.search.FullTextQuery ftQuery = ftSession.createFullTextQuery(lq, Insurance.clreplaced);
    final List<Insurance> resultList = ftQuery.list();
    replacedertThat(getFactory().getPersistenceUnitUtil().isLoaded(resultList.get(0))).isTrue();
    replacedertThat(resultList).hreplacedize(1);
    for (Object e : resultList) {
        ftSession.delete(e);
    }
    enreplacedyManager.getTransaction().commit();
    enreplacedyManager.close();
}

18 View Complete Implementation : SearchOnStandaloneOGMTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Test
public void testHibernateSearchJPAAPIUsage() throws Exception {
    final Session session = openSession();
    Transaction transaction = session.beginTransaction();
    final FullTextSession fts = Search.getFullTextSession(session);
    final Insurance insurance = new Insurance();
    insurance.setName("Macif");
    fts.persist(insurance);
    transaction.commit();
    fts.clear();
    transaction = fts.beginTransaction();
    final QueryBuilder b = fts.getSearchFactory().buildQueryBuilder().forEnreplacedy(Insurance.clreplaced).get();
    final Query lq = b.keyword().onField("name").matching("Macif").createQuery();
    final FullTextQuery ftQuery = fts.createFullTextQuery(lq, Insurance.clreplaced);
    final List<Insurance> resultList = ftQuery.list();
    replacedertThat(resultList).hreplacedize(1);
    for (Object e : resultList) {
        fts.delete(e);
    }
    transaction.commit();
    fts.close();
}

18 View Complete Implementation : SimpleEntityMassIndexingTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Test
public void testSimpleEnreplacedyMreplacedIndexing() throws Exception {
    {
        Session session = openSession();
        Transaction transaction = session.beginTransaction();
        Insurance insurance = new Insurance();
        insurance.setName("Insurance Corporation");
        session.persist(insurance);
        transaction.commit();
        session.clear();
        session.close();
    }
    {
        purgeAll(Insurance.clreplaced);
        startAndWaitMreplacedIndexing(Insurance.clreplaced);
    }
    {
        FullTextSession session = Search.getFullTextSession(openSession());
        QueryBuilder queryBuilder = session.getSearchFactory().buildQueryBuilder().forEnreplacedy(Insurance.clreplaced).get();
        Query luceneQuery = queryBuilder.keyword().wildcard().onField("name").matching("ins*").createQuery();
        Transaction transaction = session.beginTransaction();
        @SuppressWarnings("unchecked")
        List<Insurance> list = session.createFullTextQuery(luceneQuery).list();
        replacedertThat(list).hreplacedize(1);
        replacedertThat(list.get(0).getName()).isEqualTo("Insurance Corporation");
        transaction.commit();
        session.clear();
        session.close();
    }
}

18 View Complete Implementation : SimpleEntityMassIndexingTest.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Test
@SkipByGridDialect(value = { MONGODB }, comment = "Uses embedded key which is currently not supported by the db query parsers")
public void testEnreplacedyWithCompositeIdMreplacedIndexing() throws Exception {
    {
        Session session = openSession();
        Transaction transaction = session.beginTransaction();
        IndexedNews news = new IndexedNews(new NewsID("replacedle", "author"), "content");
        session.persist(news);
        transaction.commit();
        session.clear();
        session.close();
    }
    {
        purgeAll(IndexedNews.clreplaced);
        startAndWaitMreplacedIndexing(IndexedNews.clreplaced);
    }
    {
        // replacedert index creation
        FullTextSession session = Search.getFullTextSession(openSession());
        QueryBuilder queryBuilder = session.getSearchFactory().buildQueryBuilder().forEnreplacedy(IndexedNews.clreplaced).get();
        Query luceneQuery = queryBuilder.keyword().wildcard().onField("newsId").ignoreFieldBridge().matching("replaced*").createQuery();
        Transaction transaction = session.beginTransaction();
        @SuppressWarnings("unchecked")
        List<IndexedNews> list = session.createFullTextQuery(luceneQuery).list();
        replacedertThat(list).hreplacedize(1);
        replacedertThat(list.get(0).getContent()).isEqualTo("content");
        replacedertThat(list.get(0).getNewsId().getreplacedle()).isEqualTo("replacedle");
        replacedertThat(list.get(0).getNewsId().getAuthor()).isEqualTo("author");
        transaction.commit();
        session.clear();
        session.close();
    }
}

18 View Complete Implementation : SharedIndexTest.java
Copyright Apache License 2.0
Author : infinispan
private void verifyResult(FullTextSessionBuilder node) {
    FullTextSession fullTextSession = node.openFullTextSession();
    try {
        Transaction transaction = fullTextSession.beginTransaction();
        QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEnreplacedy(Toaster.clreplaced).get();
        Query query = queryBuilder.keyword().onField("serialNumber").matching("A1").createQuery();
        List list = fullTextSession.createFullTextQuery(query).getResultList();
        replacedertEquals(1, list.size());
        Device device = (Device) list.get(0);
        replacedertEquals("GE", device.manufacturer);
        transaction.commit();
    } finally {
        fullTextSession.close();
    }
}

18 View Complete Implementation : TwoNodesTest.java
Copyright Apache License 2.0
Author : infinispan
private void verifyNodeSeesUpdatedIndex(FullTextSessionBuilder node) {
    FullTextSession fullTextSession = node.openFullTextSession();
    try {
        Transaction transaction = fullTextSession.beginTransaction();
        QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEnreplacedy(SimpleEmail.clreplaced).get();
        Query query = queryBuilder.keyword().onField("message").matching("Hibernate Getting Started").createQuery();
        List list = fullTextSession.createFullTextQuery(query).setProjection("message").getResultList();
        replacedertEquals(1, list.size());
        Object[] result = (Object[]) list.get(0);
        replacedertEquals(messageText, result[0]);
        transaction.commit();
    } finally {
        fullTextSession.close();
    }
}

18 View Complete Implementation : LuceneIndexerTask.java
Copyright Apache License 2.0
Author : mothsoft
@SuppressWarnings("unchecked")
@Transactional
public void execute() {
    final long start = System.currentTimeMillis();
    logger.info("Starting Lucene indexer...");
    final Session session = (Session) this.em.getDelegate();
    final FullTextSession fullTextSession = Search.getFullTextSession(session);
    int first = 0;
    final Query query = session.createQuery("FROM Doreplacedent d WHERE d.indexed = false");
    query.setFirstResult(first);
    query.setMaxResults(BATCH_SIZE);
    List<Doreplacedent> doreplacedents = query.list();
    while (!doreplacedents.isEmpty()) {
        for (final Doreplacedent doreplacedent : doreplacedents) {
            doreplacedent.setIndexed(true);
            fullTextSession.update(doreplacedent);
            fullTextSession.index(doreplacedent);
        }
        // next
        first += BATCH_SIZE;
        doreplacedents = query.list();
    }
    logger.info("Lucene indexing took: " + ((System.currentTimeMillis() - start) / 1000.00) + " seconds");
}

18 View Complete Implementation : RebuildIndexesServlet.java
Copyright GNU General Public License v2.0
Author : openkm
/**
 * FlushToIndexes implementation
 */
@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;
    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_FORCE_REBUILD_INDEXES", null, null, 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 enreplacedies
        for (Clreplaced cls : clreplacedes) {
            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 (Clreplaced cls : clreplacedes) {
            String nodeType = cls.getSimpleName();
            out.println("<li>Indexing " + nodeType + "</li>");
            out.flush();
            ProgressMonitor monitor = new ProgressMonitor(out, nodeType, 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.doreplacedentsAdded(1);
                // Index each element
                ftSession.index(results.get(0));
                if (index++ % Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS == 0) {
                    // Apply changes to indexes
                    ftSession.flushToIndexes();
                    // Free memory since the queue is processed
                    ftSession.clear();
                }
            }
        }
        tx.commit();
        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        out.println("<li>System out of maintenance mode</li>");
        out.flush();
        // Finalized
        out.println("<li>Index rebuilding completed!</li>");
        out.println("</ul>");
        out.flush();
    } catch (Exception e) {
        tx.rollback();
        FileLogger.error(BASE_NAME, StackTraceUtils.toString(e));
        out.println("<div clreplaced=\"warn\">Exception: " + e.getMessage() + "</div>");
        out.flush();
    } finally {
        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        HibernateUtil.close(ftSession);
        HibernateUtil.close(session);
    }
    // Finalized
    FileLogger.info(BASE_NAME, "END - Rebuild Lucene indexes");
    // End page
    footer(out);
    out.flush();
    out.close();
    log.debug("luceneIndexesFlushToIndexes: void");
}

18 View Complete Implementation : RebuildIndexesServlet.java
Copyright GNU General Public License v2.0
Author : openkm
/**
 * MreplacedIndexer implementation.
 */
@SuppressWarnings("rawtypes")
private void luceneIndexesMreplacedIndexer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    log.debug("luceneIndexesMreplacedIndexer({}, {})", 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;
    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_FORCE_REBUILD_INDEXES", null, null, 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);
        long total = 0;
        // Calculate number of enreplacedies
        for (Clreplaced cls : clreplacedes) {
            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 += partial;
        }
        // Rebuild indexes
        out.println("<li>Rebuilding indexes</li>");
        out.flush();
        ProgressMonitor monitor = new ProgressMonitor(out, "NodeBase", (int) total);
        ftSession.createIndexer().batchSizeToLoadObjects(Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS).threadsForSubsequentFetching(Config.HIBERNATE_INDEXER_THREADS_SUBSEQUENT_FETCHING).threadsToLoadObjects(Config.HIBERNATE_INDEXER_THREADS_LOAD_OBJECTS).threadsForIndexWriter(Config.HIBERNATE_INDEXER_THREADS_INDEX_WRITER).cacheMode(// defaults to CacheMode.IGNORE
        CacheMode.NORMAL).progressMonitor(monitor).startAndWait();
        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        out.println("<li>System out of maintenance mode</li>");
        out.flush();
        // Finalized
        out.println("<li>Index rebuilding completed!</li>");
        out.println("</ul>");
        out.flush();
    } catch (Exception e) {
        FileLogger.error(BASE_NAME, StackTraceUtils.toString(e));
        out.println("<div clreplaced=\"warn\">Exception: " + e.getMessage() + "</div>");
        out.flush();
    } finally {
        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        HibernateUtil.close(ftSession);
        HibernateUtil.close(session);
    }
    // Finalized
    FileLogger.info(BASE_NAME, "END - Rebuild Lucene indexes");
    // End page
    footer(out);
    out.flush();
    out.close();
    log.debug("luceneIndexesMreplacedIndexer: void");
}

18 View Complete Implementation : IndexerAction.java
Copyright GNU Affero General Public License v3.0
Author : RestComm
@SuppressWarnings("unchecked")
private void indexAllClreplacedes(Clreplaced... enreplacedyTypes) {
    FullTextSession fullTextSession = getFullTextSession();
    for (Clreplaced enreplacedyType : enreplacedyTypes) {
        for (Object obj : fullTextSession.createCriteria(enreplacedyType).list()) {
            fullTextSession.index(obj);
        }
    }
}

18 View Complete Implementation : IndexerAction.java
Copyright GNU Affero General Public License v3.0
Author : RestComm
@SuppressWarnings("unchecked")
private void indexProducts() {
    FullTextSession fullTextSession = getFullTextSession();
    List results = fullTextSession.createCriteria(Product.clreplaced).setFetchMode("actors", FetchMode.JOIN).setFetchMode("categories", FetchMode.JOIN).list();
    for (Object obj : results) {
        fullTextSession.index(obj);
    }
}

18 View Complete Implementation : IndexRequestMasterListener.java
Copyright Apache License 2.0
Author : servicecatalog
private void handleObjectIndexing(Object parameter) {
    Session session = getSession();
    if (parameter == null || session == null) {
        return;
    }
    FullTextSession fts = Search.getFullTextSession(session);
    Transaction tx = fts.beginTransaction();
    fts.index(parameter);
    tx.commit();
}