]> source.dussan.org Git - archiva.git/blob
64db78594d227036fd5436f65f9b1cfe48d54513
[archiva.git] /
1 package org.apache.archiva.indexer.search;
2
3 /*
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
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
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
19  * under the License.
20  */
21
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;
31
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;
52
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;
60 import java.util.Map;
61 import java.util.Set;
62
63 /**
64  * RepositorySearch implementation which uses the Maven Indexer for searching.
65  */
66 @Service( "repositorySearch#maven" )
67 public class MavenRepositorySearch
68     implements RepositorySearch
69 {
70     private Logger log = LoggerFactory.getLogger( getClass() );
71
72     private NexusIndexer indexer;
73
74     private QueryCreator queryCreator;
75
76     private ManagedRepositoryAdmin managedRepositoryAdmin;
77
78     private ProxyConnectorAdmin proxyConnectorAdmin;
79
80     private MavenIndexerUtils mavenIndexerUtils;
81
82     protected MavenRepositorySearch()
83     {
84         // for test purpose
85     }
86
87     @Inject
88     public MavenRepositorySearch( NexusIndexer nexusIndexer, ManagedRepositoryAdmin managedRepositoryAdmin,
89                                   MavenIndexerUtils mavenIndexerUtils, ProxyConnectorAdmin proxyConnectorAdmin,
90                                   QueryCreator queryCreator)
91         throws PlexusSisuBridgeException
92     {
93         this.indexer = nexusIndexer;
94         this.queryCreator = queryCreator;
95         this.managedRepositoryAdmin = managedRepositoryAdmin;
96         this.mavenIndexerUtils = mavenIndexerUtils;
97         this.proxyConnectorAdmin = proxyConnectorAdmin;
98     }
99
100     /**
101      * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
102      */
103     @Override
104     public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
105                                  List<String> previousSearchTerms )
106         throws RepositorySearchException
107     {
108         List<String> indexingContextIds = addIndexingContexts( selectedRepos );
109
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();
114
115         if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
116         {
117             constructQuery( term, q );
118         }
119         else
120         {
121             for ( String previousTerm : previousSearchTerms )
122             {
123                 BooleanQuery iQuery = new BooleanQuery();
124                 constructQuery( previousTerm, iQuery );
125
126                 q.add( iQuery, BooleanClause.Occur.MUST );
127             }
128
129             BooleanQuery iQuery = new BooleanQuery();
130             constructQuery( term, iQuery );
131             q.add( iQuery, BooleanClause.Occur.MUST );
132         }
133
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 );
137
138     }
139
140     /**
141      * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
142      */
143     @Override
144     public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
145         throws RepositorySearchException
146     {
147         if ( searchFields.getRepositories() == null )
148         {
149             throw new RepositorySearchException( "Repositories cannot be null." );
150         }
151
152         List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
153
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() ) )
158         {
159             return new SearchResults();
160         }
161
162         BooleanQuery q = new BooleanQuery();
163         if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
164         {
165             q.add( indexer.constructQuery( MAVEN.GROUP_ID, searchFields.isExactSearch()
166                                                ? new SourcedSearchExpression( searchFields.getGroupId() )
167                                                : new UserInputSearchExpression( searchFields.getGroupId() )
168                    ), BooleanClause.Occur.MUST
169             );
170         }
171
172         if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
173         {
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
179             );
180         }
181
182         if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
183         {
184             q.add( indexer.constructQuery( MAVEN.VERSION, searchFields.isExactSearch() ? new SourcedSearchExpression(
185                 searchFields.getVersion() ) : new SourcedSearchExpression( searchFields.getVersion() ) ), BooleanClause.Occur.MUST );
186         }
187
188         if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
189         {
190             q.add( indexer.constructQuery( MAVEN.PACKAGING, searchFields.isExactSearch() ? new SourcedSearchExpression(
191                        searchFields.getPackaging() ) : new UserInputSearchExpression( searchFields.getPackaging() ) ),
192                    BooleanClause.Occur.MUST
193             );
194         }
195
196         if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
197         {
198             q.add( indexer.constructQuery( MAVEN.CLASSNAMES,
199                                            new UserInputSearchExpression( searchFields.getClassName() ) ), BooleanClause.Occur.MUST );
200         }
201
202         if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
203         {
204             q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
205                                            new UserInputSearchExpression( searchFields.getBundleSymbolicName() ) ),
206                    BooleanClause.Occur.MUST
207             );
208         }
209
210         if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
211         {
212             q.add( indexer.constructQuery( OSGI.VERSION,
213                                            new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
214                    BooleanClause.Occur.MUST
215             );
216         }
217
218         if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
219         {
220             q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
221                                            new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
222                    Occur.MUST
223             );
224         }
225
226         if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
227         {
228             q.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
229                                            new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
230                    Occur.MUST
231             );
232         }
233
234         if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
235         {
236             q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
237                                            new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
238                    Occur.MUST
239             );
240         }
241
242         if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
243         {
244             q.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
245                    Occur.MUST );
246         }
247
248         if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
249         {
250             q.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
251                                            new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
252                    Occur.MUST
253             );
254         }
255
256         if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
257         {
258             q.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
259                                            new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
260                    Occur.MUST
261             );
262         }
263
264         if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
265         {
266             q.add( indexer.constructQuery( MAVEN.CLASSIFIER, searchFields.isExactSearch() ? new SourcedSearchExpression(
267                        searchFields.getClassifier() ) : new UserInputSearchExpression( searchFields.getClassifier() ) ),
268                    Occur.MUST
269             );
270         }
271         else if ( searchFields.isExactSearch() )
272         {
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
275         }
276
277         if ( q.getClauses() == null || q.getClauses().length <= 0 )
278         {
279             throw new RepositorySearchException( "No search fields set." );
280         }
281
282         return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
283                        searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
284     }
285
286     private static class NullSearch implements SearchTyped, SearchExpression
287     {
288         private static final NullSearch INSTANCE = new NullSearch();
289
290         @Override
291         public String getStringValue()
292         {
293             return "[[NULL_VALUE]]";
294         }
295
296         @Override
297         public SearchType getSearchType()
298         {
299             return SearchType.EXACT;
300         }
301     }
302
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
307     {
308
309         try
310         {
311             FlatSearchRequest request = new FlatSearchRequest( q );
312
313             request.setContexts( getIndexingContexts( indexingContextIds ) );
314             if ( limits != null )
315             {
316                 // we apply limits only when first page asked
317                 if ( limits.getSelectedPage() == 0 )
318                 {
319                     request.setCount( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
320                 }
321             }
322
323             FlatSearchResponse response = indexer.searchFlat( request );
324
325             if ( response == null || response.getTotalHits() == 0 )
326             {
327                 SearchResults results = new SearchResults();
328                 results.setLimits( limits );
329                 return results;
330             }
331
332             return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
333         }
334         catch ( IOException e )
335         {
336             throw new RepositorySearchException( e.getMessage(), e );
337         }
338         catch ( RepositoryAdminException e )
339         {
340             throw new RepositorySearchException( e.getMessage(), e );
341         }
342
343     }
344
345     private List<IndexingContext> getIndexingContexts( List<String> ids )
346     {
347         List<IndexingContext> contexts = new ArrayList<>( ids.size() );
348
349         for ( String id : ids )
350         {
351             IndexingContext context = indexer.getIndexingContexts().get( id );
352             if ( context != null )
353             {
354                 contexts.add( context );
355             }
356             else
357             {
358                 log.warn( "context with id {} not exists", id );
359             }
360         }
361
362         return contexts;
363     }
364
365     private void constructQuery( String term, BooleanQuery q )
366     {
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 );
372
373         //Query query =
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 );
378     }
379
380
381     /**
382      * @param selectedRepos
383      * @return indexing contextId used
384      */
385     private List<String> addIndexingContexts( List<String> selectedRepos )
386     {
387         Set<String> indexingContextIds = new HashSet<>();
388         for ( String repo : selectedRepos )
389         {
390             try
391             {
392                 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
393
394                 if ( repoConfig != null )
395                 {
396
397                     IndexingContext context = managedRepositoryAdmin.createIndexContext( repoConfig );
398                     if ( context.isSearchable() )
399                     {
400                         indexingContextIds.addAll( getRemoteIndexingContextIds( repo ) );
401                         indexingContextIds.add( context.getId() );
402                     }
403                     else
404                     {
405                         log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
406                     }
407
408                 }
409                 else
410                 {
411                     log.warn( "Repository '{}' not found in configuration.", repo );
412                 }
413             }
414             catch ( RepositoryAdminException e )
415             {
416                 log.warn( "RepositoryAdminException occured while accessing index of repository '{}' : {}", repo,
417                           e.getMessage() );
418                 continue;
419             }
420         }
421
422         return new ArrayList<>( indexingContextIds );
423     }
424
425
426     @Override
427     public Set<String> getRemoteIndexingContextIds( String managedRepoId )
428         throws RepositoryAdminException
429     {
430         Set<String> ids = new HashSet<>();
431
432         List<ProxyConnector> proxyConnectors = proxyConnectorAdmin.getProxyConnectorAsMap().get( managedRepoId );
433
434         if ( proxyConnectors == null || proxyConnectors.isEmpty() )
435         {
436             return ids;
437         }
438
439         for ( ProxyConnector proxyConnector : proxyConnectors )
440         {
441             String remoteId = "remote-" + proxyConnector.getTargetRepoId();
442             IndexingContext context = indexer.getIndexingContexts().get( remoteId );
443             if ( context != null && context.isSearchable() )
444             {
445                 ids.add( remoteId );
446             }
447         }
448
449         return ids;
450     }
451
452     @Override
453     public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
454         throws RepositorySearchException
455     {
456         List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
457
458         if ( indexContexts == null || indexContexts.isEmpty() )
459         {
460             return Collections.emptyList();
461         }
462
463         try
464         {
465             Set<String> allGroupIds = new HashSet<>();
466             for ( IndexingContext indexingContext : indexContexts )
467             {
468                 allGroupIds.addAll( indexingContext.getAllGroups() );
469             }
470             return allGroupIds;
471         }
472         catch ( IOException e )
473         {
474             throw new RepositorySearchException( e.getMessage(), e );
475         }
476
477     }
478
479
480     protected List<? extends IndexCreator> getAllIndexCreators()
481     {
482         return mavenIndexerUtils.getAllIndexCreators();
483     }
484
485
486     private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
487                                                   List<? extends ArtifactInfoFilter> artifactInfoFilters,
488                                                   List<String> selectedRepos, boolean includePoms )
489         throws RepositoryAdminException
490     {
491         SearchResults results = new SearchResults();
492         Set<ArtifactInfo> artifactInfos = response.getResults();
493
494         for ( ArtifactInfo artifactInfo : artifactInfos )
495         {
496             if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.getFileExtension() ) && !includePoms )
497             {
498                 continue;
499             }
500             String id = SearchUtil.getHitId( artifactInfo.getGroupId(), //
501                                              artifactInfo.getArtifactId(), //
502                                              artifactInfo.getClassifier(), //
503                                              artifactInfo.getPackaging() );
504             Map<String, SearchResultHit> hitsMap = results.getHitsMap();
505
506             if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
507             {
508                 continue;
509             }
510
511             SearchResultHit hit = hitsMap.get( id );
512             if ( hit != null )
513             {
514                 if ( !hit.getVersions().contains( artifactInfo.getVersion() ) )
515                 {
516                     hit.addVersion( artifactInfo.getVersion() );
517                 }
518             }
519             else
520             {
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 ) );
543             }
544
545             results.addHit( id, hit );
546         }
547
548         results.setTotalHits( response.getTotalHitsCount() );
549         results.setTotalHitsMapSize( results.getHitsMap().values().size() );
550         results.setReturnedHitsCount( response.getReturnedHitsCount() );
551         results.setLimits( limits );
552
553         if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
554         {
555             return results;
556         }
557         else
558         {
559             return paginate( results );
560         }
561     }
562
563     /**
564      * calculate baseUrl without the context and base Archiva Url
565      *
566      * @param artifactInfo
567      * @return
568      */
569     protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
570         throws RepositoryAdminException
571     {
572         StringBuilder sb = new StringBuilder();
573         if ( StringUtils.startsWith( artifactInfo.getContext(), "remote-" ) )
574         {
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 )
580             {
581                 sb.append( '/' ).append( managedRepoId );
582                 artifactInfo.setContext( managedRepoId );
583             }
584         }
585         else
586         {
587             sb.append( '/' ).append( artifactInfo.getContext() );
588         }
589
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() ) )
596         {
597             sb.append( '-' ).append( artifactInfo.getClassifier() );
598         }
599         // maven-plugin packaging is a jar
600         if ( StringUtils.equals( "maven-plugin", artifactInfo.getPackaging() ) )
601         {
602             sb.append( "jar" );
603         }
604         else
605         {
606             sb.append( '.' ).append( artifactInfo.getPackaging() );
607         }
608
609         return sb.toString();
610     }
611
612     /**
613      * return a managed repo for a remote result
614      *
615      * @param remoteRepo
616      * @param selectedRepos
617      * @return
618      * @throws RepositoryAdminException
619      */
620     private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
621         throws RepositoryAdminException
622     {
623         Map<String, List<ProxyConnector>> proxyConnectorMap = proxyConnectorAdmin.getProxyConnectorAsMap();
624         if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
625         {
626             return null;
627         }
628         if ( selectedRepos != null && !selectedRepos.isEmpty() )
629         {
630             for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
631             {
632                 if ( selectedRepos.contains( entry.getKey() ) )
633                 {
634                     for ( ProxyConnector proxyConnector : entry.getValue() )
635                     {
636                         if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
637                         {
638                             return proxyConnector.getSourceRepoId();
639                         }
640                     }
641                 }
642             }
643         }
644
645         // we don't find in search selected repos so return the first one
646         for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
647         {
648
649             for ( ProxyConnector proxyConnector : entry.getValue() )
650             {
651                 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepoId() ) )
652                 {
653                     return proxyConnector.getSourceRepoId();
654                 }
655             }
656
657         }
658         return null;
659     }
660
661     private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
662                                               List<? extends ArtifactInfoFilter> artifactInfoFilters,
663                                               Map<String, SearchResultHit> currentResult )
664     {
665         if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
666         {
667             return true;
668         }
669
670         for ( ArtifactInfoFilter filter : artifactInfoFilters )
671         {
672             if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
673             {
674                 return false;
675             }
676         }
677         return true;
678     }
679
680     protected SearchResults paginate( SearchResults results )
681     {
682         SearchResultLimits limits = results.getLimits();
683         SearchResults paginated = new SearchResults();
684
685         // ( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
686
687         int fetchCount = limits.getPageSize();
688         int offset = ( limits.getSelectedPage() * limits.getPageSize() );
689
690         if ( fetchCount > results.getTotalHits() )
691         {
692             fetchCount = results.getTotalHits();
693         }
694
695         // Goto offset.
696         if ( offset < results.getTotalHits() )
697         {
698             // only process if the offset is within the hit count.
699             for ( int i = 0; i < fetchCount; i++ )
700             {
701                 // Stop fetching if we are past the total # of available hits.
702                 if ( offset + i >= results.getHits().size() )
703                 {
704                     break;
705                 }
706
707                 SearchResultHit hit = results.getHits().get( ( offset + i ) );
708                 if ( hit != null )
709                 {
710                     String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
711                                                      hit.getPackaging() );
712                     paginated.addHit( id, hit );
713                 }
714                 else
715                 {
716                     break;
717                 }
718             }
719         }
720         paginated.setTotalHits( results.getTotalHits() );
721         paginated.setReturnedHitsCount( paginated.getHits().size() );
722         paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
723         paginated.setLimits( limits );
724
725         return paginated;
726     }
727
728
729 }