1 package org.apache.archiva.admin.mock;
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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
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;
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;
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;
93 import java.util.concurrent.ConcurrentSkipListSet;
94 import java.util.stream.Collectors;
96 @Service("archivaIndexManager#maven")
97 public class ArchivaIndexManagerMock implements ArchivaIndexManager {
99 private static final Logger log = LoggerFactory.getLogger( ArchivaIndexManagerMock.class );
102 private Indexer indexer;
105 private IndexerEngine indexerEngine;
108 private List<? extends IndexCreator> indexCreators;
111 private IndexPacker indexPacker;
114 private Scanner scanner;
117 private ArchivaConfiguration archivaConfiguration;
120 private WagonFactory wagonFactory;
123 ProxyRegistry proxyRegistry;
126 private ArtifactContextProducer artifactContextProducer;
128 private ConcurrentSkipListSet<Path> activeContexts = new ConcurrentSkipListSet<>( );
130 private static final int WAIT_TIME = 100;
131 private static final int MAX_WAIT = 10;
134 public static IndexingContext getMvnContext(ArchivaIndexingContext context ) throws UnsupportedBaseContextException
136 if ( !context.supports( IndexingContext.class ) )
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" );
141 return context.getBaseContext( IndexingContext.class );
144 private Path getIndexPath( ArchivaIndexingContext ctx )
146 return PathUtil.getPathFromUri( ctx.getPath( ) );
150 interface IndexUpdateConsumer
153 void accept( IndexingContext indexingContext ) throws IndexUpdateFailedException;
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.
160 private void executeUpdateFunction( ArchivaIndexingContext context, IndexUpdateConsumer function ) throws IndexUpdateFailedException
162 IndexingContext indexingContext = null;
165 indexingContext = getMvnContext( context );
167 catch ( UnsupportedBaseContextException e )
169 throw new IndexUpdateFailedException( "Maven index is not supported by this context", e );
171 final Path ctxPath = getIndexPath( context );
173 boolean active = false;
174 while ( loop-- > 0 && !active )
176 active = activeContexts.add( ctxPath );
179 Thread.currentThread( ).sleep( WAIT_TIME );
181 catch ( InterruptedException e )
190 function.accept( indexingContext );
194 activeContexts.remove( ctxPath );
199 throw new IndexUpdateFailedException( "Timeout while waiting for index release on context " + context.getId( ) );
204 public void pack( final ArchivaIndexingContext context ) throws IndexUpdateFailedException
206 executeUpdateFunction( context, indexingContext -> {
209 IndexPackingRequest request = new IndexPackingRequest( indexingContext,
210 indexingContext.acquireIndexSearcher( ).getIndexReader( ),
211 indexingContext.getIndexDirectoryFile( ) );
212 indexPacker.packIndex( request );
213 indexingContext.updateTimestamp( true );
215 catch ( IOException e )
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 );
226 public void scan(final ArchivaIndexingContext context) throws IndexUpdateFailedException
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( ) )
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 )
244 public void update(final ArchivaIndexingContext context, final boolean fullUpdate) throws IndexUpdateFailedException
246 log.info( "start download remote index for remote repository {}", context.getRepository( ).getId( ) );
248 if ( !( context.getRepository( ) instanceof RemoteRepository) || !(context.getRepository().supportsFeature(RemoteIndexFeature.class)) )
250 throw new IndexUpdateFailedException( "The context is not associated to a remote repository with remote index " + context.getId( ) );
252 RemoteIndexFeature rif = context.getRepository().getFeature(RemoteIndexFeature.class).get();
253 remoteUpdateUri = context.getRepository().getLocation().resolve(rif.getIndexUri());
255 final RemoteRepository remoteRepository = (RemoteRepository) context.getRepository( );
257 executeUpdateFunction( context,
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 ) )
267 org.apache.archiva.common.utils.FileUtils.deleteDirectory( tempIndexDirectory );
269 Files.createDirectories( tempIndexDirectory );
270 tempIndexDirectory.toFile( ).deleteOnExit( );
271 String baseIndexUrl = indexingContext.getIndexUpdateUrl( );
273 String wagonProtocol = remoteUpdateUri.toURL( ).getProtocol( );
275 NetworkProxy networkProxy = null;
276 if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
278 RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
279 if ( StringUtils.isNotBlank( rif.getProxyId( ) ) )
281 networkProxy = proxyRegistry.getNetworkProxy( rif.getProxyId( ) );
282 if ( networkProxy == null )
285 "your remote repository is configured to download remote index trought a proxy we cannot find id:{}",
290 final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
291 new WagonFactoryRequest( wagonProtocol, remoteRepository.getExtraHeaders( ) ).networkProxy(
294 int readTimeout = (int) rif.getDownloadTimeout( ).toMillis( ) * 1000;
295 wagon.setReadTimeout( readTimeout );
296 wagon.setTimeout( (int) remoteRepository.getTimeout( ).toMillis( ) * 1000 );
298 if ( wagon instanceof AbstractHttpClientWagon)
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 );
308 wagon.addTransferListener( new DownloadListener( ) );
309 ProxyInfo proxyInfo = null;
310 if ( networkProxy != null )
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( ) );
319 AuthenticationInfo authenticationInfo = null;
320 if ( remoteRepository.getLoginCredentials( ) != null && ( remoteRepository.getLoginCredentials( ) instanceof PasswordCredentials) )
322 PasswordCredentials creds = (PasswordCredentials) remoteRepository.getLoginCredentials( );
323 authenticationInfo = new AuthenticationInfo( );
324 authenticationInfo.setUserName( creds.getUsername( ) );
325 authenticationInfo.setPassword( new String( creds.getPassword( ) ) );
327 wagon.connect( new org.apache.maven.wagon.repository.Repository( remoteRepository.getId( ), baseIndexUrl ), authenticationInfo,
330 Path indexDirectory = indexingContext.getIndexDirectoryFile( ).toPath( );
331 if ( !Files.exists( indexDirectory ) )
333 Files.createDirectories( indexDirectory );
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( ) );
342 // indexUpdater.fetchAndUpdateIndex( request );
344 indexingContext.updateTimestamp( true );
348 catch ( AuthenticationException e )
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 );
353 catch ( ConnectionException e )
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 );
358 catch ( MalformedURLException e )
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 );
363 catch ( IOException e )
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 );
369 catch ( WagonFactoryException e )
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 );
379 public void addArtifactsToIndex( final ArchivaIndexingContext context, final Collection<URI> artifactReference ) throws IndexUpdateFailedException
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());
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() : ""));
395 public void removeArtifactsFromIndex( ArchivaIndexingContext context, Collection<URI> artifactReference ) throws IndexUpdateFailedException
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());
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() : ""));
412 public boolean supportsRepository( RepositoryType type )
414 return type == RepositoryType.MAVEN;
418 public ArchivaIndexingContext createContext( Repository repository ) throws IndexCreationFailedException
420 log.debug("Creating context for repo {}, type: {}", repository.getId(), repository.getType());
421 if ( repository.getType( ) != RepositoryType.MAVEN )
423 throw new UnsupportedRepositoryTypeException( repository.getType( ) );
425 IndexingContext mvnCtx = null;
428 if ( repository instanceof RemoteRepository )
430 mvnCtx = createRemoteContext( (RemoteRepository) repository );
432 else if ( repository instanceof ManagedRepository )
434 mvnCtx = createManagedContext( (ManagedRepository) repository );
437 catch ( IOException e )
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 );
443 MavenIndexContextMock context = new MavenIndexContextMock( repository, mvnCtx );
449 public ArchivaIndexingContext reset(ArchivaIndexingContext context) throws IndexUpdateFailedException {
450 ArchivaIndexingContext ctx;
451 executeUpdateFunction(context, indexingContext -> {
453 indexingContext.close(true);
454 } catch (IOException e) {
455 log.warn("Index close failed");
458 FileUtils.deleteDirectory(Paths.get(context.getPath()));
459 } catch (IOException e) {
460 throw new IndexUpdateFailedException("Could not delete index files");
464 Repository repo = context.getRepository();
465 ctx = createContext(context.getRepository());
466 if (repo instanceof EditableRepository) {
467 ((EditableRepository)repo).setIndexingContext(ctx);
469 } catch (IndexCreationFailedException e) {
470 throw new IndexUpdateFailedException("Could not create index");
476 public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
480 if (context.supports(IndexingContext.class)) {
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
489 if (!Files.exists(oldPath)) {
490 return createContext(repo);
491 } else if (context.isEmpty()) {
493 return createContext(repo);
495 context.close(false);
496 Files.move(oldPath, newPath.getFilePath());
497 return createContext(repo);
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.");
506 throw new IndexCreationFailedException("Bad context type. This is not a maven context.");
511 public void updateLocalIndexPath(Repository repo) {
512 if (repo.supportsFeature(IndexCreationFeature.class)) {
513 IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
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());
523 public ArchivaIndexingContext mergeContexts(Repository destinationRepo, List<ArchivaIndexingContext> contexts, boolean packIndex) throws UnsupportedOperationException, IndexCreationFailedException {
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( ) ) )
536 indexDirectory = PathUtil.getPathFromUri( indexDir );
537 // not absolute so create it in repository directory
538 if ( indexDirectory.isAbsolute( ) )
540 indexPath = indexDirectory.getFileName().toString();
544 indexDirectory = repoDir.resolve( indexDirectory );
549 indexDirectory = repoDir.resolve( ".index" );
550 indexPath = ".index";
553 if ( !Files.exists( indexDirectory ) )
555 Files.createDirectories( indexDirectory );
557 return new FilesystemAsset( indexPath, indexDirectory);
560 private IndexingContext createRemoteContext(RemoteRepository remoteRepository ) throws IOException
562 Path appServerBase = archivaConfiguration.getAppServerBaseDir( );
564 String contextKey = "remote-" + remoteRepository.getId( );
567 // create remote repository path
568 Path repoDir = remoteRepository.getAsset("").getFilePath();
569 if ( !Files.exists( repoDir ) )
571 Files.createDirectories( repoDir );
574 StorageAsset indexDirectory = null;
576 // is there configured indexDirectory ?
577 if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
579 RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
580 indexDirectory = getIndexPath(remoteRepository);
581 String remoteIndexUrl = calculateIndexRemoteUrl( remoteRepository.getLocation( ), rif );
585 return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
587 catch ( IndexFormatTooOldException e )
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 );
600 throw new IOException( "No remote index defined" );
604 private IndexingContext getIndexingContext( Repository repository, String contextKey, Path repoDir, StorageAsset indexDirectory, String indexUrl ) throws IOException
606 return indexer.createIndexingContext( contextKey, repository.getId( ), repoDir.toFile( ), indexDirectory.getFilePath().toFile( ),
607 repository.getLocation( ) == null ? null : repository.getLocation( ).toString( ),
613 private IndexingContext createManagedContext( ManagedRepository repository ) throws IOException
616 IndexingContext context;
617 // take care first about repository location as can be relative
618 Path repositoryDirectory = repository.getAsset("").getFilePath();
620 if ( !Files.exists( repositoryDirectory ) )
624 Files.createDirectories( repositoryDirectory );
626 catch ( IOException e )
628 log.error( "Could not create directory {}", repositoryDirectory );
632 StorageAsset indexDirectory = null;
634 if ( repository.supportsFeature( IndexCreationFeature.class ) )
636 indexDirectory = getIndexPath(repository);
638 String indexUrl = repositoryDirectory.toUri( ).toURL( ).toExternalForm( );
641 context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
642 context.setSearchable( repository.isScanned( ) );
644 catch ( IndexFormatTooOldException e )
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( ) );
658 throw new IOException( "No repository index defined" );
662 private String calculateIndexRemoteUrl( URI baseUri, RemoteIndexFeature rif )
664 if ( rif.getIndexUri( ) == null )
666 return baseUri.resolve( ".index" ).toString( );
670 return baseUri.resolve( rif.getIndexUri( ) ).toString( );
674 private static final class DownloadListener
675 implements TransferListener
677 private Logger log = LoggerFactory.getLogger( getClass( ) );
679 private String resourceName;
681 private long startTime;
683 private int totalLength = 0;
686 public void transferInitiated( TransferEvent transferEvent )
688 startTime = System.currentTimeMillis( );
689 resourceName = transferEvent.getResource( ).getName( );
690 log.debug( "initiate transfer of {}", resourceName );
694 public void transferStarted( TransferEvent transferEvent )
696 this.totalLength = 0;
697 resourceName = transferEvent.getResource( ).getName( );
698 log.info( "start transfer of {}", transferEvent.getResource( ).getName( ) );
702 public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
704 log.debug( "transfer of {} : {}/{}", transferEvent.getResource( ).getName( ), buffer.length, length );
705 this.totalLength += length;
709 public void transferCompleted( TransferEvent transferEvent )
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 );
718 public void transferError( TransferEvent transferEvent )
720 log.info( "error of transfer file {}: {}", transferEvent.getResource( ).getName( ),
721 transferEvent.getException( ).getMessage( ), transferEvent.getException( ) );
725 public void debug( String message )
727 log.debug( "transfer debug {}", message );
731 private static class WagonResourceFetcher
732 implements ResourceFetcher
737 Path tempIndexDirectory;
741 RemoteRepository remoteRepository;
743 private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
744 RemoteRepository remoteRepository )
747 this.tempIndexDirectory = tempIndexDirectory;
749 this.remoteRepository = remoteRepository;
753 public void connect( String id, String url )
760 public void disconnect( )
767 public InputStream retrieve(String name )
768 throws IOException, FileNotFoundException
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 );
779 catch ( AuthorizationException | TransferFailedException e )
781 throw new IOException( e.getMessage( ), e );
783 catch ( ResourceDoesNotExistException e )
785 FileNotFoundException fnfe = new FileNotFoundException( e.getMessage( ) );
791 // FIXME remove crappy copy/paste
792 protected String addParameters( String path, RemoteRepository remoteRepository )
794 if ( remoteRepository.getExtraParameters( ).isEmpty( ) )
799 boolean question = false;
801 StringBuilder res = new StringBuilder( path == null ? "" : path );
803 for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters( ).entrySet( ) )
807 res.append( '?' ).append( entry.getKey( ) ).append( '=' ).append( entry.getValue( ) );
811 return res.toString( );