1 package org.apache.maven.index.context;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Iterator;
27 import java.util.List;
28
29 import org.apache.lucene.index.IndexReader;
30 import org.apache.lucene.index.MultiReader;
31 import org.apache.lucene.search.IndexSearcher;
32
33 public class NexusIndexMultiReader
34 {
35 private final List<IndexingContext> contexts;
36
37 private List<IndexSearcher> searchers;
38
39 public NexusIndexMultiReader( final Collection<IndexingContext> contexts )
40 {
41 this.contexts = Collections.unmodifiableList( new ArrayList<IndexingContext>( contexts ) );
42 }
43
44 public synchronized IndexReader acquire()
45 throws IOException
46 {
47 if ( searchers != null )
48 {
49 release();
50 throw new IllegalStateException( "acquire() called 2nd time without release() in between!" );
51 }
52 this.searchers = new ArrayList<IndexSearcher>();
53 final ArrayList<IndexReader> contextReaders = new ArrayList<IndexReader>( contexts.size() );
54 for ( IndexingContext ctx : contexts )
55 {
56 final IndexSearcher indexSearcher = ctx.acquireIndexSearcher();
57 searchers.add( indexSearcher );
58 contextReaders.add( indexSearcher.getIndexReader() );
59 }
60 return new MultiReader( contextReaders.toArray( new IndexReader[contextReaders.size()] ) );
61 }
62
63 public synchronized void release()
64 throws IOException
65 {
66 if ( searchers != null )
67 {
68 final Iterator<IndexingContext> ic = contexts.iterator();
69 final Iterator<IndexSearcher> is = searchers.iterator();
70
71 while ( ic.hasNext() && is.hasNext() )
72 {
73 ic.next().releaseIndexSearcher( is.next() );
74 }
75
76 if ( ic.hasNext() || is.hasNext() )
77 {
78 throw new IllegalStateException( "Context and IndexSearcher mismatch: " + contexts + " vs " + searchers );
79 }
80 }
81
82 searchers = null;
83 }
84
85
86
87
88
89
90
91 public synchronized List<IndexSearcher> getAcquiredSearchers()
92 {
93 return searchers;
94 }
95 }