1 package org.apache.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 org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
23 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
24 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
25 import org.apache.archiva.indexer.util.SearchUtil;
26 import org.apache.commons.lang.StringUtils;
27 import org.apache.lucene.search.BooleanClause.Occur;
28 import org.apache.lucene.search.BooleanQuery;
29 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
30 import org.apache.maven.archiva.configuration.Configuration;
31 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
32 import org.apache.maven.index.ArtifactInfo;
33 import org.apache.maven.index.FlatSearchRequest;
34 import org.apache.maven.index.FlatSearchResponse;
35 import org.apache.maven.index.MAVEN;
36 import org.apache.maven.index.NexusIndexer;
37 import org.apache.maven.index.OSGI;
38 import org.apache.maven.index.context.IndexCreator;
39 import org.apache.maven.index.context.IndexingContext;
40 import org.apache.maven.index.context.UnsupportedExistingLuceneIndexException;
41 import org.apache.maven.index.expr.StringSearchExpression;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.stereotype.Service;
46 import javax.inject.Inject;
48 import java.io.IOException;
49 import java.util.ArrayList;
50 import java.util.List;
55 * RepositorySearch implementation which uses the Nexus Indexer for searching.
57 @Service( "nexusSearch" )
58 public class NexusRepositorySearch
59 implements RepositorySearch
61 private Logger log = LoggerFactory.getLogger( getClass() );
63 private NexusIndexer indexer;
65 private ArchivaConfiguration archivaConfig;
67 private MavenIndexerUtils mavenIndexerUtils;
70 public NexusRepositorySearch( PlexusSisuBridge plexusSisuBridge, ArchivaConfiguration archivaConfig,
71 MavenIndexerUtils mavenIndexerUtils )
72 throws PlexusSisuBridgeException
74 this.indexer = plexusSisuBridge.lookup( NexusIndexer.class );
75 this.archivaConfig = archivaConfig;
76 this.mavenIndexerUtils = mavenIndexerUtils;
81 * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
83 public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
84 List<String> previousSearchTerms )
85 throws RepositorySearchException
87 List<String> indexingContextIds = addIndexingContexts( selectedRepos );
89 // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
90 // resulting to more wildcard searches so we need to increase max clause count
91 BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
92 BooleanQuery q = new BooleanQuery();
94 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
96 constructQuery( term, q );
100 for ( String previousTerm : previousSearchTerms )
102 BooleanQuery iQuery = new BooleanQuery();
103 constructQuery( previousTerm, iQuery );
105 q.add( iQuery, Occur.MUST );
108 BooleanQuery iQuery = new BooleanQuery();
109 constructQuery( term, iQuery );
110 q.add( iQuery, Occur.MUST );
113 return search( limits, q, indexingContextIds );
117 * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
119 public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
120 throws RepositorySearchException
122 if ( searchFields.getRepositories() == null )
124 throw new RepositorySearchException( "Repositories cannot be null." );
127 List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
129 BooleanQuery q = new BooleanQuery();
130 if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
132 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new StringSearchExpression( searchFields.getGroupId() ) ),
136 if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
139 indexer.constructQuery( MAVEN.ARTIFACT_ID, new StringSearchExpression( searchFields.getArtifactId() ) ),
143 if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
145 q.add( indexer.constructQuery( MAVEN.VERSION, new StringSearchExpression( searchFields.getVersion() ) ),
149 if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
151 q.add( indexer.constructQuery( MAVEN.PACKAGING, new StringSearchExpression( searchFields.getPackaging() ) ),
155 if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
158 indexer.constructQuery( MAVEN.CLASSNAMES, new StringSearchExpression( searchFields.getClassName() ) ),
162 if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
164 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
165 new StringSearchExpression( searchFields.getBundleSymbolicName() ) ),
169 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
172 indexer.constructQuery( OSGI.VERSION, new StringSearchExpression( searchFields.getBundleVersion() ) ),
176 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
178 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
179 new StringSearchExpression( searchFields.getBundleExportPackage() ) ),
183 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
185 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
186 new StringSearchExpression( searchFields.getBundleExportService() ) ),
190 if ( q.getClauses() == null || q.getClauses().length <= 0 )
192 throw new RepositorySearchException( "No search fields set." );
195 return search( limits, q, indexingContextIds );
198 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds )
199 throws RepositorySearchException
203 FlatSearchRequest request = new FlatSearchRequest( q );
204 request.setContexts( getIndexingContexts( indexingContextIds ) );
205 FlatSearchResponse response = indexer.searchFlat( request );
207 if ( response == null || response.getTotalHits() == 0 )
209 SearchResults results = new SearchResults();
210 results.setLimits( limits );
214 return convertToSearchResults( response, limits );
216 catch ( IOException e )
218 throw new RepositorySearchException( e );
221 olamy : don't understand why this ?? it remove content from index ??
222 comment until someone explain WTF ?? :-))
225 Map<String, IndexingContext> indexingContexts = indexer.getIndexingContexts();
227 for ( Map.Entry<String, IndexingContext> entry : indexingContexts.entrySet() )
231 indexer.removeIndexingContext( entry.getValue(), false );
232 log.debug( "Indexing context '{}' removed from search.", entry.getKey() );
234 catch ( IOException e )
236 log.warn( "IOException occurred while removing indexing content '" + entry.getKey() + "'." );
243 private List<IndexingContext> getIndexingContexts( List<String> ids )
245 List<IndexingContext> contexts = new ArrayList<IndexingContext>( ids.size() );
247 for ( String id : ids )
249 IndexingContext context = indexer.getIndexingContexts().get( id );
250 if ( context != null )
252 contexts.add( context );
256 log.warn( "context with id {} not exists", id );
263 private void constructQuery( String term, BooleanQuery q )
265 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new StringSearchExpression( term ) ), Occur.SHOULD );
266 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new StringSearchExpression( term ) ), Occur.SHOULD );
267 q.add( indexer.constructQuery( MAVEN.VERSION, new StringSearchExpression( term ) ), Occur.SHOULD );
268 q.add( indexer.constructQuery( MAVEN.PACKAGING, new StringSearchExpression( term ) ), Occur.SHOULD );
269 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new StringSearchExpression( term ) ), Occur.SHOULD );
270 // olamy IMHO we could set this option as at least one must match
271 //q.setMinimumNumberShouldMatch( 1 );
276 * @param selectedRepos
277 * @return indexing contextId used
279 private List<String> addIndexingContexts( List<String> selectedRepos )
281 List<String> indexingContextIds = new ArrayList<String>();
282 for ( String repo : selectedRepos )
286 Configuration config = archivaConfig.getConfiguration();
287 ManagedRepositoryConfiguration repoConfig = config.findManagedRepositoryById( repo );
289 if ( repoConfig != null )
291 String indexDir = repoConfig.getIndexDir();
292 File indexDirectory = null;
293 if ( indexDir != null && !"".equals( indexDir ) )
295 indexDirectory = new File( repoConfig.getIndexDir() );
299 indexDirectory = new File( repoConfig.getLocation(), ".indexer" );
302 IndexingContext context = indexer.getIndexingContexts().get( repoConfig.getId() );
303 if ( context != null )
305 // alreday here so no need to record it again
306 log.debug( "index with id {} already exists skip adding it", repoConfig.getId() );
307 // set searchable flag
308 context.setSearchable( repoConfig.isScanned() );
309 indexingContextIds.add( context.getId() );
313 context = indexer.addIndexingContext( repoConfig.getId(), repoConfig.getId(),
314 new File( repoConfig.getLocation() ), indexDirectory, null,
315 null, getAllIndexCreators() );
316 context.setSearchable( repoConfig.isScanned() );
317 if ( context.isSearchable() )
319 indexingContextIds.add( context.getId() );
323 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
329 log.warn( "Repository '" + repo + "' not found in configuration." );
332 catch ( UnsupportedExistingLuceneIndexException e )
334 log.warn( "Error accessing index of repository '" + repo + "' : " + e.getMessage() );
337 catch ( IOException e )
339 log.warn( "IO error occured while accessing index of repository '" + repo + "' : " + e.getMessage() );
343 return indexingContextIds;
347 protected List<? extends IndexCreator> getAllIndexCreators()
349 return mavenIndexerUtils.getAllIndexCreators();
353 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits )
355 SearchResults results = new SearchResults();
356 Set<ArtifactInfo> artifactInfos = response.getResults();
358 for ( ArtifactInfo artifactInfo : artifactInfos )
360 String id = SearchUtil.getHitId( artifactInfo.groupId, artifactInfo.artifactId );
361 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
363 SearchResultHit hit = hitsMap.get( id );
366 if ( !hit.getVersions().contains( artifactInfo.version ) )
368 hit.addVersion( artifactInfo.version );
373 hit = new SearchResultHit();
374 hit.setArtifactId( artifactInfo.artifactId );
375 hit.setGroupId( artifactInfo.groupId );
376 // do we still need to set the repository id even though we're merging everything?
377 //hit.setRepositoryId( artifactInfo.repository );
378 hit.setUrl( artifactInfo.repository + "/" + artifactInfo.fname );
379 hit.addVersion( artifactInfo.version );
380 hit.setBundleExportPackage( artifactInfo.bundleExportPackage );
381 hit.setBundleExportService( artifactInfo.bundleExportService );
382 hit.setBundleSymbolicName( artifactInfo.bundleSymbolicName );
383 hit.setBundleVersion( artifactInfo.bundleVersion );
386 results.addHit( id, hit );
389 results.setTotalHits( response.getTotalHitsCount() );
390 results.setReturnedHitsCount( response.getReturnedHitsCount() );
391 results.setLimits( limits );
393 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
399 return paginate( results );
403 private SearchResults paginate( SearchResults results )
405 SearchResultLimits limits = results.getLimits();
406 SearchResults paginated = new SearchResults();
408 int fetchCount = limits.getPageSize();
409 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
411 if ( fetchCount > results.getTotalHits() )
413 fetchCount = results.getTotalHits();
417 if ( offset < results.getTotalHits() )
419 // only process if the offset is within the hit count.
420 for ( int i = 0; i < fetchCount; i++ )
422 // Stop fetching if we are past the total # of available hits.
423 if ( offset + i >= results.getHits().size() )
428 SearchResultHit hit = results.getHits().get( ( offset + i ) );
431 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId() );
432 paginated.addHit( id, hit );
440 paginated.setTotalHits( results.getTotalHits() );
441 paginated.setReturnedHitsCount( paginated.getHits().size() );
442 paginated.setLimits( limits );