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.queryParser.ParseException;
33 import org.apache.lucene.search.BooleanClause;
34 import org.apache.lucene.search.BooleanClause.Occur;
35 import org.apache.lucene.search.BooleanQuery;
36 import org.apache.lucene.search.Query;
37 import org.apache.maven.index.ArtifactInfo;
38 import org.apache.maven.index.FlatSearchRequest;
39 import org.apache.maven.index.FlatSearchResponse;
40 import org.apache.maven.index.MAVEN;
41 import org.apache.maven.index.NexusIndexer;
42 import org.apache.maven.index.OSGI;
43 import org.apache.maven.index.QueryCreator;
44 import org.apache.maven.index.SearchType;
45 import org.apache.maven.index.context.IndexCreator;
46 import org.apache.maven.index.context.IndexingContext;
47 import org.apache.maven.index.expr.SearchExpression;
48 import org.apache.maven.index.expr.SearchTyped;
49 import org.apache.maven.index.expr.SourcedSearchExpression;
50 import org.apache.maven.index.expr.UserInputSearchExpression;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.stereotype.Service;
55 import javax.inject.Inject;
56 import java.io.IOException;
57 import java.util.ArrayList;
58 import java.util.Collection;
59 import java.util.Collections;
60 import java.util.HashSet;
61 import java.util.List;
66 * RepositorySearch implementation which uses the Maven Indexer for searching.
68 @Service( "repositorySearch#maven" )
69 public class MavenRepositorySearch
70 implements RepositorySearch
72 private Logger log = LoggerFactory.getLogger( getClass() );
74 private NexusIndexer indexer;
76 private QueryCreator queryCreator;
78 private ManagedRepositoryAdmin managedRepositoryAdmin;
80 private ProxyConnectorAdmin proxyConnectorAdmin;
82 private MavenIndexerUtils mavenIndexerUtils;
84 protected MavenRepositorySearch()
90 public MavenRepositorySearch( PlexusSisuBridge plexusSisuBridge, ManagedRepositoryAdmin managedRepositoryAdmin,
91 MavenIndexerUtils mavenIndexerUtils, ProxyConnectorAdmin proxyConnectorAdmin )
92 throws PlexusSisuBridgeException
94 this.indexer = plexusSisuBridge.lookup( NexusIndexer.class );
95 this.queryCreator = plexusSisuBridge.lookup( QueryCreator.class );
96 this.managedRepositoryAdmin = managedRepositoryAdmin;
97 this.mavenIndexerUtils = mavenIndexerUtils;
98 this.proxyConnectorAdmin = proxyConnectorAdmin;
102 * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
105 public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
106 List<String> previousSearchTerms )
107 throws RepositorySearchException
109 List<String> indexingContextIds = addIndexingContexts( selectedRepos );
111 // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
112 // resulting to more wildcard searches so we need to increase max clause count
113 BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
114 BooleanQuery q = new BooleanQuery();
116 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
118 constructQuery( term, q );
122 for ( String previousTerm : previousSearchTerms )
124 BooleanQuery iQuery = new BooleanQuery();
125 constructQuery( previousTerm, iQuery );
127 q.add( iQuery, Occur.MUST );
130 BooleanQuery iQuery = new BooleanQuery();
131 constructQuery( term, iQuery );
132 q.add( iQuery, Occur.MUST );
135 // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
136 // FIXME cannot find a way currently to setup this in constructQuery !!!
137 return search( limits, q, indexingContextIds, NoClassifierArtifactInfoFilter.LIST, selectedRepos, true );
142 * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
145 public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
146 throws RepositorySearchException
148 if ( searchFields.getRepositories() == null )
150 throw new RepositorySearchException( "Repositories cannot be null." );
153 List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
155 // if no index found in the specified ones return an empty search result instead of doing a search on all index
156 // olamy: IMHO doesn't make sense
157 if ( !searchFields.getRepositories().isEmpty() && ( indexingContextIds == null
158 || indexingContextIds.isEmpty() ) )
160 return new SearchResults();
163 BooleanQuery q = new BooleanQuery();
164 if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
166 q.add( indexer.constructQuery( MAVEN.GROUP_ID, searchFields.isExactSearch()
167 ? new SourcedSearchExpression( searchFields.getGroupId() )
168 : new UserInputSearchExpression( searchFields.getGroupId() )
173 if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
175 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID,
176 searchFields.isExactSearch()
177 ? new SourcedSearchExpression( searchFields.getArtifactId() )
178 : new UserInputSearchExpression( searchFields.getArtifactId() )
183 if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
185 q.add( indexer.constructQuery( MAVEN.VERSION, searchFields.isExactSearch() ? new SourcedSearchExpression(
186 searchFields.getVersion() ) : new SourcedSearchExpression( searchFields.getVersion() ) ), Occur.MUST );
189 if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
191 q.add( indexer.constructQuery( MAVEN.PACKAGING, searchFields.isExactSearch() ? new SourcedSearchExpression(
192 searchFields.getPackaging() ) : new UserInputSearchExpression( searchFields.getPackaging() ) ),
197 if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
199 q.add( indexer.constructQuery( MAVEN.CLASSNAMES,
200 new UserInputSearchExpression( searchFields.getClassName() ) ), Occur.MUST );
203 if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
205 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
206 new UserInputSearchExpression( searchFields.getBundleSymbolicName() ) ),
211 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
213 q.add( indexer.constructQuery( OSGI.VERSION,
214 new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
219 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
221 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
222 new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
227 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
229 q.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
230 new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
235 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
237 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
238 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
243 if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
245 q.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
249 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
251 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
252 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
257 if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
259 q.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
260 new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
265 if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
267 q.add( indexer.constructQuery( MAVEN.CLASSIFIER, searchFields.isExactSearch() ? new SourcedSearchExpression(
268 searchFields.getClassifier() ) : new UserInputSearchExpression( searchFields.getClassifier() ) ),
272 else if ( searchFields.isExactSearch() )
274 //TODO improvement in case of exact search and no classifier we must query for classifier with null value
275 // currently it's done in DefaultSearchService with some filtering
278 if ( q.getClauses() == null || q.getClauses().length <= 0 )
280 throw new RepositorySearchException( "No search fields set." );
283 return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
284 searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
287 private static class NullSearch implements SearchTyped, SearchExpression
289 private static final NullSearch INSTANCE = new NullSearch();
292 public String getStringValue()
294 return "[[NULL_VALUE]]";
298 public SearchType getSearchType()
300 return SearchType.EXACT;
304 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
305 List<? extends ArtifactInfoFilter> filters, List<String> selectedRepos,
306 boolean includePoms )
307 throws RepositorySearchException
312 FlatSearchRequest request = new FlatSearchRequest( q );
314 request.setContexts( getIndexingContexts( indexingContextIds ) );
315 if ( limits != null )
317 // we apply limits only when first page asked
318 if ( limits.getSelectedPage() == 0 )
320 request.setCount( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
324 FlatSearchResponse response = indexer.searchFlat( request );
326 if ( response == null || response.getTotalHits() == 0 )
328 SearchResults results = new SearchResults();
329 results.setLimits( limits );
333 return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
335 catch ( IOException e )
337 throw new RepositorySearchException( e.getMessage(), e );
339 catch ( RepositoryAdminException e )
341 throw new RepositorySearchException( e.getMessage(), e );
346 private List<IndexingContext> getIndexingContexts( List<String> ids )
348 List<IndexingContext> contexts = new ArrayList<>( ids.size() );
350 for ( String id : ids )
352 IndexingContext context = indexer.getIndexingContexts().get( id );
353 if ( context != null )
355 contexts.add( context );
359 log.warn( "context with id {} not exists", id );
366 private void constructQuery( String term, BooleanQuery q )
368 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
369 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
370 q.add( indexer.constructQuery( MAVEN.VERSION, new UserInputSearchExpression( term ) ), Occur.SHOULD );
371 q.add( indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( term ) ), Occur.SHOULD );
372 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new UserInputSearchExpression( term ) ), Occur.SHOULD );
375 // new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
376 //q.add( query, Occur.MUST_NOT );
377 // olamy IMHO we could set this option as at least one must match
378 //q.setMinimumNumberShouldMatch( 1 );
383 * @param selectedRepos
384 * @return indexing contextId used
386 private List<String> addIndexingContexts( List<String> selectedRepos )
388 Set<String> indexingContextIds = new HashSet<>();
389 for ( String repo : selectedRepos )
393 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
395 if ( repoConfig != null )
398 IndexingContext context = managedRepositoryAdmin.createIndexContext( repoConfig );
399 if ( context.isSearchable() )
401 indexingContextIds.addAll( getRemoteIndexingContextIds( repo ) );
402 indexingContextIds.add( context.getId() );
406 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
412 log.warn( "Repository '{}' not found in configuration.", repo );
415 catch ( RepositoryAdminException e )
417 log.warn( "RepositoryAdminException occured while accessing index of repository '{}' : {}", repo,
423 return new ArrayList<>( indexingContextIds );
428 public Set<String> getRemoteIndexingContextIds( String managedRepoId )
429 throws RepositoryAdminException
431 Set<String> ids = new HashSet<>();
433 List<ProxyConnector> proxyConnectors = proxyConnectorAdmin.getProxyConnectorAsMap().get( managedRepoId );
435 if ( proxyConnectors == null || proxyConnectors.isEmpty() )
440 for ( ProxyConnector proxyConnector : proxyConnectors )
442 String remoteId = "remote-" + proxyConnector.getTargetRepoId();
443 IndexingContext context = indexer.getIndexingContexts().get( remoteId );
444 if ( context != null && context.isSearchable() )
454 public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
455 throws RepositorySearchException
457 List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
459 if ( indexContexts == null || indexContexts.isEmpty() )
461 return Collections.emptyList();
466 Set<String> allGroupIds = new HashSet<>();
467 for ( IndexingContext indexingContext : indexContexts )
469 allGroupIds.addAll( indexingContext.getAllGroups() );
473 catch ( IOException e )
475 throw new RepositorySearchException( e.getMessage(), e );
481 protected List<? extends IndexCreator> getAllIndexCreators()
483 return mavenIndexerUtils.getAllIndexCreators();
487 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
488 List<? extends ArtifactInfoFilter> artifactInfoFilters,
489 List<String> selectedRepos, boolean includePoms )
490 throws RepositoryAdminException
492 SearchResults results = new SearchResults();
493 Set<ArtifactInfo> artifactInfos = response.getResults();
495 for ( ArtifactInfo artifactInfo : artifactInfos )
497 if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.fextension ) && !includePoms )
501 String id = SearchUtil.getHitId( artifactInfo.groupId, artifactInfo.artifactId, artifactInfo.classifier,
502 artifactInfo.packaging );
503 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
505 if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
510 SearchResultHit hit = hitsMap.get( id );
513 if ( !hit.getVersions().contains( artifactInfo.version ) )
515 hit.addVersion( artifactInfo.version );
520 hit = new SearchResultHit();
521 hit.setArtifactId( artifactInfo.artifactId );
522 hit.setGroupId( artifactInfo.groupId );
523 hit.setRepositoryId( artifactInfo.repository );
524 hit.addVersion( artifactInfo.version );
525 hit.setBundleExportPackage( artifactInfo.bundleExportPackage );
526 hit.setBundleExportService( artifactInfo.bundleExportService );
527 hit.setBundleSymbolicName( artifactInfo.bundleSymbolicName );
528 hit.setBundleVersion( artifactInfo.bundleVersion );
529 hit.setBundleDescription( artifactInfo.bundleDescription );
530 hit.setBundleDocUrl( artifactInfo.bundleDocUrl );
531 hit.setBundleRequireBundle( artifactInfo.bundleRequireBundle );
532 hit.setBundleImportPackage( artifactInfo.bundleImportPackage );
533 hit.setBundleLicense( artifactInfo.bundleLicense );
534 hit.setBundleName( artifactInfo.bundleName );
535 hit.setContext( artifactInfo.context );
536 hit.setGoals( artifactInfo.goals );
537 hit.setPrefix( artifactInfo.prefix );
538 hit.setPackaging( artifactInfo.packaging );
539 hit.setClassifier( artifactInfo.classifier );
540 hit.setFileExtension( artifactInfo.fextension );
541 hit.setUrl( getBaseUrl( artifactInfo, selectedRepos ) );
544 results.addHit( id, hit );
547 results.setTotalHits( response.getTotalHitsCount() );
548 results.setTotalHitsMapSize( results.getHitsMap().values().size() );
549 results.setReturnedHitsCount( response.getReturnedHitsCount() );
550 results.setLimits( limits );
552 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
558 return paginate( results );
563 * calculate baseUrl without the context and base Archiva Url
565 * @param artifactInfo
568 protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
569 throws RepositoryAdminException
571 StringBuilder sb = new StringBuilder();
572 if ( StringUtils.startsWith( artifactInfo.context, "remote-" ) )
574 // it's a remote index result we search a managed which proxying this remote and on which
575 // current user has read karma
576 String managedRepoId =
577 getManagedRepoId( StringUtils.substringAfter( artifactInfo.context, "remote-" ), selectedRepos );
578 if ( managedRepoId != null )
580 sb.append( '/' ).append( managedRepoId );
581 artifactInfo.context = managedRepoId;
586 sb.append( '/' ).append( artifactInfo.context );
589 sb.append( '/' ).append( StringUtils.replaceChars( artifactInfo.groupId, '.', '/' ) );
590 sb.append( '/' ).append( artifactInfo.artifactId );
591 sb.append( '/' ).append( artifactInfo.version );
592 sb.append( '/' ).append( artifactInfo.artifactId );
593 sb.append( '-' ).append( artifactInfo.version );
594 if ( StringUtils.isNotBlank( artifactInfo.classifier ) )
596 sb.append( '-' ).append( artifactInfo.classifier );
598 // maven-plugin packaging is a jar
599 if ( StringUtils.equals( "maven-plugin", artifactInfo.packaging ) )
605 sb.append( '.' ).append( artifactInfo.packaging );
608 return sb.toString();
612 * return a managed repo for a remote result
615 * @param selectedRepos
617 * @throws RepositoryAdminException
619 private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
620 throws RepositoryAdminException
622 Map<String, List<ProxyConnector>> proxyConnectorMap = proxyConnectorAdmin.getProxyConnectorAsMap();
623 if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
627 if ( selectedRepos != null && !selectedRepos.isEmpty() )
629 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
631 if ( selectedRepos.contains( entry.getKey() ) )
633 for ( ProxyConnector proxyConnector : entry.getValue() )
635 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
637 return proxyConnector.getSourceRepoId();
644 // we don't find in search selected repos so return the first one
645 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
648 for ( ProxyConnector proxyConnector : entry.getValue() )
650 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
652 return proxyConnector.getSourceRepoId();
660 private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
661 List<? extends ArtifactInfoFilter> artifactInfoFilters,
662 Map<String, SearchResultHit> currentResult )
664 if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
669 for ( ArtifactInfoFilter filter : artifactInfoFilters )
671 if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
679 protected SearchResults paginate( SearchResults results )
681 SearchResultLimits limits = results.getLimits();
682 SearchResults paginated = new SearchResults();
684 // ( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
686 int fetchCount = limits.getPageSize();
687 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
689 if ( fetchCount > results.getTotalHits() )
691 fetchCount = results.getTotalHits();
695 if ( offset < results.getTotalHits() )
697 // only process if the offset is within the hit count.
698 for ( int i = 0; i < fetchCount; i++ )
700 // Stop fetching if we are past the total # of available hits.
701 if ( offset + i >= results.getHits().size() )
706 SearchResultHit hit = results.getHits().get( ( offset + i ) );
709 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
710 hit.getPackaging() );
711 paginated.addHit( id, hit );
719 paginated.setTotalHits( results.getTotalHits() );
720 paginated.setReturnedHitsCount( paginated.getHits().size() );
721 paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
722 paginated.setLimits( limits );