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.beans.ProxyConnector;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin;
27 import org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
28 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
29 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
30 import org.apache.archiva.indexer.util.SearchUtil;
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.lucene.search.BooleanClause.Occur;
33 import org.apache.lucene.search.BooleanQuery;
34 import org.apache.maven.index.ArtifactInfo;
35 import org.apache.maven.index.FlatSearchRequest;
36 import org.apache.maven.index.FlatSearchResponse;
37 import org.apache.maven.index.MAVEN;
38 import org.apache.maven.index.NexusIndexer;
39 import org.apache.maven.index.OSGI;
40 import org.apache.maven.index.context.IndexCreator;
41 import org.apache.maven.index.context.IndexingContext;
42 import org.apache.maven.index.expr.SourcedSearchExpression;
43 import org.apache.maven.index.expr.UserInputSearchExpression;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.stereotype.Service;
48 import javax.inject.Inject;
49 import java.io.IOException;
50 import java.util.ArrayList;
51 import java.util.Collection;
52 import java.util.Collections;
53 import java.util.HashSet;
54 import java.util.List;
59 * RepositorySearch implementation which uses the Maven Indexer for searching.
61 @Service("repositorySearch#maven")
62 public class MavenRepositorySearch
63 implements RepositorySearch
65 private Logger log = LoggerFactory.getLogger( getClass() );
67 private NexusIndexer indexer;
69 private ManagedRepositoryAdmin managedRepositoryAdmin;
71 private ProxyConnectorAdmin proxyConnectorAdmin;
73 private MavenIndexerUtils mavenIndexerUtils;
75 protected MavenRepositorySearch()
81 public MavenRepositorySearch( PlexusSisuBridge plexusSisuBridge, ManagedRepositoryAdmin managedRepositoryAdmin,
82 MavenIndexerUtils mavenIndexerUtils, ProxyConnectorAdmin proxyConnectorAdmin )
83 throws PlexusSisuBridgeException
85 this.indexer = plexusSisuBridge.lookup( NexusIndexer.class );
86 this.managedRepositoryAdmin = managedRepositoryAdmin;
87 this.mavenIndexerUtils = mavenIndexerUtils;
88 this.proxyConnectorAdmin = proxyConnectorAdmin;
92 * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
94 public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
95 List<String> previousSearchTerms )
96 throws RepositorySearchException
98 List<String> indexingContextIds = addIndexingContexts( selectedRepos );
100 // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
101 // resulting to more wildcard searches so we need to increase max clause count
102 BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
103 BooleanQuery q = new BooleanQuery();
105 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
107 constructQuery( term, q );
111 for ( String previousTerm : previousSearchTerms )
113 BooleanQuery iQuery = new BooleanQuery();
114 constructQuery( previousTerm, iQuery );
116 q.add( iQuery, Occur.MUST );
119 BooleanQuery iQuery = new BooleanQuery();
120 constructQuery( term, iQuery );
121 q.add( iQuery, Occur.MUST );
124 // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
125 // FIXME cannot find a way currently to setup this in constructQuery !!!
126 return search( limits, q, indexingContextIds, NoClassifierArtifactInfoFilter.LIST, selectedRepos, true );
131 * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
133 public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
134 throws RepositorySearchException
136 if ( searchFields.getRepositories() == null )
138 throw new RepositorySearchException( "Repositories cannot be null." );
141 List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
143 // if no index found in the specified ones return an empty search result instead of doing a search on all index
144 // olamy: IMHO doesn't make sense
145 if ( !searchFields.getRepositories().isEmpty() && ( indexingContextIds == null
146 || indexingContextIds.isEmpty() ) )
148 return new SearchResults();
151 BooleanQuery q = new BooleanQuery();
152 if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
154 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( searchFields.getGroupId() ) ),
158 if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
160 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID,
161 new UserInputSearchExpression( searchFields.getArtifactId() ) ),
165 if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
167 q.add( indexer.constructQuery( MAVEN.VERSION, new SourcedSearchExpression( searchFields.getVersion() ) ),
171 if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
174 indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( searchFields.getPackaging() ) ),
178 if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
180 q.add( indexer.constructQuery( MAVEN.CLASSNAMES,
181 new UserInputSearchExpression( searchFields.getClassName() ) ), Occur.MUST );
184 if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
186 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
187 new UserInputSearchExpression( searchFields.getBundleSymbolicName() ) ),
191 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
193 q.add( indexer.constructQuery( OSGI.VERSION,
194 new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
198 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
200 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
201 new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
205 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
207 q.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
208 new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
212 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
214 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
215 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
219 if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
221 q.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
225 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
227 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
228 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
232 if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
234 q.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
235 new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
239 if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
241 q.add( indexer.constructQuery( MAVEN.CLASSIFIER,
242 new UserInputSearchExpression( searchFields.getClassifier() ) ),
246 if ( q.getClauses() == null || q.getClauses().length <= 0 )
248 throw new RepositorySearchException( "No search fields set." );
251 return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
252 searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
255 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
256 List<? extends ArtifactInfoFilter> filters, List<String> selectedRepos,
257 boolean includePoms )
258 throws RepositorySearchException
263 FlatSearchRequest request = new FlatSearchRequest( q );
264 request.setContexts( getIndexingContexts( indexingContextIds ) );
266 FlatSearchResponse response = indexer.searchFlat( request );
268 if ( response == null || response.getTotalHits() == 0 )
270 SearchResults results = new SearchResults();
271 results.setLimits( limits );
275 return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
277 catch ( IOException e )
279 throw new RepositorySearchException( e.getMessage(), e );
281 catch ( RepositoryAdminException e )
283 throw new RepositorySearchException( e.getMessage(), e );
288 private List<IndexingContext> getIndexingContexts( List<String> ids )
290 List<IndexingContext> contexts = new ArrayList<IndexingContext>( ids.size() );
292 for ( String id : ids )
294 IndexingContext context = indexer.getIndexingContexts().get( id );
295 if ( context != null )
297 contexts.add( context );
301 log.warn( "context with id {} not exists", id );
308 private void constructQuery( String term, BooleanQuery q )
310 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
311 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
312 q.add( indexer.constructQuery( MAVEN.VERSION, new UserInputSearchExpression( term ) ), Occur.SHOULD );
313 q.add( indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( term ) ), Occur.SHOULD );
314 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new UserInputSearchExpression( term ) ), Occur.SHOULD );
317 // new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
318 //q.add( query, Occur.MUST_NOT );
319 // olamy IMHO we could set this option as at least one must match
320 //q.setMinimumNumberShouldMatch( 1 );
325 * @param selectedRepos
326 * @return indexing contextId used
328 private List<String> addIndexingContexts( List<String> selectedRepos )
330 Set<String> indexingContextIds = new HashSet<String>();
331 for ( String repo : selectedRepos )
335 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
337 if ( repoConfig != null )
340 IndexingContext context = managedRepositoryAdmin.createIndexContext( repoConfig );
341 if ( context.isSearchable() )
343 indexingContextIds.addAll( getRemoteIndexingContextIds( repo ) );
344 indexingContextIds.add( context.getId() );
348 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
354 log.warn( "Repository '{}' not found in configuration.", repo );
357 catch ( RepositoryAdminException e )
359 log.warn( "RepositoryAdminException occured while accessing index of repository '{}' : {}", repo,
365 return new ArrayList<String>( indexingContextIds );
369 public Set<String> getRemoteIndexingContextIds( String managedRepoId )
370 throws RepositoryAdminException
372 Set<String> ids = new HashSet<String>();
374 List<ProxyConnector> proxyConnectors = proxyConnectorAdmin.getProxyConnectorAsMap().get( managedRepoId );
376 if ( proxyConnectors == null || proxyConnectors.isEmpty() )
381 for ( ProxyConnector proxyConnector : proxyConnectors )
383 String remoteId = "remote-" + proxyConnector.getTargetRepoId();
384 IndexingContext context = indexer.getIndexingContexts().get( remoteId );
385 if ( context != null && context.isSearchable() )
394 public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
395 throws RepositorySearchException
397 List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
399 if ( indexContexts == null || indexContexts.isEmpty() )
401 return Collections.emptyList();
406 Set<String> allGroupIds = new HashSet<String>();
407 for ( IndexingContext indexingContext : indexContexts )
409 allGroupIds.addAll( indexingContext.getAllGroups() );
413 catch ( IOException e )
415 throw new RepositorySearchException( e.getMessage(), e );
421 protected List<? extends IndexCreator> getAllIndexCreators()
423 return mavenIndexerUtils.getAllIndexCreators();
427 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
428 List<? extends ArtifactInfoFilter> artifactInfoFilters,
429 List<String> selectedRepos, boolean includePoms )
430 throws RepositoryAdminException
432 SearchResults results = new SearchResults();
433 Set<ArtifactInfo> artifactInfos = response.getResults();
435 for ( ArtifactInfo artifactInfo : artifactInfos )
437 if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.fextension ) && !includePoms )
441 String id = SearchUtil.getHitId( artifactInfo.groupId, artifactInfo.artifactId, artifactInfo.classifier,
442 artifactInfo.packaging );
443 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
445 if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
450 SearchResultHit hit = hitsMap.get( id );
453 if ( !hit.getVersions().contains( artifactInfo.version ) )
455 hit.addVersion( artifactInfo.version );
460 hit = new SearchResultHit();
461 hit.setArtifactId( artifactInfo.artifactId );
462 hit.setGroupId( artifactInfo.groupId );
463 hit.setRepositoryId( artifactInfo.repository );
464 hit.addVersion( artifactInfo.version );
465 hit.setBundleExportPackage( artifactInfo.bundleExportPackage );
466 hit.setBundleExportService( artifactInfo.bundleExportService );
467 hit.setBundleSymbolicName( artifactInfo.bundleSymbolicName );
468 hit.setBundleVersion( artifactInfo.bundleVersion );
469 hit.setBundleDescription( artifactInfo.bundleDescription );
470 hit.setBundleDocUrl( artifactInfo.bundleDocUrl );
471 hit.setBundleRequireBundle( artifactInfo.bundleRequireBundle );
472 hit.setBundleImportPackage( artifactInfo.bundleImportPackage );
473 hit.setBundleLicense( artifactInfo.bundleLicense );
474 hit.setBundleName( artifactInfo.bundleName );
475 hit.setContext( artifactInfo.context );
476 hit.setGoals( artifactInfo.goals );
477 hit.setPrefix( artifactInfo.prefix );
478 hit.setPackaging( artifactInfo.packaging );
479 hit.setClassifier( artifactInfo.classifier );
480 hit.setFileExtension( artifactInfo.fextension );
481 hit.setUrl( getBaseUrl( artifactInfo, selectedRepos ) );
484 results.addHit( id, hit );
487 results.setTotalHits( response.getTotalHitsCount() );
488 results.setTotalHitsMapSize( results.getHitsMap().values().size() );
489 results.setReturnedHitsCount( response.getReturnedHitsCount() );
490 results.setLimits( limits );
492 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
498 return paginate( results );
503 * calculate baseUrl without the context and base Archiva Url
505 * @param artifactInfo
508 protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
509 throws RepositoryAdminException
511 StringBuilder sb = new StringBuilder();
512 if ( StringUtils.startsWith( artifactInfo.context, "remote-" ) )
514 // it's a remote index result we search a managed which proxying this remote and on which
515 // current user has read karma
516 String managedRepoId =
517 getManagedRepoId( StringUtils.substringAfter( artifactInfo.context, "remote-" ), selectedRepos );
518 if ( managedRepoId != null )
520 sb.append( '/' ).append( managedRepoId );
521 artifactInfo.context = managedRepoId;
526 sb.append( '/' ).append( artifactInfo.context );
529 sb.append( '/' ).append( StringUtils.replaceChars( artifactInfo.groupId, '.', '/' ) );
530 sb.append( '/' ).append( artifactInfo.artifactId );
531 sb.append( '/' ).append( artifactInfo.version );
532 sb.append( '/' ).append( artifactInfo.artifactId );
533 sb.append( '-' ).append( artifactInfo.version );
534 if ( StringUtils.isNotBlank( artifactInfo.classifier ) )
536 sb.append( '-' ).append( artifactInfo.classifier );
538 // maven-plugin packaging is a jar
539 if ( StringUtils.equals( "maven-plugin", artifactInfo.packaging ) )
545 sb.append( '.' ).append( artifactInfo.packaging );
548 return sb.toString();
552 * return a managed repo for a remote result
555 * @param selectedRepos
557 * @throws RepositoryAdminException
559 private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
560 throws RepositoryAdminException
562 Map<String, List<ProxyConnector>> proxyConnectorMap = proxyConnectorAdmin.getProxyConnectorAsMap();
563 if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
567 if ( selectedRepos != null && !selectedRepos.isEmpty() )
569 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
571 if ( selectedRepos.contains( entry.getKey() ) )
573 for ( ProxyConnector proxyConnector : entry.getValue() )
575 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
577 return proxyConnector.getSourceRepoId();
584 // we don't find in search selected repos so return the first one
585 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
588 for ( ProxyConnector proxyConnector : entry.getValue() )
590 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
592 return proxyConnector.getSourceRepoId();
600 private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
601 List<? extends ArtifactInfoFilter> artifactInfoFilters,
602 Map<String, SearchResultHit> currentResult )
604 if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
609 for ( ArtifactInfoFilter filter : artifactInfoFilters )
611 if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
619 protected SearchResults paginate( SearchResults results )
621 SearchResultLimits limits = results.getLimits();
622 SearchResults paginated = new SearchResults();
624 int fetchCount = limits.getPageSize();
625 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
627 if ( fetchCount > results.getTotalHits() )
629 fetchCount = results.getTotalHits();
633 if ( offset < results.getTotalHits() )
635 // only process if the offset is within the hit count.
636 for ( int i = 0; i < fetchCount; i++ )
638 // Stop fetching if we are past the total # of available hits.
639 if ( offset + i >= results.getHits().size() )
644 SearchResultHit hit = results.getHits().get( ( offset + i ) );
647 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
648 hit.getPackaging() );
649 paginated.addHit( id, hit );
657 paginated.setTotalHits( results.getTotalHits() );
658 paginated.setReturnedHitsCount( paginated.getHits().size() );
659 paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
660 paginated.setLimits( limits );