]> source.dussan.org Git - archiva.git/blob
ff594757cca0686d07d4bf922aba80c94bd88312
[archiva.git] /
1 package org.apache.archiva.indexer.maven.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.indexer.UnsupportedBaseContextException;
23 import org.apache.archiva.indexer.search.ArtifactInfoFilter;
24 import org.apache.archiva.indexer.search.NoClassifierArtifactInfoFilter;
25 import org.apache.archiva.indexer.search.RepositorySearch;
26 import org.apache.archiva.indexer.search.RepositorySearchException;
27 import org.apache.archiva.indexer.search.SearchFields;
28 import org.apache.archiva.indexer.search.SearchResultHit;
29 import org.apache.archiva.indexer.search.SearchResultLimits;
30 import org.apache.archiva.indexer.search.SearchResults;
31 import org.apache.archiva.indexer.util.SearchUtil;
32 import org.apache.archiva.model.ArchivaArtifactModel;
33 import org.apache.archiva.proxy.ProxyRegistry;
34 import org.apache.archiva.proxy.model.ProxyConnector;
35 import org.apache.archiva.repository.RemoteRepository;
36 import org.apache.archiva.repository.Repository;
37 import org.apache.archiva.repository.RepositoryRegistry;
38 import org.apache.archiva.repository.RepositoryType;
39 import org.apache.commons.lang3.StringUtils;
40 import org.apache.maven.index.ArtifactInfo;
41 import org.apache.maven.index.FlatSearchRequest;
42 import org.apache.maven.index.FlatSearchResponse;
43 import org.apache.maven.index.Indexer;
44 import org.apache.maven.index.MAVEN;
45 import org.apache.maven.index.OSGI;
46 import org.apache.maven.index.QueryCreator;
47 import org.apache.maven.index.SearchType;
48 import org.apache.maven.index.context.IndexingContext;
49 import org.apache.maven.index.expr.SearchExpression;
50 import org.apache.maven.index.expr.SearchTyped;
51 import org.apache.maven.index.expr.SourcedSearchExpression;
52 import org.apache.maven.index.expr.UserInputSearchExpression;
53 import org.apache.maven.index_shaded.lucene.search.BooleanClause;
54 import org.apache.maven.index_shaded.lucene.search.BooleanClause.Occur;
55 import org.apache.maven.index_shaded.lucene.search.BooleanQuery;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.stereotype.Service;
59
60 import javax.inject.Inject;
61 import java.io.IOException;
62 import java.util.ArrayList;
63 import java.util.Collection;
64 import java.util.Collections;
65 import java.util.HashSet;
66 import java.util.List;
67 import java.util.Map;
68 import java.util.Set;
69
70 /**
71  * RepositorySearch implementation which uses the Maven Indexer for searching.
72  */
73 @Service( "repositorySearch#maven" )
74 public class MavenRepositorySearch
75     implements RepositorySearch
76 {
77     private Logger log = LoggerFactory.getLogger( getClass() );
78
79     private Indexer indexer;
80
81     private QueryCreator queryCreator;
82
83
84     private RepositoryRegistry repositoryRegistry;
85
86     private ProxyRegistry proxyRegistry;
87
88     protected MavenRepositorySearch()
89     {
90         // for test purpose
91     }
92
93     @Inject
94     public MavenRepositorySearch( Indexer nexusIndexer, RepositoryRegistry repositoryRegistry,
95                                   ProxyRegistry proxyRegistry, QueryCreator queryCreator )
96     {
97         this.indexer = nexusIndexer;
98         this.queryCreator = queryCreator;
99         this.repositoryRegistry = repositoryRegistry;
100         this.proxyRegistry = proxyRegistry;
101     }
102
103     /**
104      * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
105      */
106     @Override
107     public SearchResults search(String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
108                                 List<String> previousSearchTerms )
109         throws RepositorySearchException
110     {
111         List<String> indexingContextIds = addIndexingContexts( selectedRepos );
112
113         // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
114         //      resulting to more wildcard searches so we need to increase max clause count
115         BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
116         BooleanQuery.Builder qb = new BooleanQuery.Builder();
117
118         if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
119         {
120             constructQuery( term, qb );
121         }
122         else
123         {
124             for ( String previousTerm : previousSearchTerms )
125             {
126                 BooleanQuery.Builder iQuery = new BooleanQuery.Builder();
127                 constructQuery( previousTerm, iQuery );
128
129                 qb.add( iQuery.build(), BooleanClause.Occur.MUST );
130             }
131
132             BooleanQuery.Builder iQuery = new BooleanQuery.Builder();
133             constructQuery( term, iQuery );
134             qb.add( iQuery.build(), BooleanClause.Occur.MUST );
135         }
136
137         // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
138         // FIXME  cannot find a way currently to setup this in constructQuery !!!
139         return search( limits, qb.build(), indexingContextIds, NoClassifierArtifactInfoFilter.LIST, selectedRepos, true );
140
141     }
142
143     /**
144      * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
145      */
146     @SuppressWarnings( "deprecation" )
147     @Override
148     public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
149         throws RepositorySearchException
150     {
151         if ( searchFields.getRepositories() == null )
152         {
153             throw new RepositorySearchException( "Repositories cannot be null." );
154         }
155
156         List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
157
158         // if no index found in the specified ones return an empty search result instead of doing a search on all index
159         // olamy: IMHO doesn't make sense
160         if ( !searchFields.getRepositories().isEmpty() && ( indexingContextIds == null
161             || indexingContextIds.isEmpty() ) )
162         {
163             return new SearchResults();
164         }
165
166         BooleanQuery.Builder qb = new BooleanQuery.Builder();
167         if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
168         {
169             qb.add( indexer.constructQuery( MAVEN.GROUP_ID, searchFields.isExactSearch() ? new SourcedSearchExpression(
170                        searchFields.getGroupId() ) : new UserInputSearchExpression( searchFields.getGroupId() ) ),
171                    BooleanClause.Occur.MUST );
172         }
173
174         if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
175         {
176             qb.add( indexer.constructQuery( MAVEN.ARTIFACT_ID,
177                                            searchFields.isExactSearch()
178                                                ? new SourcedSearchExpression( searchFields.getArtifactId() )
179                                                : new UserInputSearchExpression( searchFields.getArtifactId() ) ),
180                    BooleanClause.Occur.MUST );
181         }
182
183         if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
184         {
185             qb.add( indexer.constructQuery( MAVEN.VERSION, searchFields.isExactSearch() ? new SourcedSearchExpression(
186                        searchFields.getVersion() ) : new SourcedSearchExpression( searchFields.getVersion() ) ),
187                    BooleanClause.Occur.MUST );
188         }
189
190         if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
191         {
192             qb.add( indexer.constructQuery( MAVEN.PACKAGING, searchFields.isExactSearch() ? new SourcedSearchExpression(
193                        searchFields.getPackaging() ) : new UserInputSearchExpression( searchFields.getPackaging() ) ),
194                    BooleanClause.Occur.MUST );
195         }
196
197         if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
198         {
199             qb.add( indexer.constructQuery( MAVEN.CLASSNAMES,
200                                            new UserInputSearchExpression( searchFields.getClassName() ) ),
201                    BooleanClause.Occur.MUST );
202         }
203
204         if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
205         {
206             qb.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
207                                            new UserInputSearchExpression( searchFields.getBundleSymbolicName() ) ),
208                    BooleanClause.Occur.MUST );
209         }
210
211         if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
212         {
213             qb.add( indexer.constructQuery( OSGI.VERSION,
214                                            new UserInputSearchExpression( searchFields.getBundleVersion() ) ),
215                    BooleanClause.Occur.MUST );
216         }
217
218         if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
219         {
220             qb.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
221                                            new UserInputSearchExpression( searchFields.getBundleExportPackage() ) ),
222                    Occur.MUST );
223         }
224
225         if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
226         {
227             qb.add( indexer.constructQuery( OSGI.EXPORT_SERVICE,
228                                            new UserInputSearchExpression( searchFields.getBundleExportService() ) ),
229                    Occur.MUST );
230         }
231
232         if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
233         {
234             qb.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
235                                            new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
236                    Occur.MUST );
237         }
238
239         if ( StringUtils.isNotBlank( searchFields.getBundleName() ) )
240         {
241             qb.add( indexer.constructQuery( OSGI.NAME, new UserInputSearchExpression( searchFields.getBundleName() ) ),
242                    Occur.MUST );
243         }
244
245         if ( StringUtils.isNotBlank( searchFields.getBundleImportPackage() ) )
246         {
247             qb.add( indexer.constructQuery( OSGI.IMPORT_PACKAGE,
248                                            new UserInputSearchExpression( searchFields.getBundleImportPackage() ) ),
249                    Occur.MUST );
250         }
251
252         if ( StringUtils.isNotBlank( searchFields.getBundleRequireBundle() ) )
253         {
254             qb.add( indexer.constructQuery( OSGI.REQUIRE_BUNDLE,
255                                            new UserInputSearchExpression( searchFields.getBundleRequireBundle() ) ),
256                    Occur.MUST );
257         }
258
259         if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
260         {
261             qb.add( indexer.constructQuery( MAVEN.CLASSIFIER, searchFields.isExactSearch() ? new SourcedSearchExpression(
262                        searchFields.getClassifier() ) : new UserInputSearchExpression( searchFields.getClassifier() ) ),
263                    Occur.MUST );
264         }
265         else if ( searchFields.isExactSearch() )
266         {
267             //TODO improvement in case of exact search and no classifier we must query for classifier with null value
268             // currently it's done in DefaultSearchService with some filtering
269         }
270
271         BooleanQuery qu = qb.build();
272         if ( qu.clauses() == null || qu.clauses().size() <= 0 )
273         {
274             throw new RepositorySearchException( "No search fields set." );
275         }
276         if (qu.clauses()!=null) {
277             log.debug("CLAUSES ", qu.clauses());
278             for (BooleanClause cl : qu.clauses()) {
279                 log.debug("Clause ",cl);
280             }
281         }
282
283         return search( limits, qu, indexingContextIds, Collections.<ArtifactInfoFilter>emptyList(),
284                        searchFields.getRepositories(), searchFields.isIncludePomArtifacts() );
285     }
286
287     private static class NullSearch
288         implements SearchTyped, SearchExpression
289     {
290         private static final NullSearch INSTANCE = new NullSearch();
291
292         @Override
293         public String getStringValue()
294         {
295             return "[[NULL_VALUE]]";
296         }
297
298         @Override
299         public SearchType getSearchType()
300         {
301             return SearchType.EXACT;
302         }
303     }
304
305     private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
306                                   List<? extends ArtifactInfoFilter> filters, List<String> selectedRepos,
307                                   boolean includePoms )
308         throws RepositorySearchException
309     {
310
311         try
312         {
313             FlatSearchRequest request = new FlatSearchRequest( q );
314
315             request.setContexts( getIndexingContexts( indexingContextIds ) );
316             if ( limits != null )
317             {
318                 // we apply limits only when first page asked
319                 if ( limits.getSelectedPage() == 0 )
320                 {
321                     request.setCount( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
322                 }
323             }
324
325             FlatSearchResponse response = indexer.searchFlat( request );
326
327             if ( response == null || response.getTotalHitsCount() == 0 )
328             {
329                 SearchResults results = new SearchResults();
330                 results.setLimits( limits );
331                 return results;
332             }
333
334             return convertToSearchResults( response, limits, filters, selectedRepos, includePoms );
335         }
336         catch ( IOException e )
337         {
338             throw new RepositorySearchException( e.getMessage(), e );
339         }
340
341     }
342
343     private IndexingContext getIndexingContext(String id) {
344         String repoId;
345         if (StringUtils.startsWith(id, "remote-")) {
346             repoId = StringUtils.substringAfter(id, "remote-");
347         } else {
348             repoId = id;
349         }
350         Repository repo = repositoryRegistry.getRepository(repoId);
351         if (repo==null) {
352             return null;
353         } else {
354             if (repo.getIndexingContext()!=null) {
355                 try {
356                     return repo.getIndexingContext().getBaseContext(IndexingContext.class);
357                 } catch (UnsupportedBaseContextException e) {
358                     return null;
359                 }
360             } else {
361                 return null;
362             }
363         }
364     }
365
366     private List<IndexingContext> getIndexingContexts( List<String> ids )
367     {
368         List<IndexingContext> contexts = new ArrayList<>( ids.size() );
369
370         for ( String id : ids )
371         {
372             IndexingContext context = getIndexingContext(id);
373             if ( context != null )
374             {
375                 contexts.add( context );
376             }
377             else
378             {
379                 log.warn( "context with id {} not exists", id );
380             }
381         }
382
383         return contexts;
384     }
385
386     private void constructQuery( String term, BooleanQuery.Builder q )
387     {
388         q.add( indexer.constructQuery( MAVEN.GROUP_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
389         q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new UserInputSearchExpression( term ) ), Occur.SHOULD );
390         q.add( indexer.constructQuery( MAVEN.VERSION, new UserInputSearchExpression( term ) ), Occur.SHOULD );
391         q.add( indexer.constructQuery( MAVEN.PACKAGING, new UserInputSearchExpression( term ) ), Occur.SHOULD );
392         q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new UserInputSearchExpression( term ) ), Occur.SHOULD );
393
394         //Query query =
395         //    new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
396         //q.add( query, Occur.MUST_NOT );
397         // olamy IMHO we could set this option as at least one must match
398         //q.setMinimumNumberShouldMatch( 1 );
399     }
400
401
402     /**
403      * @param selectedRepos
404      * @return indexing contextId used
405      */
406     private List<String> addIndexingContexts( List<String> selectedRepos )
407     {
408         Set<String> indexingContextIds = new HashSet<>();
409         for ( String repo : selectedRepos )
410         {
411             try
412             {
413                 Repository rRepo = repositoryRegistry.getRepository(repo);
414
415                 if ( rRepo != null )
416                 {
417
418                     if (rRepo.getType().equals(RepositoryType.MAVEN)) {
419                         assert rRepo.getIndexingContext() != null;
420                         IndexingContext context = rRepo.getIndexingContext().getBaseContext(IndexingContext.class);
421                         if (context.isSearchable()) {
422                             indexingContextIds.addAll(getRemoteIndexingContextIds(repo));
423                             indexingContextIds.add(context.getId());
424                         } else {
425                             log.warn("indexingContext with id {} not searchable", rRepo.getId());
426                         }
427                     }
428
429                 }
430                 else
431                 {
432                     log.warn( "Repository '{}' not found in configuration.", repo );
433                 }
434             }
435             catch ( RepositorySearchException e )
436             {
437                 log.warn( "RepositorySearchException occured while accessing index of repository '{}' : {}", repo,
438                     e.getMessage() );
439                 continue;
440             } catch (UnsupportedBaseContextException e) {
441                 log.error("Fatal situation: Maven repository without IndexingContext found.");
442                 continue;
443             }
444         }
445
446         return new ArrayList<>( indexingContextIds );
447     }
448
449
450     @Override
451     public Set<String> getRemoteIndexingContextIds( String managedRepoId )
452         throws RepositorySearchException
453     {
454         Set<String> ids = new HashSet<>();
455
456         List<ProxyConnector> proxyConnectors = null;
457         proxyConnectors = proxyRegistry.getProxyConnectorAsMap( ).get( managedRepoId );
458
459         if ( proxyConnectors == null || proxyConnectors.isEmpty() )
460         {
461             return ids;
462         }
463
464         for ( ProxyConnector proxyConnector : proxyConnectors )
465         {
466             String remoteId = "remote-" + proxyConnector.getTargetRepository().getId();
467             RemoteRepository repo = repositoryRegistry.getRemoteRepository(proxyConnector.getTargetRepository().getId());
468             if (repo.getType()==RepositoryType.MAVEN) {
469                 try {
470                     IndexingContext context = repo.getIndexingContext() != null ? repo.getIndexingContext().getBaseContext(IndexingContext.class) : null;
471                     if (context!=null && context.isSearchable()) {
472                         ids.add(remoteId);
473                     }
474                 } catch (UnsupportedBaseContextException e) {
475                     // Ignore this one
476                 }
477             }
478         }
479
480         return ids;
481     }
482
483     @Override
484     public Collection<String> getAllGroupIds( String principal, List<String> selectedRepos )
485         throws RepositorySearchException
486     {
487         List<IndexingContext> indexContexts = getIndexingContexts( selectedRepos );
488
489         if ( indexContexts == null || indexContexts.isEmpty() )
490         {
491             return Collections.emptyList();
492         }
493
494         try
495         {
496             Set<String> allGroupIds = new HashSet<>();
497             for ( IndexingContext indexingContext : indexContexts )
498             {
499                 allGroupIds.addAll( indexingContext.getAllGroups() );
500             }
501             return allGroupIds;
502         }
503         catch ( IOException e )
504         {
505             throw new RepositorySearchException( e.getMessage(), e );
506         }
507
508     }
509
510     private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
511                                                   List<? extends ArtifactInfoFilter> artifactInfoFilters,
512                                                   List<String> selectedRepos, boolean includePoms )
513     {
514         SearchResults results = new SearchResults();
515         Set<ArtifactInfo> artifactInfos = response.getResults();
516
517         for ( ArtifactInfo artifactInfo : artifactInfos )
518         {
519             if ( StringUtils.equalsIgnoreCase( "pom", artifactInfo.getFileExtension() ) && !includePoms )
520             {
521                 continue;
522             }
523             String id = SearchUtil.getHitId( artifactInfo.getGroupId(), //
524                                              artifactInfo.getArtifactId(), //
525                                              artifactInfo.getClassifier(), //
526                                              artifactInfo.getPackaging() );
527             Map<String, SearchResultHit> hitsMap = results.getHitsMap();
528
529
530             if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilters, hitsMap ) )
531             {
532                 continue;
533             }
534
535             SearchResultHit hit = hitsMap.get( id );
536             if ( hit != null )
537             {
538                 if ( !hit.getVersions().contains( artifactInfo.getVersion() ) )
539                 {
540                     hit.addVersion( artifactInfo.getVersion() );
541                 }
542             }
543             else
544             {
545                 hit = new SearchResultHit();
546                 hit.setArtifactId( artifactInfo.getArtifactId() );
547                 hit.setGroupId( artifactInfo.getGroupId() );
548                 hit.setRepositoryId( artifactInfo.getRepository() );
549                 hit.addVersion( artifactInfo.getVersion() );
550                 hit.setBundleExportPackage( artifactInfo.getBundleExportPackage() );
551                 hit.setBundleExportService( artifactInfo.getBundleExportService() );
552                 hit.setBundleSymbolicName( artifactInfo.getBundleSymbolicName() );
553                 hit.setBundleVersion( artifactInfo.getBundleVersion() );
554                 hit.setBundleDescription( artifactInfo.getBundleDescription() );
555                 hit.setBundleDocUrl( artifactInfo.getBundleDocUrl() );
556                 hit.setBundleRequireBundle( artifactInfo.getBundleRequireBundle() );
557                 hit.setBundleImportPackage( artifactInfo.getBundleImportPackage() );
558                 hit.setBundleLicense( artifactInfo.getBundleLicense() );
559                 hit.setBundleName( artifactInfo.getBundleName() );
560                 hit.setContext( artifactInfo.getContext() );
561                 hit.setGoals( artifactInfo.getGoals() );
562                 hit.setPrefix( artifactInfo.getPrefix() );
563                 hit.setPackaging( artifactInfo.getPackaging() );
564                 hit.setClassifier( artifactInfo.getClassifier() );
565                 hit.setFileExtension( artifactInfo.getFileExtension() );
566                 hit.setUrl( getBaseUrl( artifactInfo, selectedRepos ) );
567             }
568
569             results.addHit( id, hit );
570         }
571
572         results.setTotalHits( response.getTotalHitsCount() );
573         results.setTotalHitsMapSize( results.getHitsMap().values().size() );
574         results.setReturnedHitsCount( response.getReturnedHitsCount() );
575         results.setLimits( limits );
576
577         if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
578         {
579             return results;
580         }
581         else
582         {
583             return paginate( results );
584         }
585     }
586
587     /**
588      * calculate baseUrl without the context and base Archiva Url
589      *
590      * @param artifactInfo
591      * @return
592      */
593     protected String getBaseUrl( ArtifactInfo artifactInfo, List<String> selectedRepos )
594     {
595         StringBuilder sb = new StringBuilder();
596         if ( StringUtils.startsWith( artifactInfo.getContext(), "remote-" ) )
597         {
598             // it's a remote index result we search a managed which proxying this remote and on which
599             // current user has read karma
600             String managedRepoId =
601                 getManagedRepoId( StringUtils.substringAfter( artifactInfo.getContext(), "remote-" ), selectedRepos );
602             if ( managedRepoId != null )
603             {
604                 sb.append( '/' ).append( managedRepoId );
605                 artifactInfo.setContext( managedRepoId );
606             }
607         }
608         else
609         {
610             sb.append( '/' ).append( artifactInfo.getContext() );
611         }
612
613         sb.append( '/' ).append( StringUtils.replaceChars( artifactInfo.getGroupId(), '.', '/' ) );
614         sb.append( '/' ).append( artifactInfo.getArtifactId() );
615         sb.append( '/' ).append( artifactInfo.getVersion() );
616         sb.append( '/' ).append( artifactInfo.getArtifactId() );
617         sb.append( '-' ).append( artifactInfo.getVersion() );
618         if ( StringUtils.isNotBlank( artifactInfo.getClassifier() ) )
619         {
620             sb.append( '-' ).append( artifactInfo.getClassifier() );
621         }
622         // maven-plugin packaging is a jar
623         if ( StringUtils.equals( "maven-plugin", artifactInfo.getPackaging() ) )
624         {
625             sb.append( "jar" );
626         }
627         else
628         {
629             sb.append( '.' ).append( artifactInfo.getPackaging() );
630         }
631
632         return sb.toString();
633     }
634
635     /**
636      * return a managed repo for a remote result
637      *
638      * @param remoteRepo
639      * @param selectedRepos
640      * @return
641      */
642     private String getManagedRepoId( String remoteRepo, List<String> selectedRepos )
643     {
644         Map<String, List<ProxyConnector>> proxyConnectorMap = proxyRegistry.getProxyConnectorAsMap();
645         if ( proxyConnectorMap == null || proxyConnectorMap.isEmpty() )
646         {
647             return null;
648         }
649         if ( selectedRepos != null && !selectedRepos.isEmpty() )
650         {
651             for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
652             {
653                 if ( selectedRepos.contains( entry.getKey() ) )
654                 {
655                     for ( ProxyConnector proxyConnector : entry.getValue() )
656                     {
657                         if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepository().getId() ) )
658                         {
659                             return proxyConnector.getSourceRepository().getId();
660                         }
661                     }
662                 }
663             }
664         }
665
666         // we don't find in search selected repos so return the first one
667         for ( Map.Entry<String, List<ProxyConnector>> entry : proxyConnectorMap.entrySet() )
668         {
669
670             for ( ProxyConnector proxyConnector : entry.getValue() )
671             {
672                 if ( StringUtils.equals( remoteRepo, proxyConnector.getTargetRepository().getId() ) )
673                 {
674                     return proxyConnector.getSourceRepository().getId();
675                 }
676             }
677
678         }
679         return null;
680     }
681
682     private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
683                                               List<? extends ArtifactInfoFilter> artifactInfoFilters,
684                                               Map<String, SearchResultHit> currentResult )
685     {
686         if ( artifactInfoFilters == null || artifactInfoFilters.isEmpty() )
687         {
688             return true;
689         }
690
691         ArchivaArtifactModel artifact = new ArchivaArtifactModel();
692         artifact.setArtifactId( artifactInfo.getArtifactId() );
693         artifact.setClassifier( artifactInfo.getClassifier() );
694         artifact.setGroupId( artifactInfo.getGroupId() );
695         artifact.setRepositoryId( artifactInfo.getRepository() );
696         artifact.setVersion( artifactInfo.getVersion() );
697         artifact.setChecksumMD5( artifactInfo.getMd5() );
698         artifact.setChecksumSHA1( artifactInfo.getSha1() );
699         for ( ArtifactInfoFilter filter : artifactInfoFilters )
700         {
701             if ( !filter.addArtifactInResult( artifact, currentResult ) )
702             {
703                 return false;
704             }
705         }
706         return true;
707     }
708
709     protected SearchResults paginate( SearchResults results )
710     {
711         SearchResultLimits limits = results.getLimits();
712         SearchResults paginated = new SearchResults();
713
714         // ( limits.getPageSize() * ( Math.max( 1, limits.getSelectedPage() ) ) );
715
716         int fetchCount = limits.getPageSize();
717         int offset = ( limits.getSelectedPage() * limits.getPageSize() );
718
719         if ( fetchCount > results.getTotalHits() )
720         {
721             fetchCount = results.getTotalHits();
722         }
723
724         // Goto offset.
725         if ( offset < results.getTotalHits() )
726         {
727             // only process if the offset is within the hit count.
728             for ( int i = 0; i < fetchCount; i++ )
729             {
730                 // Stop fetching if we are past the total # of available hits.
731                 if ( offset + i >= results.getHits().size() )
732                 {
733                     break;
734                 }
735
736                 SearchResultHit hit = results.getHits().get( ( offset + i ) );
737                 if ( hit != null )
738                 {
739                     String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
740                                                      hit.getPackaging() );
741                     paginated.addHit( id, hit );
742                 }
743                 else
744                 {
745                     break;
746                 }
747             }
748         }
749         paginated.setTotalHits( results.getTotalHits() );
750         paginated.setReturnedHitsCount( paginated.getHits().size() );
751         paginated.setTotalHitsMapSize( results.getTotalHitsMapSize() );
752         paginated.setLimits( limits );
753
754         return paginated;
755     }
756
757
758 }