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)
95 public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
96 List<String> previousSearchTerms )
97 throws RepositorySearchException
99 List<String> indexingContextIds = addIndexingContexts( selectedRepos );
101 // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
102 // resulting to more wildcard searches so we need to increase max clause count
103 BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
104 BooleanQuery q = new BooleanQuery();
106 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
108 constructQuery( term, q );
112 for ( String previousTerm : previousSearchTerms )
114 BooleanQuery iQuery = new BooleanQuery();
115 constructQuery( previousTerm, iQuery );
117 q.add( iQuery, Occur.MUST );
120 BooleanQuery iQuery = new BooleanQuery();
121 constructQuery( term, iQuery );
122 q.add( iQuery, Occur.MUST );
125 // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
126 // FIXME cannot find a way currently to setup this in constructQuery !!!
127 return search( limits, q, indexingContextIds, NoClassifierArtifactInfoFilter.LIST, selectedRepos, true );
132 * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
135 public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
136 throws RepositorySearchException
138 if ( searchFields.getRepositories() == null )
140 throw new RepositorySearchException( "Repositories cannot be null." );
143 List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
145 // if no index found in the specified ones return an empty search result instead of doing a search on all index
146 // olamy: IMHO doesn't make sense
147 if ( !searchFields.getRepositories().isEmpty() && ( indexingContextIds == null
148 || indexingContextIds.isEmpty() ) )
150 return new SearchResults();
153 BooleanQuery q = new BooleanQuery();
154 if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
156 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( searchFields.getGroupId() ) ),
160 if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
162 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID,
163 new UserInputSearchExpression( searchFields.getArtifactId() ) ), Occur.MUST
167 if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
169 q.add( indexer.constructQuery( MAVEN.VERSION, new SourcedSearchExpression( searchFields.getVersion() ) ),
173 if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
176 indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( searchFields.getPackaging() ) ),
180 if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
182 q.add( indexer.constructQuery( MAVEN.CLASSNAMES,
183 new UserInputSearchExpression( searchFields.getClassName() ) ), Occur.MUST );
186 if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
188 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
189 new UserInputSearchExpression( searchFields.getBundleSymbolicName() ) ),
194 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
196 q.add( indexer.constructQuery( OSGI.VERSION,
197 new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
202 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
204 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
205 new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
210 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
212 q.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
213 new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
218 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
220 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
221 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
226 if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
228 q.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
232 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
234 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
235 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
240 if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
242 q.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
243 new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
248 if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
250 q.add( indexer.constructQuery( MAVEN.CLASSIFIER,
251 new UserInputSearchExpression( searchFields.getClassifier() ) ), Occur.MUST
255 if ( q.getClauses() == null || q.getClauses().length <= 0 )
257 throw new RepositorySearchException( "No search fields set." );
260 return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
261 searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
264 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
265 List<? extends ArtifactInfoFilter> filters, List<String> selectedRepos,
266 boolean includePoms )
267 throws RepositorySearchException
272 FlatSearchRequest request = new FlatSearchRequest( q );
274 request.setContexts( getIndexingContexts( indexingContextIds ) );
275 if ( limits != null )
277 // we apply limits only when first page asked
278 if ( limits.getSelectedPage() == 0 )
280 request.setCount( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
284 FlatSearchResponse response = indexer.searchFlat( request );
286 if ( response == null || response.getTotalHits() == 0 )
288 SearchResults results = new SearchResults();
289 results.setLimits( limits );
293 return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
295 catch ( IOException e )
297 throw new RepositorySearchException( e.getMessage(), e );
299 catch ( RepositoryAdminException e )
301 throw new RepositorySearchException( e.getMessage(), e );
306 private List<IndexingContext> getIndexingContexts( List<String> ids )
308 List<IndexingContext> contexts = new ArrayList<>( ids.size() );
310 for ( String id : ids )
312 IndexingContext context = indexer.getIndexingContexts().get( id );
313 if ( context != null )
315 contexts.add( context );
319 log.warn( "context with id {} not exists", id );
326 private void constructQuery( String term, BooleanQuery q )
328 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
329 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
330 q.add( indexer.constructQuery( MAVEN.VERSION, new UserInputSearchExpression( term ) ), Occur.SHOULD );
331 q.add( indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( term ) ), Occur.SHOULD );
332 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new UserInputSearchExpression( term ) ), Occur.SHOULD );
335 // new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
336 //q.add( query, Occur.MUST_NOT );
337 // olamy IMHO we could set this option as at least one must match
338 //q.setMinimumNumberShouldMatch( 1 );
343 * @param selectedRepos
344 * @return indexing contextId used
346 private List<String> addIndexingContexts( List<String> selectedRepos )
348 Set<String> indexingContextIds = new HashSet<>();
349 for ( String repo : selectedRepos )
353 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
355 if ( repoConfig != null )
358 IndexingContext context = managedRepositoryAdmin.createIndexContext( repoConfig );
359 if ( context.isSearchable() )
361 indexingContextIds.addAll( getRemoteIndexingContextIds( repo ) );
362 indexingContextIds.add( context.getId() );
366 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
372 log.warn( "Repository '{}' not found in configuration.", repo );
375 catch ( RepositoryAdminException e )
377 log.warn( "RepositoryAdminException occured while accessing index of repository '{}' : {}", repo,
383 return new ArrayList<>( indexingContextIds );
388 public Set<String> getRemoteIndexingContextIds( String managedRepoId )
389 throws RepositoryAdminException
391 Set<String> ids = new HashSet<>();
393 List<ProxyConnector> proxyConnectors = proxyConnectorAdmin.getProxyConnectorAsMap().get( managedRepoId );
395 if ( proxyConnectors == null || proxyConnectors.isEmpty() )
400 for ( ProxyConnector proxyConnector : proxyConnectors )
402 String remoteId = "remote-" + proxyConnector.getTargetRepoId();
403 IndexingContext context = indexer.getIndexingContexts().get( remoteId );
404 if ( context != null && context.isSearchable() )
414 public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
415 throws RepositorySearchException
417 List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
419 if ( indexContexts == null || indexContexts.isEmpty() )
421 return Collections.emptyList();
426 Set<String> allGroupIds = new HashSet<>();
427 for ( IndexingContext indexingContext : indexContexts )
429 allGroupIds.addAll( indexingContext.getAllGroups() );
433 catch ( IOException e )
435 throw new RepositorySearchException( e.getMessage(), e );
441 protected List<? extends IndexCreator> getAllIndexCreators()
443 return mavenIndexerUtils.getAllIndexCreators();
447 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
448 List<? extends ArtifactInfoFilter> artifactInfoFilters,
449 List<String> selectedRepos, boolean includePoms )
450 throws RepositoryAdminException
452 SearchResults results = new SearchResults();
453 Set<ArtifactInfo> artifactInfos = response.getResults();
455 for ( ArtifactInfo artifactInfo : artifactInfos )
457 if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.fextension ) && !includePoms )
461 String id = SearchUtil.getHitId( artifactInfo.groupId, artifactInfo.artifactId, artifactInfo.classifier,
462 artifactInfo.packaging );
463 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
465 if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
470 SearchResultHit hit = hitsMap.get( id );
473 if ( !hit.getVersions().contains( artifactInfo.version ) )
475 hit.addVersion( artifactInfo.version );
480 hit = new SearchResultHit();
481 hit.setArtifactId( artifactInfo.artifactId );
482 hit.setGroupId( artifactInfo.groupId );
483 hit.setRepositoryId( artifactInfo.repository );
484 hit.addVersion( artifactInfo.version );
485 hit.setBundleExportPackage( artifactInfo.bundleExportPackage );
486 hit.setBundleExportService( artifactInfo.bundleExportService );
487 hit.setBundleSymbolicName( artifactInfo.bundleSymbolicName );
488 hit.setBundleVersion( artifactInfo.bundleVersion );
489 hit.setBundleDescription( artifactInfo.bundleDescription );
490 hit.setBundleDocUrl( artifactInfo.bundleDocUrl );
491 hit.setBundleRequireBundle( artifactInfo.bundleRequireBundle );
492 hit.setBundleImportPackage( artifactInfo.bundleImportPackage );
493 hit.setBundleLicense( artifactInfo.bundleLicense );
494 hit.setBundleName( artifactInfo.bundleName );
495 hit.setContext( artifactInfo.context );
496 hit.setGoals( artifactInfo.goals );
497 hit.setPrefix( artifactInfo.prefix );
498 hit.setPackaging( artifactInfo.packaging );
499 hit.setClassifier( artifactInfo.classifier );
500 hit.setFileExtension( artifactInfo.fextension );
501 hit.setUrl( getBaseUrl( artifactInfo, selectedRepos ) );
504 results.addHit( id, hit );
507 results.setTotalHits( response.getTotalHitsCount() );
508 results.setTotalHitsMapSize( results.getHitsMap().values().size() );
509 results.setReturnedHitsCount( response.getReturnedHitsCount() );
510 results.setLimits( limits );
512 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
518 return paginate( results );
523 * calculate baseUrl without the context and base Archiva Url
525 * @param artifactInfo
528 protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
529 throws RepositoryAdminException
531 StringBuilder sb = new StringBuilder();
532 if ( StringUtils.startsWith( artifactInfo.context, "remote-" ) )
534 // it's a remote index result we search a managed which proxying this remote and on which
535 // current user has read karma
536 String managedRepoId =
537 getManagedRepoId( StringUtils.substringAfter( artifactInfo.context, "remote-" ), selectedRepos );
538 if ( managedRepoId != null )
540 sb.append( '/' ).append( managedRepoId );
541 artifactInfo.context = managedRepoId;
546 sb.append( '/' ).append( artifactInfo.context );
549 sb.append( '/' ).append( StringUtils.replaceChars( artifactInfo.groupId, '.', '/' ) );
550 sb.append( '/' ).append( artifactInfo.artifactId );
551 sb.append( '/' ).append( artifactInfo.version );
552 sb.append( '/' ).append( artifactInfo.artifactId );
553 sb.append( '-' ).append( artifactInfo.version );
554 if ( StringUtils.isNotBlank( artifactInfo.classifier ) )
556 sb.append( '-' ).append( artifactInfo.classifier );
558 // maven-plugin packaging is a jar
559 if ( StringUtils.equals( "maven-plugin", artifactInfo.packaging ) )
565 sb.append( '.' ).append( artifactInfo.packaging );
568 return sb.toString();
572 * return a managed repo for a remote result
575 * @param selectedRepos
577 * @throws RepositoryAdminException
579 private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
580 throws RepositoryAdminException
582 Map<String, List<ProxyConnector>> proxyConnectorMap = proxyConnectorAdmin.getProxyConnectorAsMap();
583 if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
587 if ( selectedRepos != null && !selectedRepos.isEmpty() )
589 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
591 if ( selectedRepos.contains( entry.getKey() ) )
593 for ( ProxyConnector proxyConnector : entry.getValue() )
595 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
597 return proxyConnector.getSourceRepoId();
604 // we don't find in search selected repos so return the first one
605 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
608 for ( ProxyConnector proxyConnector : entry.getValue() )
610 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
612 return proxyConnector.getSourceRepoId();
620 private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
621 List<? extends ArtifactInfoFilter> artifactInfoFilters,
622 Map<String, SearchResultHit> currentResult )
624 if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
629 for ( ArtifactInfoFilter filter : artifactInfoFilters )
631 if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
639 protected SearchResults paginate( SearchResults results )
641 SearchResultLimits limits = results.getLimits();
642 SearchResults paginated = new SearchResults();
644 // ( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
646 int fetchCount = limits.getPageSize();
647 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
649 if ( fetchCount > results.getTotalHits() )
651 fetchCount = results.getTotalHits();
655 if ( offset < results.getTotalHits() )
657 // only process if the offset is within the hit count.
658 for ( int i = 0; i < fetchCount; i++ )
660 // Stop fetching if we are past the total # of available hits.
661 if ( offset + i >= results.getHits().size() )
666 SearchResultHit hit = results.getHits().get( ( offset + i ) );
669 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
670 hit.getPackaging() );
671 paginated.addHit( id, hit );
679 paginated.setTotalHits( results.getTotalHits() );
680 paginated.setReturnedHitsCount( paginated.getHits().size() );
681 paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
682 paginated.setLimits( limits );