1 package org.apache.maven.archiva.indexer.search;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.List;
26 import org.apache.lucene.document.Document;
27 import org.apache.lucene.queryParser.MultiFieldQueryParser;
28 import org.apache.lucene.queryParser.ParseException;
29 import org.apache.lucene.queryParser.QueryParser;
30 import org.apache.lucene.search.BooleanClause;
31 import org.apache.lucene.search.BooleanQuery;
32 import org.apache.lucene.search.Filter;
33 import org.apache.lucene.search.Hits;
34 import org.apache.lucene.search.MultiSearcher;
35 import org.apache.lucene.search.Query;
36 import org.apache.lucene.search.QueryWrapperFilter;
37 import org.apache.lucene.search.Searchable;
38 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
39 import org.apache.maven.archiva.configuration.ConfigurationNames;
40 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
41 import org.apache.maven.archiva.indexer.ArtifactKeys;
42 import org.apache.maven.archiva.indexer.RepositoryContentIndex;
43 import org.apache.maven.archiva.indexer.RepositoryContentIndexFactory;
44 import org.apache.maven.archiva.indexer.RepositoryIndexException;
45 import org.apache.maven.archiva.indexer.RepositoryIndexSearchException;
46 import org.apache.maven.archiva.indexer.bytecode.BytecodeHandlers;
47 import org.apache.maven.archiva.indexer.bytecode.BytecodeKeys;
48 import org.apache.maven.archiva.indexer.filecontent.FileContentHandlers;
49 import org.apache.maven.archiva.indexer.hashcodes.HashcodesHandlers;
50 import org.apache.maven.archiva.indexer.hashcodes.HashcodesKeys;
51 import org.apache.maven.archiva.indexer.lucene.LuceneEntryConverter;
52 import org.apache.maven.archiva.indexer.lucene.LuceneQuery;
53 import org.apache.maven.archiva.indexer.lucene.LuceneRepositoryContentRecord;
54 import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
55 import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
56 import org.codehaus.plexus.registry.Registry;
57 import org.codehaus.plexus.registry.RegistryListener;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * DefaultCrossRepositorySearch
65 * @plexus.component role="org.apache.maven.archiva.indexer.search.CrossRepositorySearch" role-hint="default"
67 public class DefaultCrossRepositorySearch
68 implements CrossRepositorySearch, RegistryListener, Initializable
70 private Logger log = LoggerFactory.getLogger( DefaultCrossRepositorySearch.class );
73 * @plexus.requirement role-hint="lucene"
75 private RepositoryContentIndexFactory indexFactory;
80 private ArchivaConfiguration configuration;
82 private final List<ManagedRepositoryConfiguration> localIndexedRepositories = new ArrayList<ManagedRepositoryConfiguration>();
84 public SearchResults executeFilteredSearch( String principal, List<String> selectedRepos, String groupId,
85 String artifactId, String version, String className,
86 SearchResultLimits limits )
88 List<RepositoryContentIndex> indexes = getBytecodeIndexes( principal, selectedRepos );
89 SearchResults results = new SearchResults();
90 List<String> fieldsList = new ArrayList<String>();
91 List<String> termsList = new ArrayList<String>();
92 List<BooleanClause.Occur> flagsList = new ArrayList<BooleanClause.Occur>();
94 if( groupId != null && !"".equals( groupId.trim() ) )
96 fieldsList.add( ArtifactKeys.GROUPID );
97 termsList.add( groupId );
98 flagsList.add( BooleanClause.Occur.MUST );
101 if( artifactId != null && !"".equals( artifactId.trim() ) )
103 fieldsList.add( ArtifactKeys.ARTIFACTID );
104 termsList.add( artifactId );
105 flagsList.add( BooleanClause.Occur.MUST );
108 if( version != null && !"".equals( version.trim() ) )
110 fieldsList.add( ArtifactKeys.VERSION );
111 termsList.add( version );
112 flagsList.add( BooleanClause.Occur.MUST );
115 if( className != null && !"".equals( className.trim() ) )
117 fieldsList.add( BytecodeKeys.CLASSES );
118 fieldsList.add( BytecodeKeys.FILES );
119 fieldsList.add( BytecodeKeys.METHODS );
120 termsList.add( className.trim() );
121 termsList.add( className.trim() );
122 termsList.add( className.trim() );
123 flagsList.add( BooleanClause.Occur.SHOULD );
124 flagsList.add( BooleanClause.Occur.SHOULD );
125 flagsList.add( BooleanClause.Occur.SHOULD );
130 String[] fieldsArr = new String[ fieldsList.size() ];
131 String[] queryArr = new String[ termsList.size() ];
132 BooleanClause.Occur[] flagsArr = new BooleanClause.Occur[ flagsList.size() ];
135 MultiFieldQueryParser.parse( termsList.toArray( queryArr ), fieldsList.toArray( fieldsArr ),
136 flagsList.toArray( flagsArr ), new BytecodeHandlers().getAnalyzer() );
138 LuceneQuery query = new LuceneQuery( fieldsQuery );
139 results = searchAll( query, limits, indexes, null );
140 results.getRepositories().add( this.localIndexedRepositories );
142 catch ( ParseException e )
144 log.warn( "Unable to parse advanced search fields and query terms." );
150 public SearchResults searchForChecksum( String principal, List<String> selectedRepos, String checksum,
151 SearchResultLimits limits )
153 List<RepositoryContentIndex> indexes = getHashcodeIndexes( principal, selectedRepos );
157 QueryParser parser = new MultiFieldQueryParser( new String[]{HashcodesKeys.MD5, HashcodesKeys.SHA1},
158 new HashcodesHandlers().getAnalyzer() );
159 LuceneQuery query = new LuceneQuery( parser.parse( checksum ) );
160 SearchResults results = searchAll( query, limits, indexes, null );
161 results.getRepositories().addAll( this.localIndexedRepositories );
165 catch ( ParseException e )
167 log.warn( "Unable to parse query [" + checksum + "]: " + e.getMessage(), e );
171 return new SearchResults();
174 public SearchResults searchForBytecode( String principal, List<String> selectedRepos, String term, SearchResultLimits limits )
176 List<RepositoryContentIndex> indexes = getBytecodeIndexes( principal, selectedRepos );
180 QueryParser parser = new BytecodeHandlers().getQueryParser();
181 LuceneQuery query = new LuceneQuery( parser.parse( term ) );
182 SearchResults results = searchAll( query, limits, indexes, null );
183 results.getRepositories().addAll( this.localIndexedRepositories );
187 catch ( ParseException e )
189 log.warn( "Unable to parse query [" + term + "]: " + e.getMessage(), e );
193 return new SearchResults();
196 public SearchResults searchForTerm( String principal, List<String> selectedRepos, String term, SearchResultLimits limits )
198 return searchForTerm( principal, selectedRepos, term, limits, null );
201 public SearchResults searchForTerm( String principal, List<String> selectedRepos, String term,
202 SearchResultLimits limits, List<String> previousSearchTerms )
204 List<RepositoryContentIndex> indexes = getFileContentIndexes( principal, selectedRepos );
208 QueryParser parser = new FileContentHandlers().getQueryParser();
209 LuceneQuery query = null;
210 SearchResults results = null;
211 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
213 query = new LuceneQuery( parser.parse( term ) );
214 results = searchAll( query, limits, indexes, null );
218 // AND the previous search terms
219 BooleanQuery booleanQuery = new BooleanQuery();
220 for ( String previousSearchTerm : previousSearchTerms )
222 booleanQuery.add( parser.parse( previousSearchTerm ), BooleanClause.Occur.MUST );
225 query = new LuceneQuery( booleanQuery );
226 Filter filter = new QueryWrapperFilter( parser.parse( term ) );
227 results = searchAll( query, limits, indexes, filter );
229 results.getRepositories().addAll( this.localIndexedRepositories );
233 catch ( ParseException e )
235 log.warn( "Unable to parse query [" + term + "]: " + e.getMessage(), e );
239 return new SearchResults();
242 private SearchResults searchAll( LuceneQuery luceneQuery, SearchResultLimits limits, List<RepositoryContentIndex> indexes, Filter filter )
244 org.apache.lucene.search.Query specificQuery = luceneQuery.getLuceneQuery();
246 SearchResults results = new SearchResults();
248 if ( indexes.isEmpty() )
250 // No point going any further.
254 // Setup the converter
255 LuceneEntryConverter converter = null;
256 RepositoryContentIndex index = indexes.get( 0 );
257 converter = index.getEntryConverter();
259 // Process indexes into an array of Searchables.
260 List<Searchable> searchableList = toSearchables( indexes );
262 Searchable searchables[] = new Searchable[searchableList.size()];
263 searchableList.toArray( searchables );
265 MultiSearcher searcher = null;
269 // Create a multi-searcher for looking up the information.
270 searcher = new MultiSearcher( searchables );
272 // Perform the search.
274 if ( filter != null )
276 hits = searcher.search( specificQuery, filter );
280 hits = searcher.search( specificQuery );
283 int hitCount = hits.length();
285 // Now process the limits.
286 results.setLimits( limits );
287 results.setTotalHits( hitCount );
289 int fetchCount = limits.getPageSize();
290 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
292 if ( limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
294 fetchCount = hitCount;
299 if ( offset < hitCount )
301 // only process if the offset is within the hit count.
302 for ( int i = 0; i < fetchCount; i++ )
304 // Stop fetching if we are past the total # of available hits.
305 if ( offset + i >= hitCount )
312 Document doc = hits.doc( offset + i );
313 LuceneRepositoryContentRecord record = converter.convert( doc );
314 results.addHit( record );
316 catch ( java.text.ParseException e )
318 log.warn( "Unable to parse document into record: " + e.getMessage(), e );
324 catch ( IOException e )
326 log.error( "Unable to setup multi-search: " + e.getMessage(), e );
332 if ( searcher != null )
337 catch ( IOException ie )
339 log.error( "Unable to close index searcher: " + ie.getMessage(), ie );
346 private List<Searchable> toSearchables( List<RepositoryContentIndex> indexes )
348 List<Searchable> searchableList = new ArrayList<Searchable>();
349 for ( RepositoryContentIndex contentIndex : indexes )
353 searchableList.add( contentIndex.getSearchable() );
355 catch ( RepositoryIndexSearchException e )
357 log.warn( "Unable to get searchable for index [" + contentIndex.getId() + "] :"
358 + e.getMessage(), e );
361 return searchableList;
364 public List<RepositoryContentIndex> getBytecodeIndexes( String principal, List<String> selectedRepos )
366 List<RepositoryContentIndex> ret = new ArrayList<RepositoryContentIndex>();
368 for ( ManagedRepositoryConfiguration repoConfig : localIndexedRepositories )
370 // Only used selected repo
371 if ( selectedRepos.contains( repoConfig.getId() ) )
373 RepositoryContentIndex index = indexFactory.createBytecodeIndex( repoConfig );
375 if ( indexExists( index ) )
385 public List<RepositoryContentIndex> getFileContentIndexes( String principal, List<String> selectedRepos )
387 List<RepositoryContentIndex> ret = new ArrayList<RepositoryContentIndex>();
389 for ( ManagedRepositoryConfiguration repoConfig : localIndexedRepositories )
391 // Only used selected repo
392 if ( selectedRepos.contains( repoConfig.getId() ) )
394 RepositoryContentIndex index = indexFactory.createFileContentIndex( repoConfig );
396 if ( indexExists( index ) )
406 public List<RepositoryContentIndex> getHashcodeIndexes( String principal, List<String> selectedRepos )
408 List<RepositoryContentIndex> ret = new ArrayList<RepositoryContentIndex>();
410 for ( ManagedRepositoryConfiguration repoConfig : localIndexedRepositories )
412 // Only used selected repo
413 if ( selectedRepos.contains( repoConfig.getId() ) )
415 RepositoryContentIndex index = indexFactory.createHashcodeIndex( repoConfig );
417 if ( indexExists( index ) )
427 private boolean indexExists( RepositoryContentIndex index )
431 return index.exists();
433 catch ( RepositoryIndexException e )
436 "Repository Content Index [" + index.getId() + "] for repository ["
437 + index.getRepository().getId() + "] does not exist yet in ["
438 + index.getIndexDirectory().getAbsolutePath() + "]." );
443 public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue )
445 if ( ConfigurationNames.isManagedRepositories( propertyName ) )
451 public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue )
453 /* Nothing to do here */
456 private void initRepositories()
458 synchronized ( this.localIndexedRepositories )
460 this.localIndexedRepositories.clear();
462 List<ManagedRepositoryConfiguration> repos = configuration.getConfiguration().getManagedRepositories();
463 for ( ManagedRepositoryConfiguration repo : repos )
465 if ( repo.isScanned() )
467 localIndexedRepositories.add( repo );
473 public void initialize()
474 throws InitializationException
477 configuration.addChangeListener( this );