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