]> source.dussan.org Git - archiva.git/blob
cdc906c22d36d07668b53e4fad7a2b08fffb0579
[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.managed.ManagedRepository;
24 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
25 import org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
26 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
27 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
28 import org.apache.archiva.indexer.util.SearchUtil;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.lucene.search.BooleanClause.Occur;
31 import org.apache.lucene.search.BooleanQuery;
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.context.IndexCreator;
39 import org.apache.maven.index.context.IndexingContext;
40 import org.apache.maven.index.context.UnsupportedExistingLuceneIndexException;
41 import org.apache.maven.index.expr.StringSearchExpression;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.stereotype.Service;
45
46 import javax.inject.Inject;
47 import java.io.File;
48 import java.io.IOException;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.List;
52 import java.util.Map;
53 import java.util.Set;
54
55 /**
56  * RepositorySearch implementation which uses the Nexus Indexer for searching.
57  */
58 @Service( "nexusSearch" )
59 public class NexusRepositorySearch
60     implements RepositorySearch
61 {
62     private Logger log = LoggerFactory.getLogger( getClass() );
63
64     private NexusIndexer indexer;
65
66     private ManagedRepositoryAdmin managedRepositoryAdmin;
67
68     private MavenIndexerUtils mavenIndexerUtils;
69
70     @Inject
71     public NexusRepositorySearch( PlexusSisuBridge plexusSisuBridge, ManagedRepositoryAdmin managedRepositoryAdmin,
72                                   MavenIndexerUtils mavenIndexerUtils )
73         throws PlexusSisuBridgeException
74     {
75         this.indexer = plexusSisuBridge.lookup( NexusIndexer.class );
76         this.managedRepositoryAdmin = managedRepositoryAdmin;
77         this.mavenIndexerUtils = mavenIndexerUtils;
78
79     }
80
81     /**
82      * @see RepositorySearch#search(String, List, String, SearchResultLimits, List)
83      */
84     public SearchResults search( String principal, List<String> selectedRepos, String term, SearchResultLimits limits,
85                                  List<String> previousSearchTerms )
86         throws RepositorySearchException
87     {
88         List<String> indexingContextIds = addIndexingContexts( selectedRepos );
89
90         // since upgrade to nexus 2.0.0, query has changed from g:[QUERIED TERM]* to g:*[QUERIED TERM]*
91         //      resulting to more wildcard searches so we need to increase max clause count
92         BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );
93         BooleanQuery q = new BooleanQuery();
94
95         if ( previousSearchTerms == null || previousSearchTerms.isEmpty() )
96         {
97             constructQuery( term, q );
98         }
99         else
100         {
101             for ( String previousTerm : previousSearchTerms )
102             {
103                 BooleanQuery iQuery = new BooleanQuery();
104                 constructQuery( previousTerm, iQuery );
105
106                 q.add( iQuery, Occur.MUST );
107             }
108
109             BooleanQuery iQuery = new BooleanQuery();
110             constructQuery( term, iQuery );
111             q.add( iQuery, Occur.MUST );
112         }
113
114         // we retun only artifacts without classifier in quick search, olamy cannot find a way to say with this field empty
115         // FIXME  cannot find a way currently to setup this in constructQuery !!!
116         return search( limits, q, indexingContextIds, NoClassifierArtifactInfoFiler.LIST );
117
118     }
119
120     /**
121      * @see RepositorySearch#search(String, SearchFields, SearchResultLimits)
122      */
123     public SearchResults search( String principal, SearchFields searchFields, SearchResultLimits limits )
124         throws RepositorySearchException
125     {
126         if ( searchFields.getRepositories() == null )
127         {
128             throw new RepositorySearchException( "Repositories cannot be null." );
129         }
130
131         List<String> indexingContextIds = addIndexingContexts( searchFields.getRepositories() );
132
133         BooleanQuery q = new BooleanQuery();
134         if ( StringUtils.isNotBlank( searchFields.getGroupId() ) )
135         {
136             q.add( indexer.constructQuery( MAVEN.GROUP_ID, new StringSearchExpression( searchFields.getGroupId() ) ),
137                    Occur.MUST );
138         }
139
140         if ( StringUtils.isNotBlank( searchFields.getArtifactId() ) )
141         {
142             q.add(
143                 indexer.constructQuery( MAVEN.ARTIFACT_ID, new StringSearchExpression( searchFields.getArtifactId() ) ),
144                 Occur.MUST );
145         }
146
147         if ( StringUtils.isNotBlank( searchFields.getVersion() ) )
148         {
149             q.add( indexer.constructQuery( MAVEN.VERSION, new StringSearchExpression( searchFields.getVersion() ) ),
150                    Occur.MUST );
151         }
152
153         if ( StringUtils.isNotBlank( searchFields.getPackaging() ) )
154         {
155             q.add( indexer.constructQuery( MAVEN.PACKAGING, new StringSearchExpression( searchFields.getPackaging() ) ),
156                    Occur.MUST );
157         }
158
159         if ( StringUtils.isNotBlank( searchFields.getClassName() ) )
160         {
161             q.add(
162                 indexer.constructQuery( MAVEN.CLASSNAMES, new StringSearchExpression( searchFields.getClassName() ) ),
163                 Occur.MUST );
164         }
165
166         if ( StringUtils.isNotBlank( searchFields.getBundleSymbolicName() ) )
167         {
168             q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
169                                            new StringSearchExpression( searchFields.getBundleSymbolicName() ) ),
170                    Occur.MUST );
171         }
172
173         if ( StringUtils.isNotBlank( searchFields.getBundleVersion() ) )
174         {
175             q.add(
176                 indexer.constructQuery( OSGI.VERSION, new StringSearchExpression( searchFields.getBundleVersion() ) ),
177                 Occur.MUST );
178         }
179
180         if ( StringUtils.isNotBlank( searchFields.getBundleExportPackage() ) )
181         {
182             q.add( indexer.constructQuery( OSGI.EXPORT_PACKAGE,
183                                            new StringSearchExpression( searchFields.getBundleExportPackage() ) ),
184                    Occur.MUST );
185         }
186
187         if ( StringUtils.isNotBlank( searchFields.getBundleExportService() ) )
188         {
189             q.add( indexer.constructQuery( OSGI.SYMBOLIC_NAME,
190                                            new StringSearchExpression( searchFields.getBundleExportService() ) ),
191                    Occur.MUST );
192         }
193
194         if ( StringUtils.isNotBlank( searchFields.getClassifier() ) )
195         {
196             q.add(
197                 indexer.constructQuery( MAVEN.CLASSIFIER, new StringSearchExpression( searchFields.getClassifier() ) ),
198                 Occur.MUST );
199         }
200
201         if ( q.getClauses() == null || q.getClauses().length <= 0 )
202         {
203             throw new RepositorySearchException( "No search fields set." );
204         }
205
206         return search( limits, q, indexingContextIds, Collections.<ArtifactInfoFiler>emptyList() );
207     }
208
209     private SearchResults search( SearchResultLimits limits, BooleanQuery q, List<String> indexingContextIds,
210                                   List<? extends ArtifactInfoFiler> filters )
211         throws RepositorySearchException
212     {
213
214         try
215         {
216             FlatSearchRequest request = new FlatSearchRequest( q );
217             request.setContexts( getIndexingContexts( indexingContextIds ) );
218             FlatSearchResponse response = indexer.searchFlat( request );
219
220             if ( response == null || response.getTotalHits() == 0 )
221             {
222                 SearchResults results = new SearchResults();
223                 results.setLimits( limits );
224                 return results;
225             }
226
227             return convertToSearchResults( response, limits, filters );
228         }
229         catch ( IOException e )
230         {
231             throw new RepositorySearchException( e );
232         }
233         /*
234         olamy : don't understand why this ?? it remove content from index ??
235         comment until someone explain WTF ?? :-))
236         finally
237         {
238             Map<String, IndexingContext> indexingContexts = indexer.getIndexingContexts();
239
240             for ( Map.Entry<String, IndexingContext> entry : indexingContexts.entrySet() )
241             {
242                 try
243                 {
244                     indexer.removeIndexingContext( entry.getValue(), false );
245                     log.debug( "Indexing context '{}' removed from search.", entry.getKey() );
246                 }
247                 catch ( IOException e )
248                 {
249                     log.warn( "IOException occurred while removing indexing content '" + entry.getKey() + "'." );
250                     continue;
251                 }
252             }
253         }*/
254     }
255
256     private List<IndexingContext> getIndexingContexts( List<String> ids )
257     {
258         List<IndexingContext> contexts = new ArrayList<IndexingContext>( ids.size() );
259
260         for ( String id : ids )
261         {
262             IndexingContext context = indexer.getIndexingContexts().get( id );
263             if ( context != null )
264             {
265                 contexts.add( context );
266             }
267             else
268             {
269                 log.warn( "context with id {} not exists", id );
270             }
271         }
272
273         return contexts;
274     }
275
276     private void constructQuery( String term, BooleanQuery q )
277     {
278         q.add( indexer.constructQuery( MAVEN.GROUP_ID, new StringSearchExpression( term ) ), Occur.SHOULD );
279         q.add( indexer.constructQuery( MAVEN.ARTIFACT_ID, new StringSearchExpression( term ) ), Occur.SHOULD );
280         q.add( indexer.constructQuery( MAVEN.VERSION, new StringSearchExpression( term ) ), Occur.SHOULD );
281         q.add( indexer.constructQuery( MAVEN.PACKAGING, new StringSearchExpression( term ) ), Occur.SHOULD );
282         q.add( indexer.constructQuery( MAVEN.CLASSNAMES, new StringSearchExpression( term ) ), Occur.SHOULD );
283
284         //Query query =
285         //    new WildcardQuery( new Term( MAVEN.CLASSNAMES.getFieldName(), "*" ) );
286         //q.add( query, Occur.MUST_NOT );
287         // olamy IMHO we could set this option as at least one must match
288         //q.setMinimumNumberShouldMatch( 1 );
289     }
290
291
292     /**
293      * @param selectedRepos
294      * @return indexing contextId used
295      */
296     private List<String> addIndexingContexts( List<String> selectedRepos )
297     {
298         List<String> indexingContextIds = new ArrayList<String>();
299         for ( String repo : selectedRepos )
300         {
301             try
302             {
303                 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repo );
304
305                 if ( repoConfig != null )
306                 {
307                     String indexDir = repoConfig.getIndexDirectory();
308                     File indexDirectory = null;
309                     if ( indexDir != null && !"".equals( indexDir ) )
310                     {
311                         indexDirectory = new File( repoConfig.getIndexDirectory() );
312                     }
313                     else
314                     {
315                         indexDirectory = new File( repoConfig.getLocation(), ".indexer" );
316                     }
317
318                     IndexingContext context = indexer.getIndexingContexts().get( repoConfig.getId() );
319                     if ( context != null )
320                     {
321                         // alreday here so no need to record it again
322                         log.debug( "index with id {} already exists skip adding it", repoConfig.getId() );
323                         // set searchable flag
324                         context.setSearchable( repoConfig.isScanned() );
325                         indexingContextIds.add( context.getId() );
326                         continue;
327                     }
328
329                     context = indexer.addIndexingContext( repoConfig.getId(), repoConfig.getId(),
330                                                           new File( repoConfig.getLocation() ), indexDirectory, null,
331                                                           null, getAllIndexCreators() );
332                     context.setSearchable( repoConfig.isScanned() );
333                     if ( context.isSearchable() )
334                     {
335                         indexingContextIds.add( context.getId() );
336                     }
337                     else
338                     {
339                         log.warn( "indexingContext with id {} not searchable", repoConfig.getId() );
340                     }
341
342                 }
343                 else
344                 {
345                     log.warn( "Repository '" + repo + "' not found in configuration." );
346                 }
347             }
348             catch ( UnsupportedExistingLuceneIndexException e )
349             {
350                 log.warn( "Error accessing index of repository '" + repo + "' : " + e.getMessage() );
351                 continue;
352             }
353             catch ( IOException e )
354             {
355                 log.warn( "IO error occured while accessing index of repository '" + repo + "' : " + e.getMessage() );
356                 continue;
357             }
358             catch ( RepositoryAdminException e )
359             {
360                 log.warn( "RepositoryAdminException occured while accessing index of repository '" + repo + "' : "
361                               + e.getMessage() );
362                 continue;
363             }
364         }
365         return indexingContextIds;
366     }
367
368
369     protected List<? extends IndexCreator> getAllIndexCreators()
370     {
371         return mavenIndexerUtils.getAllIndexCreators();
372     }
373
374
375     private SearchResults convertToSearchResults( FlatSearchResponse response, SearchResultLimits limits,
376                                                   List<? extends ArtifactInfoFiler> artifactInfoFilers )
377     {
378         SearchResults results = new SearchResults();
379         Set<ArtifactInfo> artifactInfos = response.getResults();
380
381         for ( ArtifactInfo artifactInfo : artifactInfos )
382         {
383             String id = SearchUtil.getHitId( artifactInfo.groupId, artifactInfo.artifactId, artifactInfo.classifier,
384                                              artifactInfo.packaging );
385             Map<String, SearchResultHit> hitsMap = results.getHitsMap();
386
387             if ( !applyArtifactInfoFilters( artifactInfo, artifactInfoFilers, hitsMap ) )
388             {
389                 continue;
390             }
391
392             SearchResultHit hit = hitsMap.get( id );
393             if ( hit != null )
394             {
395                 if ( !hit.getVersions().contains( artifactInfo.version ) )
396                 {
397                     hit.addVersion( artifactInfo.version );
398                 }
399             }
400             else
401             {
402                 hit = new SearchResultHit();
403                 hit.setArtifactId( artifactInfo.artifactId );
404                 hit.setGroupId( artifactInfo.groupId );
405                 hit.setRepositoryId( artifactInfo.repository );
406                 // FIXME archiva url ??
407                 hit.setUrl( artifactInfo.repository + "/" + artifactInfo.fname );
408                 hit.addVersion( artifactInfo.version );
409                 hit.setBundleExportPackage( artifactInfo.bundleExportPackage );
410                 hit.setBundleExportService( artifactInfo.bundleExportService );
411                 hit.setBundleSymbolicName( artifactInfo.bundleSymbolicName );
412                 hit.setBundleVersion( artifactInfo.bundleVersion );
413                 hit.setBundleDescription( artifactInfo.bundleDescription );
414                 hit.setBundleDocUrl( artifactInfo.bundleDocUrl );
415
416                 hit.setBundleRequireBundle( artifactInfo.bundleRequireBundle );
417                 hit.setBundleImportPackage( artifactInfo.bundleImportPackage );
418                 hit.setBundleLicense( artifactInfo.bundleLicense );
419                 hit.setBundleName( artifactInfo.bundleName );
420                 hit.setContext( artifactInfo.context );
421                 hit.setGoals( artifactInfo.goals );
422                 hit.setPrefix( artifactInfo.prefix );
423                 hit.setPackaging( artifactInfo.packaging );
424                 hit.setClassifier( artifactInfo.classifier );
425                 // sure ??
426                 hit.setUrl( artifactInfo.remoteUrl );
427             }
428
429             results.addHit( id, hit );
430         }
431
432         results.setTotalHits( response.getTotalHitsCount() );
433         results.setReturnedHitsCount( response.getReturnedHitsCount() );
434         results.setLimits( limits );
435
436         if ( limits == null || limits.getSelectedPage() == SearchResultLimits.ALL_PAGES )
437         {
438             return results;
439         }
440         else
441         {
442             return paginate( results );
443         }
444     }
445
446     private boolean applyArtifactInfoFilters( ArtifactInfo artifactInfo,
447                                               List<? extends ArtifactInfoFiler> artifactInfoFilers,
448                                               Map<String, SearchResultHit> currentResult )
449     {
450         if ( artifactInfoFilers == null || artifactInfoFilers.isEmpty() )
451         {
452             return true;
453         }
454
455         for ( ArtifactInfoFiler filter : artifactInfoFilers )
456         {
457             if ( !filter.addArtifactInResult( artifactInfo, currentResult ) )
458             {
459                 return false;
460             }
461         }
462         return true;
463     }
464
465     private SearchResults paginate( SearchResults results )
466     {
467         SearchResultLimits limits = results.getLimits();
468         SearchResults paginated = new SearchResults();
469
470         int fetchCount = limits.getPageSize();
471         int offset = ( limits.getSelectedPage() * limits.getPageSize() );
472
473         if ( fetchCount > results.getTotalHits() )
474         {
475             fetchCount = results.getTotalHits();
476         }
477
478         // Goto offset.
479         if ( offset < results.getTotalHits() )
480         {
481             // only process if the offset is within the hit count.
482             for ( int i = 0; i < fetchCount; i++ )
483             {
484                 // Stop fetching if we are past the total # of available hits.
485                 if ( offset + i >= results.getHits().size() )
486                 {
487                     break;
488                 }
489
490                 SearchResultHit hit = results.getHits().get( ( offset + i ) );
491                 if ( hit != null )
492                 {
493                     String id = SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(),
494                                                      hit.getPackaging() );
495                     paginated.addHit( id, hit );
496                 }
497                 else
498                 {
499                     break;
500                 }
501             }
502         }
503         paginated.setTotalHits( results.getTotalHits() );
504         paginated.setReturnedHitsCount( paginated.getHits().size() );
505         paginated.setLimits( limits );
506
507         return paginated;
508     }
509 }