]> source.dussan.org Git - archiva.git/blob
60f0a7b75f7488814ecb8f01794c5e3909182634
[archiva.git] /
1 package org.apache.archiva.mock;
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.common.utils.FileUtils;
23 import org.apache.archiva.common.utils.PathUtil;
24 import org.apache.archiva.configuration.ArchivaConfiguration;
25 import org.apache.archiva.indexer.ArchivaIndexManager;
26 import org.apache.archiva.indexer.ArchivaIndexingContext;
27 import org.apache.archiva.indexer.IndexCreationFailedException;
28 import org.apache.archiva.indexer.IndexUpdateFailedException;
29 import org.apache.archiva.indexer.UnsupportedBaseContextException;
30 import org.apache.archiva.proxy.ProxyRegistry;
31 import org.apache.archiva.proxy.maven.WagonFactory;
32 import org.apache.archiva.proxy.maven.WagonFactoryException;
33 import org.apache.archiva.proxy.maven.WagonFactoryRequest;
34 import org.apache.archiva.proxy.model.NetworkProxy;
35 import org.apache.archiva.repository.EditableRepository;
36 import org.apache.archiva.repository.ManagedRepository;
37 import org.apache.archiva.repository.PasswordCredentials;
38 import org.apache.archiva.repository.RemoteRepository;
39 import org.apache.archiva.repository.Repository;
40 import org.apache.archiva.repository.RepositoryType;
41 import org.apache.archiva.repository.UnsupportedRepositoryTypeException;
42 import org.apache.archiva.repository.content.FilesystemAsset;
43 import org.apache.archiva.repository.content.StorageAsset;
44 import org.apache.archiva.repository.features.IndexCreationFeature;
45 import org.apache.archiva.repository.features.RemoteIndexFeature;
46 import org.apache.commons.lang.StringUtils;
47 import org.apache.maven.index.ArtifactContext;
48 import org.apache.maven.index.ArtifactContextProducer;
49 import org.apache.maven.index.DefaultScannerListener;
50 import org.apache.maven.index.Indexer;
51 import org.apache.maven.index.IndexerEngine;
52 import org.apache.maven.index.Scanner;
53 import org.apache.maven.index.ScanningRequest;
54 import org.apache.maven.index.ScanningResult;
55 import org.apache.maven.index.context.IndexCreator;
56 import org.apache.maven.index.context.IndexingContext;
57 import org.apache.maven.index.packer.IndexPacker;
58 import org.apache.maven.index.packer.IndexPackingRequest;
59 import org.apache.maven.index.updater.IndexUpdateRequest;
60 import org.apache.maven.index.updater.ResourceFetcher;
61 import org.apache.maven.index_shaded.lucene.index.IndexFormatTooOldException;
62 import org.apache.maven.wagon.ConnectionException;
63 import org.apache.maven.wagon.ResourceDoesNotExistException;
64 import org.apache.maven.wagon.StreamWagon;
65 import org.apache.maven.wagon.TransferFailedException;
66 import org.apache.maven.wagon.Wagon;
67 import org.apache.maven.wagon.authentication.AuthenticationException;
68 import org.apache.maven.wagon.authentication.AuthenticationInfo;
69 import org.apache.maven.wagon.authorization.AuthorizationException;
70 import org.apache.maven.wagon.events.TransferEvent;
71 import org.apache.maven.wagon.events.TransferListener;
72 import org.apache.maven.wagon.proxy.ProxyInfo;
73 import org.apache.maven.wagon.shared.http.AbstractHttpClientWagon;
74 import org.apache.maven.wagon.shared.http.HttpConfiguration;
75 import org.apache.maven.wagon.shared.http.HttpMethodConfiguration;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78 import org.springframework.stereotype.Service;
79
80 import javax.inject.Inject;
81 import java.io.FileNotFoundException;
82 import java.io.IOException;
83 import java.io.InputStream;
84 import java.net.MalformedURLException;
85 import java.net.URI;
86 import java.nio.file.Files;
87 import java.nio.file.Path;
88 import java.nio.file.Paths;
89 import java.util.Collection;
90 import java.util.List;
91 import java.util.Map;
92 import java.util.concurrent.ConcurrentSkipListSet;
93 import java.util.stream.Collectors;
94
95 @Service("archivaIndexManager#maven")
96 public class ArchivaIndexManagerMock implements ArchivaIndexManager {
97
98     private static final Logger log = LoggerFactory.getLogger( ArchivaIndexManagerMock.class );
99
100     @Inject
101     private Indexer indexer;
102
103     @Inject
104     private IndexerEngine indexerEngine;
105
106     @Inject
107     private List<? extends IndexCreator> indexCreators;
108
109     @Inject
110     private IndexPacker indexPacker;
111
112     @Inject
113     private Scanner scanner;
114
115     @Inject
116     private ArchivaConfiguration archivaConfiguration;
117
118     @Inject
119     private WagonFactory wagonFactory;
120
121
122     @Inject
123     private ArtifactContextProducer artifactContextProducer;
124
125     private ConcurrentSkipListSet<Path> activeContexts = new ConcurrentSkipListSet<>( );
126
127     private static final int WAIT_TIME = 100;
128     private static final int MAX_WAIT = 10;
129
130
131     public static IndexingContext getMvnContext(ArchivaIndexingContext context ) throws UnsupportedBaseContextException
132     {
133         if ( !context.supports( IndexingContext.class ) )
134         {
135             log.error( "The provided archiva index context does not support the maven IndexingContext" );
136             throw new UnsupportedBaseContextException( "The context does not support the Maven IndexingContext" );
137         }
138         return context.getBaseContext( IndexingContext.class );
139     }
140
141     private Path getIndexPath( ArchivaIndexingContext ctx )
142     {
143         return PathUtil.getPathFromUri( ctx.getPath( ) );
144     }
145
146     @FunctionalInterface
147     interface IndexUpdateConsumer
148     {
149
150         void accept( IndexingContext indexingContext ) throws IndexUpdateFailedException;
151     }
152
153     /*
154      * This method is used to do some actions around the update execution code. And to make sure, that no other
155      * method is running on the same index.
156      */
157     private void executeUpdateFunction( ArchivaIndexingContext context, IndexUpdateConsumer function ) throws IndexUpdateFailedException
158     {
159         IndexingContext indexingContext = null;
160         try
161         {
162             indexingContext = getMvnContext( context );
163         }
164         catch ( UnsupportedBaseContextException e )
165         {
166             throw new IndexUpdateFailedException( "Maven index is not supported by this context", e );
167         }
168         final Path ctxPath = getIndexPath( context );
169         int loop = MAX_WAIT;
170         boolean active = false;
171         while ( loop-- > 0 && !active )
172         {
173             active = activeContexts.add( ctxPath );
174             try
175             {
176                 Thread.currentThread( ).sleep( WAIT_TIME );
177             }
178             catch ( InterruptedException e )
179             {
180                 // Ignore this
181             }
182         }
183         if ( active )
184         {
185             try
186             {
187                 function.accept( indexingContext );
188             }
189             finally
190             {
191                 activeContexts.remove( ctxPath );
192             }
193         }
194         else
195         {
196             throw new IndexUpdateFailedException( "Timeout while waiting for index release on context " + context.getId( ) );
197         }
198     }
199
200     @Override
201     public void pack( final ArchivaIndexingContext context ) throws IndexUpdateFailedException
202     {
203         executeUpdateFunction( context, indexingContext -> {
204                     try
205                     {
206                         IndexPackingRequest request = new IndexPackingRequest( indexingContext,
207                                 indexingContext.acquireIndexSearcher( ).getIndexReader( ),
208                                 indexingContext.getIndexDirectoryFile( ) );
209                         indexPacker.packIndex( request );
210                         indexingContext.updateTimestamp( true );
211                     }
212                     catch ( IOException e )
213                     {
214                         log.error( "IOException while packing index of context " + context.getId( ) + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ) );
215                         throw new IndexUpdateFailedException( "IOException during update of " + context.getId( ), e );
216                     }
217                 }
218         );
219
220     }
221
222     @Override
223     public void scan(final ArchivaIndexingContext context) throws IndexUpdateFailedException
224     {
225         executeUpdateFunction( context, indexingContext -> {
226             DefaultScannerListener listener = new DefaultScannerListener( indexingContext, indexerEngine, true, null );
227             ScanningRequest request = new ScanningRequest( indexingContext, listener );
228             ScanningResult result = scanner.scan( request );
229             if ( result.hasExceptions( ) )
230             {
231                 log.error( "Exceptions occured during index scan of " + context.getId( ) );
232                 result.getExceptions( ).stream( ).map( e -> e.getMessage( ) ).distinct( ).limit( 5 ).forEach(
233                         s -> log.error( "Message: " + s )
234                 );
235             }
236
237         } );
238     }
239
240     @Override
241     public void update(final ArchivaIndexingContext context, final boolean fullUpdate) throws IndexUpdateFailedException
242     {
243         log.info( "start download remote index for remote repository {}", context.getRepository( ).getId( ) );
244         URI remoteUpdateUri;
245         if ( !( context.getRepository( ) instanceof RemoteRepository) || !(context.getRepository().supportsFeature(RemoteIndexFeature.class)) )
246         {
247             throw new IndexUpdateFailedException( "The context is not associated to a remote repository with remote index " + context.getId( ) );
248         } else {
249             RemoteIndexFeature rif = context.getRepository().getFeature(RemoteIndexFeature.class).get();
250             remoteUpdateUri = context.getRepository().getLocation().resolve(rif.getIndexUri());
251         }
252         final RemoteRepository remoteRepository = (RemoteRepository) context.getRepository( );
253
254         executeUpdateFunction( context,
255                 indexingContext -> {
256                     try
257                     {
258                         // create a temp directory to download files
259                         Path tempIndexDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".tmpIndex" );
260                         Path indexCacheDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".indexCache" );
261                         Files.createDirectories( indexCacheDirectory );
262                         if ( Files.exists( tempIndexDirectory ) )
263                         {
264                             FileUtils.deleteDirectory( tempIndexDirectory );
265                         }
266                         Files.createDirectories( tempIndexDirectory );
267                         tempIndexDirectory.toFile( ).deleteOnExit( );
268                         String baseIndexUrl = indexingContext.getIndexUpdateUrl( );
269
270                         String wagonProtocol = remoteUpdateUri.toURL( ).getProtocol( );
271
272                         NetworkProxy networkProxy = null;
273                         if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
274                         {
275                             RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
276
277                             final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
278                                     new WagonFactoryRequest( wagonProtocol, remoteRepository.getExtraHeaders( ) ).networkProxy(
279                                             networkProxy )
280                             );
281                             int readTimeout = (int) rif.getDownloadTimeout( ).toMillis( ) * 1000;
282                             wagon.setReadTimeout( readTimeout );
283                             wagon.setTimeout( (int) remoteRepository.getTimeout( ).toMillis( ) * 1000 );
284
285                             if ( wagon instanceof AbstractHttpClientWagon)
286                             {
287                                 HttpConfiguration httpConfiguration = new HttpConfiguration( );
288                                 HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration( );
289                                 httpMethodConfiguration.setUsePreemptive( true );
290                                 httpMethodConfiguration.setReadTimeout( readTimeout );
291                                 httpConfiguration.setGet( httpMethodConfiguration );
292                                 AbstractHttpClientWagon.class.cast( wagon ).setHttpConfiguration( httpConfiguration );
293                             }
294
295                             wagon.addTransferListener( new DownloadListener( ) );
296                             ProxyInfo proxyInfo = null;
297                             if ( networkProxy != null )
298                             {
299                                 proxyInfo = new ProxyInfo( );
300                                 proxyInfo.setType( networkProxy.getProtocol( ) );
301                                 proxyInfo.setHost( networkProxy.getHost( ) );
302                                 proxyInfo.setPort( networkProxy.getPort( ) );
303                                 proxyInfo.setUserName( networkProxy.getUsername( ) );
304                                 proxyInfo.setPassword( networkProxy.getPassword( ) );
305                             }
306                             AuthenticationInfo authenticationInfo = null;
307                             if ( remoteRepository.getLoginCredentials( ) != null && ( remoteRepository.getLoginCredentials( ) instanceof PasswordCredentials) )
308                             {
309                                 PasswordCredentials creds = (PasswordCredentials) remoteRepository.getLoginCredentials( );
310                                 authenticationInfo = new AuthenticationInfo( );
311                                 authenticationInfo.setUserName( creds.getUsername( ) );
312                                 authenticationInfo.setPassword( new String( creds.getPassword( ) ) );
313                             }
314                             wagon.connect( new org.apache.maven.wagon.repository.Repository( remoteRepository.getId( ), baseIndexUrl ), authenticationInfo,
315                                     proxyInfo );
316
317                             Path indexDirectory = indexingContext.getIndexDirectoryFile( ).toPath( );
318                             if ( !Files.exists( indexDirectory ) )
319                             {
320                                 Files.createDirectories( indexDirectory );
321                             }
322
323                             ResourceFetcher resourceFetcher =
324                                     new WagonResourceFetcher( log, tempIndexDirectory, wagon, remoteRepository );
325                             IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
326                             request.setForceFullUpdate( fullUpdate );
327                             request.setLocalIndexCacheDir( indexCacheDirectory.toFile( ) );
328
329                             // indexUpdater.fetchAndUpdateIndex( request );
330
331                             indexingContext.updateTimestamp( true );
332                         }
333
334                     }
335                     catch ( AuthenticationException e )
336                     {
337                         log.error( "Could not login to the remote proxy for updating index of {}", remoteRepository.getId( ), e );
338                         throw new IndexUpdateFailedException( "Login in to proxy failed while updating remote repository " + remoteRepository.getId( ), e );
339                     }
340                     catch ( ConnectionException e )
341                     {
342                         log.error( "Connection error during index update for remote repository {}", remoteRepository.getId( ), e );
343                         throw new IndexUpdateFailedException( "Connection error during index update for remote repository " + remoteRepository.getId( ), e );
344                     }
345                     catch ( MalformedURLException e )
346                     {
347                         log.error( "URL for remote index update of remote repository {} is not correct {}", remoteRepository.getId( ), remoteUpdateUri, e );
348                         throw new IndexUpdateFailedException( "URL for remote index update of repository is not correct " + remoteUpdateUri, e );
349                     }
350                     catch ( IOException e )
351                     {
352                         log.error( "IOException during index update of remote repository {}: {}", remoteRepository.getId( ), e.getMessage( ), e );
353                         throw new IndexUpdateFailedException( "IOException during index update of remote repository " + remoteRepository.getId( )
354                                 + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
355                     }
356                     catch ( WagonFactoryException e )
357                     {
358                         log.error( "Wagon for remote index download of {} could not be created: {}", remoteRepository.getId( ), e.getMessage( ), e );
359                         throw new IndexUpdateFailedException( "Error while updating the remote index of " + remoteRepository.getId( ), e );
360                     }
361                 } );
362
363     }
364
365     @Override
366     public void addArtifactsToIndex( final ArchivaIndexingContext context, final Collection<URI> artifactReference ) throws IndexUpdateFailedException
367     {
368         final URI ctxUri = context.getPath();
369         executeUpdateFunction(context, indexingContext -> {
370             Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer.getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())).collect(Collectors.toList());
371             try {
372                 indexer.addArtifactsToIndex(artifacts, indexingContext);
373             } catch (IOException e) {
374                 log.error("IOException while adding artifact {}", e.getMessage(), e);
375                 throw new IndexUpdateFailedException("Error occured while adding artifact to index of "+context.getId()
376                         + (StringUtils.isNotEmpty(e.getMessage()) ? ": "+e.getMessage() : ""));
377             }
378         });
379     }
380
381     @Override
382     public void removeArtifactsFromIndex( ArchivaIndexingContext context, Collection<URI> artifactReference ) throws IndexUpdateFailedException
383     {
384         final URI ctxUri = context.getPath();
385         executeUpdateFunction(context, indexingContext -> {
386             Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer.getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())).collect(Collectors.toList());
387             try {
388                 indexer.deleteArtifactsFromIndex(artifacts, indexingContext);
389             } catch (IOException e) {
390                 log.error("IOException while removing artifact {}", e.getMessage(), e);
391                 throw new IndexUpdateFailedException("Error occured while removing artifact from index of "+context.getId()
392                         + (StringUtils.isNotEmpty(e.getMessage()) ? ": "+e.getMessage() : ""));
393             }
394         });
395
396     }
397
398     @Override
399     public boolean supportsRepository( RepositoryType type )
400     {
401         return type == RepositoryType.MAVEN;
402     }
403
404     @Override
405     public ArchivaIndexingContext createContext( Repository repository ) throws IndexCreationFailedException
406     {
407         log.debug("Creating context for repo {}, type: {}", repository.getId(), repository.getType());
408         if ( repository.getType( ) != RepositoryType.MAVEN )
409         {
410             throw new UnsupportedRepositoryTypeException( repository.getType( ) );
411         }
412         IndexingContext mvnCtx = null;
413         try
414         {
415             if ( repository instanceof RemoteRepository )
416             {
417                 mvnCtx = createRemoteContext( (RemoteRepository) repository );
418             }
419             else if ( repository instanceof ManagedRepository )
420             {
421                 mvnCtx = createManagedContext( (ManagedRepository) repository );
422             }
423         }
424         catch ( IOException e )
425         {
426             log.error( "IOException during context creation " + e.getMessage( ), e );
427             throw new IndexCreationFailedException( "Could not create index context for repository " + repository.getId( )
428                     + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
429         }
430         MavenIndexContextMock context = new MavenIndexContextMock( repository, mvnCtx );
431
432         return context;
433     }
434
435     @Override
436     public ArchivaIndexingContext reset(ArchivaIndexingContext context) throws IndexUpdateFailedException {
437         ArchivaIndexingContext ctx;
438         executeUpdateFunction(context, indexingContext -> {
439             try {
440                 indexingContext.close(true);
441             } catch (IOException e) {
442                 log.warn("Index close failed");
443             }
444             try {
445                 FileUtils.deleteDirectory(Paths.get(context.getPath()));
446             } catch (IOException e) {
447                 throw new IndexUpdateFailedException("Could not delete index files");
448             }
449         });
450         try {
451             Repository repo = context.getRepository();
452             ctx = createContext(context.getRepository());
453             if (repo instanceof EditableRepository) {
454                 ((EditableRepository)repo).setIndexingContext(ctx);
455             }
456         } catch (IndexCreationFailedException e) {
457             throw new IndexUpdateFailedException("Could not create index");
458         }
459         return ctx;
460     }
461
462     @Override
463     public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
464         if (context==null) {
465             return null;
466         }
467         if (context.supports(IndexingContext.class)) {
468             try {
469                 StorageAsset newPath = getIndexPath(repo);
470                 IndexingContext ctx = context.getBaseContext(IndexingContext.class);
471                 Path oldPath = ctx.getIndexDirectoryFile().toPath();
472                 if (oldPath.equals(newPath)) {
473                     // Nothing to do, if path does not change
474                     return context;
475                 }
476                 if (!Files.exists(oldPath)) {
477                     return createContext(repo);
478                 } else if (context.isEmpty()) {
479                     context.close();
480                     return createContext(repo);
481                 } else {
482                     context.close(false);
483                     Files.move(oldPath, newPath.getFilePath());
484                     return createContext(repo);
485                 }
486             } catch (IOException e) {
487                 log.error("IOException while moving index directory {}", e.getMessage(), e);
488                 throw new IndexCreationFailedException("Could not recreated the index.", e);
489             } catch (UnsupportedBaseContextException e) {
490                 throw new IndexCreationFailedException("The given context, is not a maven context.");
491             }
492         } else {
493             throw new IndexCreationFailedException("Bad context type. This is not a maven context.");
494         }
495     }
496
497     @Override
498     public void updateLocalIndexPath(Repository repo) {
499         if (repo.supportsFeature(IndexCreationFeature.class)) {
500             IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
501             try {
502                 icf.setLocalIndexPath(getIndexPath(repo));
503             } catch (IOException e) {
504                 log.error("Could not set local index path for {}. New URI: {}", repo.getId(), icf.getIndexPath());
505             }
506         }
507     }
508
509     @Override
510     public ArchivaIndexingContext mergeContexts(Repository destinationRepo, List<ArchivaIndexingContext> contexts, boolean packIndex) throws UnsupportedOperationException, IndexCreationFailedException {
511         return null;
512     }
513
514     private StorageAsset getIndexPath( Repository repo) throws IOException {
515         IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
516         Path repoDir = repo.getAsset("").getFilePath();
517         URI indexDir = icf.getIndexPath();
518         String indexPath = indexDir.getPath();
519         Path indexDirectory = null;
520         if ( ! StringUtils.isEmpty(indexDir.toString( ) ) )
521         {
522
523             indexDirectory = PathUtil.getPathFromUri( indexDir );
524             // not absolute so create it in repository directory
525             if ( indexDirectory.isAbsolute( ) )
526             {
527                 indexPath = indexDirectory.getFileName().toString();
528             }
529             else
530             {
531                 indexDirectory = repoDir.resolve( indexDirectory );
532             }
533         }
534         else
535         {
536             indexDirectory = repoDir.resolve( ".index" );
537             indexPath = ".index";
538         }
539
540         if ( !Files.exists( indexDirectory ) )
541         {
542             Files.createDirectories( indexDirectory );
543         }
544         return new FilesystemAsset( indexPath, indexDirectory);
545     }
546
547     private IndexingContext createRemoteContext(RemoteRepository remoteRepository ) throws IOException
548     {
549         Path appServerBase = archivaConfiguration.getAppServerBaseDir( );
550
551         String contextKey = "remote-" + remoteRepository.getId( );
552
553
554         // create remote repository path
555         Path repoDir = remoteRepository.getAsset("").getFilePath();
556         if ( !Files.exists( repoDir ) )
557         {
558             Files.createDirectories( repoDir );
559         }
560
561         StorageAsset indexDirectory = null;
562
563         // is there configured indexDirectory ?
564         if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
565         {
566             RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
567             indexDirectory = getIndexPath(remoteRepository);
568             String remoteIndexUrl = calculateIndexRemoteUrl( remoteRepository.getLocation( ), rif );
569             try
570             {
571
572                 return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
573             }
574             catch ( IndexFormatTooOldException e )
575             {
576                 // existing index with an old lucene format so we need to delete it!!!
577                 // delete it first then recreate it.
578                 log.warn( "the index of repository {} is too old we have to delete and recreate it", //
579                         remoteRepository.getId( ) );
580                 FileUtils.deleteDirectory( indexDirectory.getFilePath() );
581                 return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
582
583             }
584         }
585         else
586         {
587             throw new IOException( "No remote index defined" );
588         }
589     }
590
591     private IndexingContext getIndexingContext( Repository repository, String contextKey, Path repoDir, StorageAsset indexDirectory, String indexUrl ) throws IOException
592     {
593         return indexer.createIndexingContext( contextKey, repository.getId( ), repoDir.toFile( ), indexDirectory.getFilePath().toFile( ),
594                 repository.getLocation( ) == null ? null : repository.getLocation( ).toString( ),
595                 indexUrl,
596                 true, false,
597                 indexCreators );
598     }
599
600     private IndexingContext createManagedContext( ManagedRepository repository ) throws IOException
601     {
602
603         IndexingContext context;
604         // take care first about repository location as can be relative
605         Path repositoryDirectory = repository.getAsset("").getFilePath();
606
607         if ( !Files.exists( repositoryDirectory ) )
608         {
609             try
610             {
611                 Files.createDirectories( repositoryDirectory );
612             }
613             catch ( IOException e )
614             {
615                 log.error( "Could not create directory {}", repositoryDirectory );
616             }
617         }
618
619         StorageAsset indexDirectory = null;
620
621         if ( repository.supportsFeature( IndexCreationFeature.class ) )
622         {
623             indexDirectory = getIndexPath(repository);
624
625             String indexUrl = repositoryDirectory.toUri( ).toURL( ).toExternalForm( );
626             try
627             {
628                 context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
629                 context.setSearchable( repository.isScanned( ) );
630             }
631             catch ( IndexFormatTooOldException e )
632             {
633                 // existing index with an old lucene format so we need to delete it!!!
634                 // delete it first then recreate it.
635                 log.warn( "the index of repository {} is too old we have to delete and recreate it", //
636                         repository.getId( ) );
637                 FileUtils.deleteDirectory( indexDirectory.getFilePath() );
638                 context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
639                 context.setSearchable( repository.isScanned( ) );
640             }
641             return context;
642         }
643         else
644         {
645             throw new IOException( "No repository index defined" );
646         }
647     }
648
649     private String calculateIndexRemoteUrl( URI baseUri, RemoteIndexFeature rif )
650     {
651         if ( rif.getIndexUri( ) == null )
652         {
653             return baseUri.resolve( ".index" ).toString( );
654         }
655         else
656         {
657             return baseUri.resolve( rif.getIndexUri( ) ).toString( );
658         }
659     }
660
661     private static final class DownloadListener
662             implements TransferListener
663     {
664         private Logger log = LoggerFactory.getLogger( getClass( ) );
665
666         private String resourceName;
667
668         private long startTime;
669
670         private int totalLength = 0;
671
672         @Override
673         public void transferInitiated( TransferEvent transferEvent )
674         {
675             startTime = System.currentTimeMillis( );
676             resourceName = transferEvent.getResource( ).getName( );
677             log.debug( "initiate transfer of {}", resourceName );
678         }
679
680         @Override
681         public void transferStarted( TransferEvent transferEvent )
682         {
683             this.totalLength = 0;
684             resourceName = transferEvent.getResource( ).getName( );
685             log.info( "start transfer of {}", transferEvent.getResource( ).getName( ) );
686         }
687
688         @Override
689         public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
690         {
691             log.debug( "transfer of {} : {}/{}", transferEvent.getResource( ).getName( ), buffer.length, length );
692             this.totalLength += length;
693         }
694
695         @Override
696         public void transferCompleted( TransferEvent transferEvent )
697         {
698             resourceName = transferEvent.getResource( ).getName( );
699             long endTime = System.currentTimeMillis( );
700             log.info( "end of transfer file {} {} kb: {}s", transferEvent.getResource( ).getName( ),
701                     this.totalLength / 1024, ( endTime - startTime ) / 1000 );
702         }
703
704         @Override
705         public void transferError( TransferEvent transferEvent )
706         {
707             log.info( "error of transfer file {}: {}", transferEvent.getResource( ).getName( ),
708                     transferEvent.getException( ).getMessage( ), transferEvent.getException( ) );
709         }
710
711         @Override
712         public void debug( String message )
713         {
714             log.debug( "transfer debug {}", message );
715         }
716     }
717
718     private static class WagonResourceFetcher
719             implements ResourceFetcher
720     {
721
722         Logger log;
723
724         Path tempIndexDirectory;
725
726         Wagon wagon;
727
728         RemoteRepository remoteRepository;
729
730         private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
731                                       RemoteRepository remoteRepository )
732         {
733             this.log = log;
734             this.tempIndexDirectory = tempIndexDirectory;
735             this.wagon = wagon;
736             this.remoteRepository = remoteRepository;
737         }
738
739         @Override
740         public void connect( String id, String url )
741                 throws IOException
742         {
743             //no op
744         }
745
746         @Override
747         public void disconnect( )
748                 throws IOException
749         {
750             // no op
751         }
752
753         @Override
754         public InputStream retrieve(String name )
755                 throws IOException, FileNotFoundException
756         {
757             try
758             {
759                 log.info( "index update retrieve file, name:{}", name );
760                 Path file = tempIndexDirectory.resolve( name );
761                 Files.deleteIfExists( file );
762                 file.toFile( ).deleteOnExit( );
763                 wagon.get( addParameters( name, remoteRepository ), file.toFile( ) );
764                 return Files.newInputStream( file );
765             }
766             catch ( AuthorizationException | TransferFailedException e )
767             {
768                 throw new IOException( e.getMessage( ), e );
769             }
770             catch ( ResourceDoesNotExistException e )
771             {
772                 FileNotFoundException fnfe = new FileNotFoundException( e.getMessage( ) );
773                 fnfe.initCause( e );
774                 throw fnfe;
775             }
776         }
777
778         // FIXME remove crappy copy/paste
779         protected String addParameters( String path, RemoteRepository remoteRepository )
780         {
781             if ( remoteRepository.getExtraParameters( ).isEmpty( ) )
782             {
783                 return path;
784             }
785
786             boolean question = false;
787
788             StringBuilder res = new StringBuilder( path == null ? "" : path );
789
790             for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters( ).entrySet( ) )
791             {
792                 if ( !question )
793                 {
794                     res.append( '?' ).append( entry.getKey( ) ).append( '=' ).append( entry.getValue( ) );
795                 }
796             }
797
798             return res.toString( );
799         }
800
801     }
802 }