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.PlexusSisuBridgeException;
28 import org.apache.archiva.indexer.util.SearchUtil;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.maven.index.ArtifactInfo;
31 import org.apache.maven.index.FlatSearchRequest;
32 import org.apache.maven.index.FlatSearchResponse;
33 import org.apache.maven.index.MAVEN;
34 import org.apache.maven.index.NexusIndexer;
35 import org.apache.maven.index.OSGI;
36 import org.apache.maven.index.QueryCreator;
37 import org.apache.maven.index.SearchType;
38 import org.apache.maven.index.context.IndexingContext;
39 import org.apache.maven.index.expr.SearchExpression;
40 import org.apache.maven.index.expr.SearchTyped;
41 import org.apache.maven.index.expr.SourcedSearchExpression;
42 import org.apache.maven.index.expr.UserInputSearchExpression;
43 import org.apache.maven.index_shaded.lucene.search.BooleanClause;
44 import org.apache.maven.index_shaded.lucene.search.BooleanClause.Occur;
45 import org.apache.maven.index_shaded.lucene.search.BooleanQuery;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.stereotype.Service;
50 import javax.inject.Inject;
51 import java.io.IOException;
52 import java.util.ArrayList;
53 import java.util.Collection;
54 import java.util.Collections;
55 import java.util.HashSet;
56 import java.util.List;
61 * RepositorySearch implementation which uses the Maven Indexer for searching.
63 @Service( "repositorySearch#maven" )
64 public class MavenRepositorySearch
65 implements RepositorySearch
67 private Logger log = LoggerFactory.getLogger( getClass() );
69 private NexusIndexer indexer;
71 private QueryCreator queryCreator;
73 private ManagedRepositoryAdmin managedRepositoryAdmin;
75 private ProxyConnectorAdmin proxyConnectorAdmin;
77 protected MavenRepositorySearch()
83 public MavenRepositorySearch( NexusIndexer nexusIndexer, ManagedRepositoryAdmin managedRepositoryAdmin,
84 ProxyConnectorAdmin proxyConnectorAdmin, QueryCreator queryCreator )
85 throws PlexusSisuBridgeException
87 this.indexer = nexusIndexer;
88 this.queryCreator = queryCreator;
89 this.managedRepositoryAdmin = managedRepositoryAdmin;
90 this.proxyConnectorAdmin = proxyConnectorAdmin;
94 * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
97 public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
98 List<String> previousSearchTerms )
99 throws RepositorySearchException
101 List<String> indexingContextIds = addIndexingContexts( selectedRepos );
103 // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
104 // resulting to more wildcard searches so we need to increase max clause count
105 BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
106 BooleanQuery q = new BooleanQuery();
108 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
110 constructQuery( term, q );
114 for ( String previousTerm : previousSearchTerms )
116 BooleanQuery iQuery = new BooleanQuery();
117 constructQuery( previousTerm, iQuery );
119 q.add( iQuery, BooleanClause.Occur.MUST );
122 BooleanQuery iQuery = new BooleanQuery();
123 constructQuery( term, iQuery );
124 q.add( iQuery, BooleanClause.Occur.MUST );
127 // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
128 // FIXME cannot find a way currently to setup this in constructQuery !!!
129 return search( limits, q, indexingContextIds, NoClassifierArtifactInfoFilter.LIST, selectedRepos, true );
134 * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
137 public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
138 throws RepositorySearchException
140 if ( searchFields.getRepositories() == null )
142 throw new RepositorySearchException( "Repositories cannot be null." );
145 List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
147 // if no index found in the specified ones return an empty search result instead of doing a search on all index
148 // olamy: IMHO doesn't make sense
149 if ( !searchFields.getRepositories().isEmpty() && ( indexingContextIds == null
150 || indexingContextIds.isEmpty() ) )
152 return new SearchResults();
155 BooleanQuery q = new BooleanQuery();
156 if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
158 q.add( indexer.constructQuery( MAVEN.GROUP_ID, searchFields.isExactSearch() ? new SourcedSearchExpression(
159 searchFields.getGroupId() ) : new UserInputSearchExpression( searchFields.getGroupId() ) ),
160 BooleanClause.Occur.MUST );
163 if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
165 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID,
166 searchFields.isExactSearch()
167 ? new SourcedSearchExpression( searchFields.getArtifactId() )
168 : new UserInputSearchExpression( searchFields.getArtifactId() ) ),
169 BooleanClause.Occur.MUST );
172 if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
174 q.add( indexer.constructQuery( MAVEN.VERSION, searchFields.isExactSearch() ? new SourcedSearchExpression(
175 searchFields.getVersion() ) : new SourcedSearchExpression( searchFields.getVersion() ) ),
176 BooleanClause.Occur.MUST );
179 if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
181 q.add( indexer.constructQuery( MAVEN.PACKAGING, searchFields.isExactSearch() ? new SourcedSearchExpression(
182 searchFields.getPackaging() ) : new UserInputSearchExpression( searchFields.getPackaging() ) ),
183 BooleanClause.Occur.MUST );
186 if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
188 q.add( indexer.constructQuery( MAVEN.CLASSNAMES,
189 new UserInputSearchExpression( searchFields.getClassName() ) ),
190 BooleanClause.Occur.MUST );
193 if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
195 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
196 new UserInputSearchExpression( searchFields.getBundleSymbolicName() ) ),
197 BooleanClause.Occur.MUST );
200 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
202 q.add( indexer.constructQuery( OSGI.VERSION,
203 new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
204 BooleanClause.Occur.MUST );
207 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
209 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
210 new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
214 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
216 q.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
217 new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
221 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
223 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
224 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
228 if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
230 q.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
234 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
236 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
237 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
241 if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
243 q.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
244 new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
248 if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
250 q.add( indexer.constructQuery( MAVEN.CLASSIFIER, searchFields.isExactSearch() ? new SourcedSearchExpression(
251 searchFields.getClassifier() ) : new UserInputSearchExpression( searchFields.getClassifier() ) ),
254 else if ( searchFields.isExactSearch() )
256 //TODO improvement in case of exact search and no classifier we must query for classifier with null value
257 // currently it's done in DefaultSearchService with some filtering
260 if ( q.getClauses() == null || q.getClauses().length <= 0 )
262 throw new RepositorySearchException( "No search fields set." );
265 return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
266 searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
269 private static class NullSearch
270 implements SearchTyped, SearchExpression
272 private static final NullSearch INSTANCE = new NullSearch();
275 public String getStringValue()
277 return "[[NULL_VALUE]]";
281 public SearchType getSearchType()
283 return SearchType.EXACT;
287 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
288 List<? extends ArtifactInfoFilter> filters, List<String> selectedRepos,
289 boolean includePoms )
290 throws RepositorySearchException
295 FlatSearchRequest request = new FlatSearchRequest( q );
297 request.setContexts( getIndexingContexts( indexingContextIds ) );
298 if ( limits != null )
300 // we apply limits only when first page asked
301 if ( limits.getSelectedPage() == 0 )
303 request.setCount( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
307 FlatSearchResponse response = indexer.searchFlat( request );
309 if ( response == null || response.getTotalHits() == 0 )
311 SearchResults results = new SearchResults();
312 results.setLimits( limits );
316 return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
318 catch ( IOException e )
320 throw new RepositorySearchException( e.getMessage(), e );
322 catch ( RepositoryAdminException e )
324 throw new RepositorySearchException( e.getMessage(), e );
329 private List<IndexingContext> getIndexingContexts( List<String> ids )
331 List<IndexingContext> contexts = new ArrayList<>( ids.size() );
333 for ( String id : ids )
335 IndexingContext context = indexer.getIndexingContexts().get( id );
336 if ( context != null )
338 contexts.add( context );
342 log.warn( "context with id {} not exists", id );
349 private void constructQuery( String term, BooleanQuery q )
351 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
352 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
353 q.add( indexer.constructQuery( MAVEN.VERSION, new UserInputSearchExpression( term ) ), Occur.SHOULD );
354 q.add( indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( term ) ), Occur.SHOULD );
355 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new UserInputSearchExpression( term ) ), Occur.SHOULD );
358 // new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
359 //q.add( query, Occur.MUST_NOT );
360 // olamy IMHO we could set this option as at least one must match
361 //q.setMinimumNumberShouldMatch( 1 );
366 * @param selectedRepos
367 * @return indexing contextId used
369 private List<String> addIndexingContexts( List<String> selectedRepos )
371 Set<String> indexingContextIds = new HashSet<>();
372 for ( String repo : selectedRepos )
376 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
378 if ( repoConfig != null )
381 IndexingContext context = managedRepositoryAdmin.createIndexContext( repoConfig );
382 if ( context.isSearchable() )
384 indexingContextIds.addAll( getRemoteIndexingContextIds( repo ) );
385 indexingContextIds.add( context.getId() );
389 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
395 log.warn( "Repository '{}' not found in configuration.", repo );
398 catch ( RepositoryAdminException e )
400 log.warn( "RepositoryAdminException occured while accessing index of repository '{}' : {}", repo,
406 return new ArrayList<>( indexingContextIds );
411 public Set<String> getRemoteIndexingContextIds( String managedRepoId )
412 throws RepositoryAdminException
414 Set<String> ids = new HashSet<>();
416 List<ProxyConnector> proxyConnectors = proxyConnectorAdmin.getProxyConnectorAsMap().get( managedRepoId );
418 if ( proxyConnectors == null || proxyConnectors.isEmpty() )
423 for ( ProxyConnector proxyConnector : proxyConnectors )
425 String remoteId = "remote-" + proxyConnector.getTargetRepoId();
426 IndexingContext context = indexer.getIndexingContexts().get( remoteId );
427 if ( context != null && context.isSearchable() )
437 public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
438 throws RepositorySearchException
440 List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
442 if ( indexContexts == null || indexContexts.isEmpty() )
444 return Collections.emptyList();
449 Set<String> allGroupIds = new HashSet<>();
450 for ( IndexingContext indexingContext : indexContexts )
452 allGroupIds.addAll( indexingContext.getAllGroups() );
456 catch ( IOException e )
458 throw new RepositorySearchException( e.getMessage(), e );
463 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
464 List<? extends ArtifactInfoFilter> artifactInfoFilters,
465 List<String> selectedRepos, boolean includePoms )
466 throws RepositoryAdminException
468 SearchResults results = new SearchResults();
469 Set<ArtifactInfo> artifactInfos = response.getResults();
471 for ( ArtifactInfo artifactInfo : artifactInfos )
473 if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.getFileExtension() ) && !includePoms )
477 String id = SearchUtil.getHitId( artifactInfo.getGroupId(), //
478 artifactInfo.getArtifactId(), //
479 artifactInfo.getClassifier(), //
480 artifactInfo.getPackaging() );
481 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
483 if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
488 SearchResultHit hit = hitsMap.get( id );
491 if ( !hit.getVersions().contains( artifactInfo.getVersion() ) )
493 hit.addVersion( artifactInfo.getVersion() );
498 hit = new SearchResultHit();
499 hit.setArtifactId( artifactInfo.getArtifactId() );
500 hit.setGroupId( artifactInfo.getGroupId() );
501 hit.setRepositoryId( artifactInfo.getRepository() );
502 hit.addVersion( artifactInfo.getVersion() );
503 hit.setBundleExportPackage( artifactInfo.getBundleExportPackage() );
504 hit.setBundleExportService( artifactInfo.getBundleExportService() );
505 hit.setBundleSymbolicName( artifactInfo.getBundleSymbolicName() );
506 hit.setBundleVersion( artifactInfo.getBundleVersion() );
507 hit.setBundleDescription( artifactInfo.getBundleDescription() );
508 hit.setBundleDocUrl( artifactInfo.getBundleDocUrl() );
509 hit.setBundleRequireBundle( artifactInfo.getBundleRequireBundle() );
510 hit.setBundleImportPackage( artifactInfo.getBundleImportPackage() );
511 hit.setBundleLicense( artifactInfo.getBundleLicense() );
512 hit.setBundleName( artifactInfo.getBundleName() );
513 hit.setContext( artifactInfo.getContext() );
514 hit.setGoals( artifactInfo.getGoals() );
515 hit.setPrefix( artifactInfo.getPrefix() );
516 hit.setPackaging( artifactInfo.getPackaging() );
517 hit.setClassifier( artifactInfo.getClassifier() );
518 hit.setFileExtension( artifactInfo.getFileExtension() );
519 hit.setUrl( getBaseUrl( artifactInfo, selectedRepos ) );
522 results.addHit( id, hit );
525 results.setTotalHits( response.getTotalHitsCount() );
526 results.setTotalHitsMapSize( results.getHitsMap().values().size() );
527 results.setReturnedHitsCount( response.getReturnedHitsCount() );
528 results.setLimits( limits );
530 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
536 return paginate( results );
541 * calculate baseUrl without the context and base Archiva Url
543 * @param artifactInfo
546 protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
547 throws RepositoryAdminException
549 StringBuilder sb = new StringBuilder();
550 if ( StringUtils.startsWith( artifactInfo.getContext(), "remote-" ) )
552 // it's a remote index result we search a managed which proxying this remote and on which
553 // current user has read karma
554 String managedRepoId =
555 getManagedRepoId( StringUtils.substringAfter( artifactInfo.getContext(), "remote-" ), selectedRepos );
556 if ( managedRepoId != null )
558 sb.append( '/' ).append( managedRepoId );
559 artifactInfo.setContext( managedRepoId );
564 sb.append( '/' ).append( artifactInfo.getContext() );
567 sb.append( '/' ).append( StringUtils.replaceChars( artifactInfo.getGroupId(), '.', '/' ) );
568 sb.append( '/' ).append( artifactInfo.getArtifactId() );
569 sb.append( '/' ).append( artifactInfo.getVersion() );
570 sb.append( '/' ).append( artifactInfo.getArtifactId() );
571 sb.append( '-' ).append( artifactInfo.getVersion() );
572 if ( StringUtils.isNotBlank( artifactInfo.getClassifier() ) )
574 sb.append( '-' ).append( artifactInfo.getClassifier() );
576 // maven-plugin packaging is a jar
577 if ( StringUtils.equals( "maven-plugin", artifactInfo.getPackaging() ) )
583 sb.append( '.' ).append( artifactInfo.getPackaging() );
586 return sb.toString();
590 * return a managed repo for a remote result
593 * @param selectedRepos
595 * @throws RepositoryAdminException
597 private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
598 throws RepositoryAdminException
600 Map<String, List<ProxyConnector>> proxyConnectorMap = proxyConnectorAdmin.getProxyConnectorAsMap();
601 if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
605 if ( selectedRepos != null && !selectedRepos.isEmpty() )
607 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
609 if ( selectedRepos.contains( entry.getKey() ) )
611 for ( ProxyConnector proxyConnector : entry.getValue() )
613 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
615 return proxyConnector.getSourceRepoId();
622 // we don't find in search selected repos so return the first one
623 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
626 for ( ProxyConnector proxyConnector : entry.getValue() )
628 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
630 return proxyConnector.getSourceRepoId();
638 private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
639 List<? extends ArtifactInfoFilter> artifactInfoFilters,
640 Map<String, SearchResultHit> currentResult )
642 if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
647 for ( ArtifactInfoFilter filter : artifactInfoFilters )
649 if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
657 protected SearchResults paginate( SearchResults results )
659 SearchResultLimits limits = results.getLimits();
660 SearchResults paginated = new SearchResults();
662 // ( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
664 int fetchCount = limits.getPageSize();
665 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
667 if ( fetchCount > results.getTotalHits() )
669 fetchCount = results.getTotalHits();
673 if ( offset < results.getTotalHits() )
675 // only process if the offset is within the hit count.
676 for ( int i = 0; i < fetchCount; i++ )
678 // Stop fetching if we are past the total # of available hits.
679 if ( offset + i >= results.getHits().size() )
684 SearchResultHit hit = results.getHits().get( ( offset + i ) );
687 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
688 hit.getPackaging() );
689 paginated.addHit( id, hit );
697 paginated.setTotalHits( results.getTotalHits() );
698 paginated.setReturnedHitsCount( paginated.getHits().size() );
699 paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
700 paginated.setLimits( limits );