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.PlexusSisuBridgeException;
29 import org.apache.archiva.indexer.util.SearchUtil;
30 import org.apache.commons.lang.StringUtils;
32 import org.apache.maven.index.ArtifactInfo;
33 import org.apache.maven.index.FlatSearchRequest;
34 import org.apache.maven.index.FlatSearchResponse;
35 import org.apache.maven.index.MAVEN;
36 import org.apache.maven.index.NexusIndexer;
37 import org.apache.maven.index.OSGI;
38 import org.apache.maven.index.QueryCreator;
39 import org.apache.maven.index.SearchType;
40 import org.apache.maven.index.context.IndexCreator;
41 import org.apache.maven.index.context.IndexingContext;
42 import org.apache.maven.index.expr.SearchExpression;
43 import org.apache.maven.index.expr.SearchTyped;
44 import org.apache.maven.index.expr.SourcedSearchExpression;
45 import org.apache.maven.index.expr.UserInputSearchExpression;
46 import org.apache.maven.index.shaded.lucene.search.BooleanClause;
47 import org.apache.maven.index.shaded.lucene.search.BooleanClause.Occur;
48 import org.apache.maven.index.shaded.lucene.search.BooleanQuery;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.stereotype.Service;
53 import javax.inject.Inject;
54 import java.io.IOException;
55 import java.util.ArrayList;
56 import java.util.Collection;
57 import java.util.Collections;
58 import java.util.HashSet;
59 import java.util.List;
64 * RepositorySearch implementation which uses the Maven Indexer for searching.
66 @Service( "repositorySearch#maven" )
67 public class MavenRepositorySearch
68 implements RepositorySearch
70 private Logger log = LoggerFactory.getLogger( getClass() );
72 private NexusIndexer indexer;
74 private QueryCreator queryCreator;
76 private ManagedRepositoryAdmin managedRepositoryAdmin;
78 private ProxyConnectorAdmin proxyConnectorAdmin;
80 private MavenIndexerUtils mavenIndexerUtils;
82 protected MavenRepositorySearch()
88 public MavenRepositorySearch( NexusIndexer nexusIndexer, ManagedRepositoryAdmin managedRepositoryAdmin,
89 MavenIndexerUtils mavenIndexerUtils, ProxyConnectorAdmin proxyConnectorAdmin,
90 QueryCreator queryCreator)
91 throws PlexusSisuBridgeException
93 this.indexer = nexusIndexer;
94 this.queryCreator = queryCreator;
95 this.managedRepositoryAdmin = managedRepositoryAdmin;
96 this.mavenIndexerUtils = mavenIndexerUtils;
97 this.proxyConnectorAdmin = proxyConnectorAdmin;
101 * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
104 public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
105 List<String> previousSearchTerms )
106 throws RepositorySearchException
108 List<String> indexingContextIds = addIndexingContexts( selectedRepos );
110 // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
111 // resulting to more wildcard searches so we need to increase max clause count
112 BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
113 BooleanQuery q = new BooleanQuery();
115 if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
117 constructQuery( term, q );
121 for ( String previousTerm : previousSearchTerms )
123 BooleanQuery iQuery = new BooleanQuery();
124 constructQuery( previousTerm, iQuery );
126 q.add( iQuery, BooleanClause.Occur.MUST );
129 BooleanQuery iQuery = new BooleanQuery();
130 constructQuery( term, iQuery );
131 q.add( iQuery, BooleanClause.Occur.MUST );
134 // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
135 // FIXME cannot find a way currently to setup this in constructQuery !!!
136 return search( limits, q, indexingContextIds, NoClassifierArtifactInfoFilter.LIST, selectedRepos, true );
141 * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
144 public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
145 throws RepositorySearchException
147 if ( searchFields.getRepositories() == null )
149 throw new RepositorySearchException( "Repositories cannot be null." );
152 List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
154 // if no index found in the specified ones return an empty search result instead of doing a search on all index
155 // olamy: IMHO doesn't make sense
156 if ( !searchFields.getRepositories().isEmpty() && ( indexingContextIds == null
157 || indexingContextIds.isEmpty() ) )
159 return new SearchResults();
162 BooleanQuery q = new BooleanQuery();
163 if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
165 q.add( indexer.constructQuery( MAVEN.GROUP_ID, searchFields.isExactSearch()
166 ? new SourcedSearchExpression( searchFields.getGroupId() )
167 : new UserInputSearchExpression( searchFields.getGroupId() )
168 ), BooleanClause.Occur.MUST
172 if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
174 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID,
175 searchFields.isExactSearch()
176 ? new SourcedSearchExpression( searchFields.getArtifactId() )
177 : new UserInputSearchExpression( searchFields.getArtifactId() )
178 ), BooleanClause.Occur.MUST
182 if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
184 q.add( indexer.constructQuery( MAVEN.VERSION, searchFields.isExactSearch() ? new SourcedSearchExpression(
185 searchFields.getVersion() ) : new SourcedSearchExpression( searchFields.getVersion() ) ), BooleanClause.Occur.MUST );
188 if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
190 q.add( indexer.constructQuery( MAVEN.PACKAGING, searchFields.isExactSearch() ? new SourcedSearchExpression(
191 searchFields.getPackaging() ) : new UserInputSearchExpression( searchFields.getPackaging() ) ),
192 BooleanClause.Occur.MUST
196 if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
198 q.add( indexer.constructQuery( MAVEN.CLASSNAMES,
199 new UserInputSearchExpression( searchFields.getClassName() ) ), BooleanClause.Occur.MUST );
202 if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
204 q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
205 new UserInputSearchExpression( searchFields.getBundleSymbolicName() ) ),
206 BooleanClause.Occur.MUST
210 if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
212 q.add( indexer.constructQuery( OSGI.VERSION,
213 new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
214 BooleanClause.Occur.MUST
218 if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
220 q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
221 new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
226 if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
228 q.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
229 new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
234 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
236 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
237 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
242 if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
244 q.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
248 if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
250 q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
251 new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
256 if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
258 q.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
259 new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
264 if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
266 q.add( indexer.constructQuery( MAVEN.CLASSIFIER, searchFields.isExactSearch() ? new SourcedSearchExpression(
267 searchFields.getClassifier() ) : new UserInputSearchExpression( searchFields.getClassifier() ) ),
271 else if ( searchFields.isExactSearch() )
273 //TODO improvement in case of exact search and no classifier we must query for classifier with null value
274 // currently it's done in DefaultSearchService with some filtering
277 if ( q.getClauses() == null || q.getClauses().length <= 0 )
279 throw new RepositorySearchException( "No search fields set." );
282 return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
283 searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
286 private static class NullSearch implements SearchTyped, SearchExpression
288 private static final NullSearch INSTANCE = new NullSearch();
291 public String getStringValue()
293 return "[[NULL_VALUE]]";
297 public SearchType getSearchType()
299 return SearchType.EXACT;
303 private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
304 List<? extends ArtifactInfoFilter> filters, List<String> selectedRepos,
305 boolean includePoms )
306 throws RepositorySearchException
311 FlatSearchRequest request = new FlatSearchRequest( q );
313 request.setContexts( getIndexingContexts( indexingContextIds ) );
314 if ( limits != null )
316 // we apply limits only when first page asked
317 if ( limits.getSelectedPage() == 0 )
319 request.setCount( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
323 FlatSearchResponse response = indexer.searchFlat( request );
325 if ( response == null || response.getTotalHits() == 0 )
327 SearchResults results = new SearchResults();
328 results.setLimits( limits );
332 return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
334 catch ( IOException e )
336 throw new RepositorySearchException( e.getMessage(), e );
338 catch ( RepositoryAdminException e )
340 throw new RepositorySearchException( e.getMessage(), e );
345 private List<IndexingContext> getIndexingContexts( List<String> ids )
347 List<IndexingContext> contexts = new ArrayList<>( ids.size() );
349 for ( String id : ids )
351 IndexingContext context = indexer.getIndexingContexts().get( id );
352 if ( context != null )
354 contexts.add( context );
358 log.warn( "context with id {} not exists", id );
365 private void constructQuery( String term, BooleanQuery q )
367 q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
368 q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
369 q.add( indexer.constructQuery( MAVEN.VERSION, new UserInputSearchExpression( term ) ), Occur.SHOULD );
370 q.add( indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( term ) ), Occur.SHOULD );
371 q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new UserInputSearchExpression( term ) ), Occur.SHOULD );
374 // new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
375 //q.add( query, Occur.MUST_NOT );
376 // olamy IMHO we could set this option as at least one must match
377 //q.setMinimumNumberShouldMatch( 1 );
382 * @param selectedRepos
383 * @return indexing contextId used
385 private List<String> addIndexingContexts( List<String> selectedRepos )
387 Set<String> indexingContextIds = new HashSet<>();
388 for ( String repo : selectedRepos )
392 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
394 if ( repoConfig != null )
397 IndexingContext context = managedRepositoryAdmin.createIndexContext( repoConfig );
398 if ( context.isSearchable() )
400 indexingContextIds.addAll( getRemoteIndexingContextIds( repo ) );
401 indexingContextIds.add( context.getId() );
405 log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
411 log.warn( "Repository '{}' not found in configuration.", repo );
414 catch ( RepositoryAdminException e )
416 log.warn( "RepositoryAdminException occured while accessing index of repository '{}' : {}", repo,
422 return new ArrayList<>( indexingContextIds );
427 public Set<String> getRemoteIndexingContextIds( String managedRepoId )
428 throws RepositoryAdminException
430 Set<String> ids = new HashSet<>();
432 List<ProxyConnector> proxyConnectors = proxyConnectorAdmin.getProxyConnectorAsMap().get( managedRepoId );
434 if ( proxyConnectors == null || proxyConnectors.isEmpty() )
439 for ( ProxyConnector proxyConnector : proxyConnectors )
441 String remoteId = "remote-" + proxyConnector.getTargetRepoId();
442 IndexingContext context = indexer.getIndexingContexts().get( remoteId );
443 if ( context != null && context.isSearchable() )
453 public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
454 throws RepositorySearchException
456 List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
458 if ( indexContexts == null || indexContexts.isEmpty() )
460 return Collections.emptyList();
465 Set<String> allGroupIds = new HashSet<>();
466 for ( IndexingContext indexingContext : indexContexts )
468 allGroupIds.addAll( indexingContext.getAllGroups() );
472 catch ( IOException e )
474 throw new RepositorySearchException( e.getMessage(), e );
480 protected List<? extends IndexCreator> getAllIndexCreators()
482 return mavenIndexerUtils.getAllIndexCreators();
486 private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
487 List<? extends ArtifactInfoFilter> artifactInfoFilters,
488 List<String> selectedRepos, boolean includePoms )
489 throws RepositoryAdminException
491 SearchResults results = new SearchResults();
492 Set<ArtifactInfo> artifactInfos = response.getResults();
494 for ( ArtifactInfo artifactInfo : artifactInfos )
496 if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.getFileExtension() ) && !includePoms )
500 String id = SearchUtil.getHitId( artifactInfo.getGroupId(), //
501 artifactInfo.getArtifactId(), //
502 artifactInfo.getClassifier(), //
503 artifactInfo.getPackaging() );
504 Map<String, SearchResultHit> hitsMap = results.getHitsMap();
506 if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
511 SearchResultHit hit = hitsMap.get( id );
514 if ( !hit.getVersions().contains( artifactInfo.getVersion() ) )
516 hit.addVersion( artifactInfo.getVersion() );
521 hit = new SearchResultHit();
522 hit.setArtifactId( artifactInfo.getArtifactId() );
523 hit.setGroupId( artifactInfo.getGroupId() );
524 hit.setRepositoryId( artifactInfo.getRepository() );
525 hit.addVersion( artifactInfo.getVersion() );
526 hit.setBundleExportPackage( artifactInfo.getBundleExportPackage() );
527 hit.setBundleExportService( artifactInfo.getBundleExportService() );
528 hit.setBundleSymbolicName( artifactInfo.getBundleSymbolicName() );
529 hit.setBundleVersion( artifactInfo.getBundleVersion() );
530 hit.setBundleDescription( artifactInfo.getBundleDescription() );
531 hit.setBundleDocUrl( artifactInfo.getBundleDocUrl() );
532 hit.setBundleRequireBundle( artifactInfo.getBundleRequireBundle() );
533 hit.setBundleImportPackage( artifactInfo.getBundleImportPackage() );
534 hit.setBundleLicense( artifactInfo.getBundleLicense() );
535 hit.setBundleName( artifactInfo.getBundleName() );
536 hit.setContext( artifactInfo.getContext() );
537 hit.setGoals( artifactInfo.getGoals() );
538 hit.setPrefix( artifactInfo.getPrefix() );
539 hit.setPackaging( artifactInfo.getPackaging() );
540 hit.setClassifier( artifactInfo.getClassifier() );
541 hit.setFileExtension( artifactInfo.getFileExtension() );
542 hit.setUrl( getBaseUrl( artifactInfo, selectedRepos ) );
545 results.addHit( id, hit );
548 results.setTotalHits( response.getTotalHitsCount() );
549 results.setTotalHitsMapSize( results.getHitsMap().values().size() );
550 results.setReturnedHitsCount( response.getReturnedHitsCount() );
551 results.setLimits( limits );
553 if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
559 return paginate( results );
564 * calculate baseUrl without the context and base Archiva Url
566 * @param artifactInfo
569 protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
570 throws RepositoryAdminException
572 StringBuilder sb = new StringBuilder();
573 if ( StringUtils.startsWith( artifactInfo.getContext(), "remote-" ) )
575 // it's a remote index result we search a managed which proxying this remote and on which
576 // current user has read karma
577 String managedRepoId =
578 getManagedRepoId( StringUtils.substringAfter( artifactInfo.getContext(), "remote-" ), selectedRepos );
579 if ( managedRepoId != null )
581 sb.append( '/' ).append( managedRepoId );
582 artifactInfo.setContext( managedRepoId );
587 sb.append( '/' ).append( artifactInfo.getContext() );
590 sb.append( '/' ).append( StringUtils.replaceChars( artifactInfo.getGroupId(), '.', '/' ) );
591 sb.append( '/' ).append( artifactInfo.getArtifactId() );
592 sb.append( '/' ).append( artifactInfo.getVersion() );
593 sb.append( '/' ).append( artifactInfo.getArtifactId() );
594 sb.append( '-' ).append( artifactInfo.getVersion() );
595 if ( StringUtils.isNotBlank( artifactInfo.getClassifier() ) )
597 sb.append( '-' ).append( artifactInfo.getClassifier() );
599 // maven-plugin packaging is a jar
600 if ( StringUtils.equals( "maven-plugin", artifactInfo.getPackaging() ) )
606 sb.append( '.' ).append( artifactInfo.getPackaging() );
609 return sb.toString();
613 * return a managed repo for a remote result
616 * @param selectedRepos
618 * @throws RepositoryAdminException
620 private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
621 throws RepositoryAdminException
623 Map<String, List<ProxyConnector>> proxyConnectorMap = proxyConnectorAdmin.getProxyConnectorAsMap();
624 if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
628 if ( selectedRepos != null && !selectedRepos.isEmpty() )
630 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
632 if ( selectedRepos.contains( entry.getKey() ) )
634 for ( ProxyConnector proxyConnector : entry.getValue() )
636 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
638 return proxyConnector.getSourceRepoId();
645 // we don't find in search selected repos so return the first one
646 for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
649 for ( ProxyConnector proxyConnector : entry.getValue() )
651 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
653 return proxyConnector.getSourceRepoId();
661 private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
662 List<? extends ArtifactInfoFilter> artifactInfoFilters,
663 Map<String, SearchResultHit> currentResult )
665 if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
670 for ( ArtifactInfoFilter filter : artifactInfoFilters )
672 if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
680 protected SearchResults paginate( SearchResults results )
682 SearchResultLimits limits = results.getLimits();
683 SearchResults paginated = new SearchResults();
685 // ( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
687 int fetchCount = limits.getPageSize();
688 int offset = ( limits.getSelectedPage() * limits.getPageSize() );
690 if ( fetchCount > results.getTotalHits() )
692 fetchCount = results.getTotalHits();
696 if ( offset < results.getTotalHits() )
698 // only process if the offset is within the hit count.
699 for ( int i = 0; i < fetchCount; i++ )
701 // Stop fetching if we are past the total # of available hits.
702 if ( offset + i >= results.getHits().size() )
707 SearchResultHit hit = results.getHits().get( ( offset + i ) );
710 String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
711 hit.getPackaging() );
712 paginated.addHit( id, hit );
720 paginated.setTotalHits( results.getTotalHits() );
721 paginated.setReturnedHitsCount( paginated.getHits().size() );
722 paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
723 paginated.setLimits( limits );