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.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.beans.ManagedRepository;
24 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
25 import org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
26 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
27 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
28 import org.apache.archiva.indexer.util.SearchUtil;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.lucene.search.BooleanClause.Occur;
31 import org.apache.lucene.search.BooleanQuery;
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.Collections;
51 import java.util.List;
56 * RepositorySearch implementation which uses the Nexus Indexer for searching.
58 @Service( "nexusSearch" )
59 public class NexusRepositorySearch
60 implements RepositorySearch
62 private Logger log = LoggerFactory.getLogger( getClass() );
64 private NexusIndexer indexer;
66 private ManagedRepositoryAdmin managedRepositoryAdmin;
68 private MavenIndexerUtils mavenIndexerUtils;
71 public NexusRepositorySearch( PlexusSisuBridge plexusSisuBridge, ManagedRepositoryAdmin managedRepositoryAdmin,
72 MavenIndexerUtils mavenIndexerUtils )
73 throws PlexusSisuBridgeException
75 this.indexer = plexusSisuBridge.lookup( NexusIndexer.class );
76 this.managedRepositoryAdmin = managedRepositoryAdmin;
77 this.mavenIndexerUtils = mavenIndexerUtils;
82 * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
84 public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
85 List<String> previousSearchTerms )
86 throws RepositorySearchException
88 List<String> indexingContextIds = addIndexingContexts( selectedRepos );
90 // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
91 // resulting to more wildcard searches so we need to increase max clause count
92 BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
93 BooleanQuery q = new BooleanQuery();
95 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
97 constructQuery( term, q );
101 for ( String previousTerm : previousSearchTerms )
103 BooleanQuery iQuery = new BooleanQuery();
104 constructQuery( previousTerm, iQuery );
106 q.add( iQuery, Occur.MUST );
109 BooleanQuery iQuery = new BooleanQuery();
110 constructQuery( term, iQuery );
111 q.add( iQuery, Occur.MUST );
114 // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
115 // FIXME cannot find a way currently to setup this in constructQuery !!!
116 return search( limits, q, indexingContextIds, NoClassifierArtifactInfoFiler.LIST );
121 * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
123 public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
124 throws RepositorySearchException
126 if ( searchFields.getRepositories() == null )
128 throw new RepositorySearchException( "Repositories cannot be null." );
131 List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
133 BooleanQuery q = new BooleanQuery();
134 if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
136 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new StringSearchExpression( searchFields.getGroupId() ) ),
140 if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
143 indexer.constructQuery( MAVEN.ARTIFACT_ID, new StringSearchExpression( searchFields.getArtifactId() ) ),
147 if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
149 q.add( indexer.constructQuery( MAVEN.VERSION, new StringSearchExpression( searchFields.getVersion() ) ),
153 if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
155 q.add( indexer.constructQuery( MAVEN.PACKAGING, new StringSearchExpression( searchFields.getPackaging() ) ),
159 if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
162 indexer.constructQuery( MAVEN.CLASSNAMES, new StringSearchExpression( searchFields.getClassName() ) ),
166 if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
168 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
169 new StringSearchExpression( searchFields.getBundleSymbolicName() ) ),
173 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
176 indexer.constructQuery( OSGI.VERSION, new StringSearchExpression( searchFields.getBundleVersion() ) ),
180 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
182 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
183 new StringSearchExpression( searchFields.getBundleExportPackage() ) ),
187 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
189 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
190 new StringSearchExpression( searchFields.getBundleExportService() ) ),
194 if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
197 indexer.constructQuery( MAVEN.CLASSIFIER, new StringSearchExpression( searchFields.getClassifier() ) ),
201 if ( q.getClauses() == null || q.getClauses().length <= 0 )
203 throw new RepositorySearchException( "No search fields set." );
206 return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFiler>emptyList() );
209 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
210 List<? extends ArtifactInfoFiler> filters )
211 throws RepositorySearchException
216 FlatSearchRequest request = new FlatSearchRequest( q );
217 request.setContexts( getIndexingContexts( indexingContextIds ) );
218 FlatSearchResponse response = indexer.searchFlat( request );
220 if ( response == null || response.getTotalHits() == 0 )
222 SearchResults results = new SearchResults();
223 results.setLimits( limits );
227 return convertToSearchResults( response, limits, filters );
229 catch ( IOException e )
231 throw new RepositorySearchException( e );
234 olamy : don't understand why this ?? it remove content from index ??
235 comment until someone explain WTF ?? :-))
238 Map<String, IndexingContext> indexingContexts = indexer.getIndexingContexts();
240 for ( Map.Entry<String, IndexingContext> entry : indexingContexts.entrySet() )
244 indexer.removeIndexingContext( entry.getValue(), false );
245 log.debug( "Indexing context '{}' removed from search.", entry.getKey() );
247 catch ( IOException e )
249 log.warn( "IOException occurred while removing indexing content '" + entry.getKey() + "'." );
256 private List<IndexingContext> getIndexingContexts( List<String> ids )
258 List<IndexingContext> contexts = new ArrayList<IndexingContext>( ids.size() );
260 for ( String id : ids )
262 IndexingContext context = indexer.getIndexingContexts().get( id );
263 if ( context != null )
265 contexts.add( context );
269 log.warn( "context with id {} not exists", id );
276 private void constructQuery( String term, BooleanQuery q )
278 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new StringSearchExpression( term ) ), Occur.SHOULD );
279 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new StringSearchExpression( term ) ), Occur.SHOULD );
280 q.add( indexer.constructQuery( MAVEN.VERSION, new StringSearchExpression( term ) ), Occur.SHOULD );
281 q.add( indexer.constructQuery( MAVEN.PACKAGING, new StringSearchExpression( term ) ), Occur.SHOULD );
282 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new StringSearchExpression( term ) ), Occur.SHOULD );
285 // new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
286 //q.add( query, Occur.MUST_NOT );
287 // olamy IMHO we could set this option as at least one must match
288 //q.setMinimumNumberShouldMatch( 1 );
293 * @param selectedRepos
294 * @return indexing contextId used
296 private List<String> addIndexingContexts( List<String> selectedRepos )
298 List<String> indexingContextIds = new ArrayList<String>();
299 for ( String repo : selectedRepos )
303 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
305 if ( repoConfig != null )
307 String indexDir = repoConfig.getIndexDirectory();
308 File indexDirectory = null;
309 if ( indexDir != null && !"".equals( indexDir ) )
311 indexDirectory = new File( repoConfig.getIndexDirectory() );
315 indexDirectory = new File( repoConfig.getLocation(), ".indexer" );
318 IndexingContext context = indexer.getIndexingContexts().get( repoConfig.getId() );
319 if ( context != null )
321 // alreday here so no need to record it again
322 log.debug( "index with id {} already exists skip adding it", repoConfig.getId() );
323 // set searchable flag
324 context.setSearchable( repoConfig.isScanned() );
325 indexingContextIds.add( context.getId() );
329 context = indexer.addIndexingContext( repoConfig.getId(), repoConfig.getId(),
330 new File( repoConfig.getLocation() ), indexDirectory, null,
331 null, getAllIndexCreators() );
332 context.setSearchable( repoConfig.isScanned() );
333 if ( context.isSearchable() )
335 indexingContextIds.add( context.getId() );
339 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
345 log.warn( "Repository '" + repo + "' not found in configuration." );
348 catch ( UnsupportedExistingLuceneIndexException e )
350 log.warn( "Error accessing index of repository '" + repo + "' : " + e.getMessage() );
353 catch ( IOException e )
355 log.warn( "IO error occured while accessing index of repository '" + repo + "' : " + e.getMessage() );
358 catch ( RepositoryAdminException e )
360 log.warn( "RepositoryAdminException occured while accessing index of repository '" + repo + "' : "
365 return indexingContextIds;
369 protected List<? extends IndexCreator> getAllIndexCreators()
371 return mavenIndexerUtils.getAllIndexCreators();
375 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
376 List<? extends ArtifactInfoFiler> artifactInfoFilers )
378 SearchResults results = new SearchResults();
379 Set<ArtifactInfo> artifactInfos = response.getResults();
381 for ( ArtifactInfo artifactInfo : artifactInfos )
383 String id = SearchUtil.getHitId( artifactInfo.groupId, artifactInfo.artifactId, artifactInfo.classifier,
384 artifactInfo.packaging );
385 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
387 if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilers, hitsMap ) )
392 SearchResultHit hit = hitsMap.get( id );
395 if ( !hit.getVersions().contains( artifactInfo.version ) )
397 hit.addVersion( artifactInfo.version );
402 hit = new SearchResultHit();
403 hit.setArtifactId( artifactInfo.artifactId );
404 hit.setGroupId( artifactInfo.groupId );
405 hit.setRepositoryId( artifactInfo.repository );
406 // FIXME archiva url ??
407 hit.setUrl( artifactInfo.repository + "/" + artifactInfo.fname );
408 hit.addVersion( artifactInfo.version );
409 hit.setBundleExportPackage( artifactInfo.bundleExportPackage );
410 hit.setBundleExportService( artifactInfo.bundleExportService );
411 hit.setBundleSymbolicName( artifactInfo.bundleSymbolicName );
412 hit.setBundleVersion( artifactInfo.bundleVersion );
413 hit.setBundleDescription( artifactInfo.bundleDescription );
414 hit.setBundleDocUrl( artifactInfo.bundleDocUrl );
416 hit.setBundleRequireBundle( artifactInfo.bundleRequireBundle );
417 hit.setBundleImportPackage( artifactInfo.bundleImportPackage );
418 hit.setBundleLicense( artifactInfo.bundleLicense );
419 hit.setBundleName( artifactInfo.bundleName );
420 hit.setContext( artifactInfo.context );
421 hit.setGoals( artifactInfo.goals );
422 hit.setPrefix( artifactInfo.prefix );
423 hit.setPackaging( artifactInfo.packaging );
424 hit.setClassifier( artifactInfo.classifier );
426 hit.setUrl( artifactInfo.remoteUrl );
429 results.addHit( id, hit );
432 results.setTotalHits( response.getTotalHitsCount() );
433 results.setReturnedHitsCount( response.getReturnedHitsCount() );
434 results.setLimits( limits );
436 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
442 return paginate( results );
446 private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
447 List<? extends ArtifactInfoFiler> artifactInfoFilers,
448 Map<String, SearchResultHit> currentResult )
450 if ( artifactInfoFilers == null || artifactInfoFilers.isEmpty() )
455 for ( ArtifactInfoFiler filter : artifactInfoFilers )
457 if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
465 private SearchResults paginate( SearchResults results )
467 SearchResultLimits limits = results.getLimits();
468 SearchResults paginated = new SearchResults();
470 int fetchCount = limits.getPageSize();
471 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
473 if ( fetchCount > results.getTotalHits() )
475 fetchCount = results.getTotalHits();
479 if ( offset < results.getTotalHits() )
481 // only process if the offset is within the hit count.
482 for ( int i = 0; i < fetchCount; i++ )
484 // Stop fetching if we are past the total # of available hits.
485 if ( offset + i >= results.getHits().size() )
490 SearchResultHit hit = results.getHits().get( ( offset + i ) );
493 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
494 hit.getPackaging() );
495 paginated.addHit( id, hit );
503 paginated.setTotalHits( results.getTotalHits() );
504 paginated.setReturnedHitsCount( paginated.getHits().size() );
505 paginated.setLimits( limits );