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() ) ),
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() ) ),
193 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
195 q.add( indexer.constructQuery( OSGI.VERSION,
196 new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
200 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
202 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
203 new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
207 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
209 q.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
210 new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
214 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
216 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
217 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
221 if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
223 q.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
227 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
229 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
230 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
234 if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
236 q.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
237 new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
241 if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
243 q.add( indexer.constructQuery( MAVEN.CLASSIFIER,
244 new UserInputSearchExpression( searchFields.getClassifier() ) ),
248 if ( q.getClauses() == null || q.getClauses().length <= 0 )
250 throw new RepositorySearchException( "No search fields set." );
253 return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
254 searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
257 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
258 List<? extends ArtifactInfoFilter> filters, List<String> selectedRepos,
259 boolean includePoms )
260 throws RepositorySearchException
265 FlatSearchRequest request = new FlatSearchRequest( q );
267 request.setContexts( getIndexingContexts( indexingContextIds ) );
269 FlatSearchResponse response = indexer.searchFlat( request );
271 if ( response == null || response.getTotalHits() == 0 )
273 SearchResults results = new SearchResults();
274 results.setLimits( limits );
278 return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
280 catch ( IOException e )
282 throw new RepositorySearchException( e.getMessage(), e );
284 catch ( RepositoryAdminException e )
286 throw new RepositorySearchException( e.getMessage(), e );
291 private List<IndexingContext> getIndexingContexts( List<String> ids )
293 List<IndexingContext> contexts = new ArrayList<>( ids.size() );
295 for ( String id : ids )
297 IndexingContext context = indexer.getIndexingContexts().get( id );
298 if ( context != null )
300 contexts.add( context );
304 log.warn( "context with id {} not exists", id );
311 private void constructQuery( String term, BooleanQuery q )
313 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
314 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
315 q.add( indexer.constructQuery( MAVEN.VERSION, new UserInputSearchExpression( term ) ), Occur.SHOULD );
316 q.add( indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( term ) ), Occur.SHOULD );
317 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new UserInputSearchExpression( term ) ), Occur.SHOULD );
320 // new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
321 //q.add( query, Occur.MUST_NOT );
322 // olamy IMHO we could set this option as at least one must match
323 //q.setMinimumNumberShouldMatch( 1 );
328 * @param selectedRepos
329 * @return indexing contextId used
331 private List<String> addIndexingContexts( List<String> selectedRepos )
333 Set<String> indexingContextIds = new HashSet<>();
334 for ( String repo : selectedRepos )
338 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
340 if ( repoConfig != null )
343 IndexingContext context = managedRepositoryAdmin.createIndexContext( repoConfig );
344 if ( context.isSearchable() )
346 indexingContextIds.addAll( getRemoteIndexingContextIds( repo ) );
347 indexingContextIds.add( context.getId() );
351 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
357 log.warn( "Repository '{}' not found in configuration.", repo );
360 catch ( RepositoryAdminException e )
362 log.warn( "RepositoryAdminException occured while accessing index of repository '{}' : {}", repo,
368 return new ArrayList<>( indexingContextIds );
373 public Set<String> getRemoteIndexingContextIds( String managedRepoId )
374 throws RepositoryAdminException
376 Set<String> ids = new HashSet<>();
378 List<ProxyConnector> proxyConnectors = proxyConnectorAdmin.getProxyConnectorAsMap().get( managedRepoId );
380 if ( proxyConnectors == null || proxyConnectors.isEmpty() )
385 for ( ProxyConnector proxyConnector : proxyConnectors )
387 String remoteId = "remote-" + proxyConnector.getTargetRepoId();
388 IndexingContext context = indexer.getIndexingContexts().get( remoteId );
389 if ( context != null && context.isSearchable() )
399 public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
400 throws RepositorySearchException
402 List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
404 if ( indexContexts == null || indexContexts.isEmpty() )
406 return Collections.emptyList();
411 Set<String> allGroupIds = new HashSet<>();
412 for ( IndexingContext indexingContext : indexContexts )
414 allGroupIds.addAll( indexingContext.getAllGroups() );
418 catch ( IOException e )
420 throw new RepositorySearchException( e.getMessage(), e );
426 protected List<? extends IndexCreator> getAllIndexCreators()
428 return mavenIndexerUtils.getAllIndexCreators();
432 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
433 List<? extends ArtifactInfoFilter> artifactInfoFilters,
434 List<String> selectedRepos, boolean includePoms )
435 throws RepositoryAdminException
437 SearchResults results = new SearchResults();
438 Set<ArtifactInfo> artifactInfos = response.getResults();
440 for ( ArtifactInfo artifactInfo : artifactInfos )
442 if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.fextension ) && !includePoms )
446 String id = SearchUtil.getHitId( artifactInfo.groupId, artifactInfo.artifactId, artifactInfo.classifier,
447 artifactInfo.packaging );
448 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
450 if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
455 SearchResultHit hit = hitsMap.get( id );
458 if ( !hit.getVersions().contains( artifactInfo.version ) )
460 hit.addVersion( artifactInfo.version );
465 hit = new SearchResultHit();
466 hit.setArtifactId( artifactInfo.artifactId );
467 hit.setGroupId( artifactInfo.groupId );
468 hit.setRepositoryId( artifactInfo.repository );
469 hit.addVersion( artifactInfo.version );
470 hit.setBundleExportPackage( artifactInfo.bundleExportPackage );
471 hit.setBundleExportService( artifactInfo.bundleExportService );
472 hit.setBundleSymbolicName( artifactInfo.bundleSymbolicName );
473 hit.setBundleVersion( artifactInfo.bundleVersion );
474 hit.setBundleDescription( artifactInfo.bundleDescription );
475 hit.setBundleDocUrl( artifactInfo.bundleDocUrl );
476 hit.setBundleRequireBundle( artifactInfo.bundleRequireBundle );
477 hit.setBundleImportPackage( artifactInfo.bundleImportPackage );
478 hit.setBundleLicense( artifactInfo.bundleLicense );
479 hit.setBundleName( artifactInfo.bundleName );
480 hit.setContext( artifactInfo.context );
481 hit.setGoals( artifactInfo.goals );
482 hit.setPrefix( artifactInfo.prefix );
483 hit.setPackaging( artifactInfo.packaging );
484 hit.setClassifier( artifactInfo.classifier );
485 hit.setFileExtension( artifactInfo.fextension );
486 hit.setUrl( getBaseUrl( artifactInfo, selectedRepos ) );
489 results.addHit( id, hit );
492 results.setTotalHits( response.getTotalHitsCount() );
493 results.setTotalHitsMapSize( results.getHitsMap().values().size() );
494 results.setReturnedHitsCount( response.getReturnedHitsCount() );
495 results.setLimits( limits );
497 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
503 return paginate( results );
508 * calculate baseUrl without the context and base Archiva Url
510 * @param artifactInfo
513 protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
514 throws RepositoryAdminException
516 StringBuilder sb = new StringBuilder();
517 if ( StringUtils.startsWith( artifactInfo.context, "remote-" ) )
519 // it's a remote index result we search a managed which proxying this remote and on which
520 // current user has read karma
521 String managedRepoId =
522 getManagedRepoId( StringUtils.substringAfter( artifactInfo.context, "remote-" ), selectedRepos );
523 if ( managedRepoId != null )
525 sb.append( '/' ).append( managedRepoId );
526 artifactInfo.context = managedRepoId;
531 sb.append( '/' ).append( artifactInfo.context );
534 sb.append( '/' ).append( StringUtils.replaceChars( artifactInfo.groupId, '.', '/' ) );
535 sb.append( '/' ).append( artifactInfo.artifactId );
536 sb.append( '/' ).append( artifactInfo.version );
537 sb.append( '/' ).append( artifactInfo.artifactId );
538 sb.append( '-' ).append( artifactInfo.version );
539 if ( StringUtils.isNotBlank( artifactInfo.classifier ) )
541 sb.append( '-' ).append( artifactInfo.classifier );
543 // maven-plugin packaging is a jar
544 if ( StringUtils.equals( "maven-plugin", artifactInfo.packaging ) )
550 sb.append( '.' ).append( artifactInfo.packaging );
553 return sb.toString();
557 * return a managed repo for a remote result
560 * @param selectedRepos
562 * @throws RepositoryAdminException
564 private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
565 throws RepositoryAdminException
567 Map<String, List<ProxyConnector>> proxyConnectorMap = proxyConnectorAdmin.getProxyConnectorAsMap();
568 if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
572 if ( selectedRepos != null && !selectedRepos.isEmpty() )
574 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
576 if ( selectedRepos.contains( entry.getKey() ) )
578 for ( ProxyConnector proxyConnector : entry.getValue() )
580 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
582 return proxyConnector.getSourceRepoId();
589 // we don't find in search selected repos so return the first one
590 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
593 for ( ProxyConnector proxyConnector : entry.getValue() )
595 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
597 return proxyConnector.getSourceRepoId();
605 private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
606 List<? extends ArtifactInfoFilter> artifactInfoFilters,
607 Map<String, SearchResultHit> currentResult )
609 if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
614 for ( ArtifactInfoFilter filter : artifactInfoFilters )
616 if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
624 protected SearchResults paginate( SearchResults results )
626 SearchResultLimits limits = results.getLimits();
627 SearchResults paginated = new SearchResults();
629 int fetchCount = limits.getPageSize();
630 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
632 if ( fetchCount > results.getTotalHits() )
634 fetchCount = results.getTotalHits();
638 if ( offset < results.getTotalHits() )
640 // only process if the offset is within the hit count.
641 for ( int i = 0; i < fetchCount; i++ )
643 // Stop fetching if we are past the total # of available hits.
644 if ( offset + i >= results.getHits().size() )
649 SearchResultHit hit = results.getHits().get( ( offset + i ) );
652 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
653 hit.getPackaging() );
654 paginated.addHit( id, hit );
662 paginated.setTotalHits( results.getTotalHits() );
663 paginated.setReturnedHitsCount( paginated.getHits().size() );
664 paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
665 paginated.setLimits( limits );