1 package org.apache.archiva.repository.index.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;
97 * @author Martin Stockhammer <martin_s@apache.org>
99 @Service("archivaIndexManager#maven")
100 public class ArchivaIndexManagerMock implements ArchivaIndexManager {
101 private static final Logger log = LoggerFactory.getLogger( ArchivaIndexManagerMock.class );
104 private Indexer indexer;
107 private IndexerEngine indexerEngine;
110 private List<? extends IndexCreator> indexCreators;
113 private IndexPacker indexPacker;
116 private Scanner scanner;
119 private ArchivaConfiguration archivaConfiguration;
122 private WagonFactory wagonFactory;
125 private ArtifactContextProducer artifactContextProducer;
128 private ProxyRegistry proxyRegistry;
130 private ConcurrentSkipListSet<Path> activeContexts = new ConcurrentSkipListSet<>( );
132 private static final int WAIT_TIME = 100;
133 private static final int MAX_WAIT = 10;
136 public static IndexingContext getMvnContext(ArchivaIndexingContext context ) throws UnsupportedBaseContextException
138 if ( !context.supports( IndexingContext.class ) )
140 log.error( "The provided archiva index context does not support the maven IndexingContext" );
141 throw new UnsupportedBaseContextException( "The context does not support the Maven IndexingContext" );
143 return context.getBaseContext( IndexingContext.class );
146 private Path getIndexPath( ArchivaIndexingContext ctx )
148 return PathUtil.getPathFromUri( ctx.getPath( ) );
152 interface IndexUpdateConsumer
155 void accept( IndexingContext indexingContext ) throws IndexUpdateFailedException;
159 * This method is used to do some actions around the update execution code. And to make sure, that no other
160 * method is running on the same index.
162 private void executeUpdateFunction( ArchivaIndexingContext context, IndexUpdateConsumer function ) throws IndexUpdateFailedException
164 IndexingContext indexingContext = null;
167 indexingContext = getMvnContext( context );
169 catch ( UnsupportedBaseContextException e )
171 throw new IndexUpdateFailedException( "Maven index is not supported by this context", e );
173 final Path ctxPath = getIndexPath( context );
175 boolean active = false;
176 while ( loop-- > 0 && !active )
178 active = activeContexts.add( ctxPath );
181 Thread.currentThread( ).sleep( WAIT_TIME );
183 catch ( InterruptedException e )
192 function.accept( indexingContext );
196 activeContexts.remove( ctxPath );
201 throw new IndexUpdateFailedException( "Timeout while waiting for index release on context " + context.getId( ) );
206 public void pack( final ArchivaIndexingContext context ) throws IndexUpdateFailedException
208 executeUpdateFunction( context, indexingContext -> {
211 IndexPackingRequest request = new IndexPackingRequest( indexingContext,
212 indexingContext.acquireIndexSearcher( ).getIndexReader( ),
213 indexingContext.getIndexDirectoryFile( ) );
214 indexPacker.packIndex( request );
215 indexingContext.updateTimestamp( true );
217 catch ( IOException e )
219 log.error( "IOException while packing index of context " + context.getId( ) + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ) );
220 throw new IndexUpdateFailedException( "IOException during update of " + context.getId( ), e );
228 public void scan(final ArchivaIndexingContext context) throws IndexUpdateFailedException
230 executeUpdateFunction( context, indexingContext -> {
231 DefaultScannerListener listener = new DefaultScannerListener( indexingContext, indexerEngine, true, null );
232 ScanningRequest request = new ScanningRequest( indexingContext, listener );
233 ScanningResult result = scanner.scan( request );
234 if ( result.hasExceptions( ) )
236 log.error( "Exceptions occured during index scan of " + context.getId( ) );
237 result.getExceptions( ).stream( ).map( e -> e.getMessage( ) ).distinct( ).limit( 5 ).forEach(
238 s -> log.error( "Message: " + s )
246 public void update(final ArchivaIndexingContext context, final boolean fullUpdate) throws IndexUpdateFailedException
248 log.info( "start download remote index for remote repository {}", context.getRepository( ).getId( ) );
250 if ( !( context.getRepository( ) instanceof RemoteRepository) || !(context.getRepository().supportsFeature(RemoteIndexFeature.class)) )
252 throw new IndexUpdateFailedException( "The context is not associated to a remote repository with remote index " + context.getId( ) );
254 RemoteIndexFeature rif = context.getRepository().getFeature(RemoteIndexFeature.class).get();
255 remoteUpdateUri = context.getRepository().getLocation().resolve(rif.getIndexUri());
257 final RemoteRepository remoteRepository = (RemoteRepository) context.getRepository( );
259 executeUpdateFunction( context,
263 // create a temp directory to download files
264 Path tempIndexDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".tmpIndex" );
265 Path indexCacheDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".indexCache" );
266 Files.createDirectories( indexCacheDirectory );
267 if ( Files.exists( tempIndexDirectory ) )
269 org.apache.archiva.common.utils.FileUtils.deleteDirectory( tempIndexDirectory );
271 Files.createDirectories( tempIndexDirectory );
272 tempIndexDirectory.toFile( ).deleteOnExit( );
273 String baseIndexUrl = indexingContext.getIndexUpdateUrl( );
275 String wagonProtocol = remoteUpdateUri.toURL( ).getProtocol( );
277 NetworkProxy networkProxy = null;
278 if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
280 RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
281 if ( StringUtils.isNotBlank( rif.getProxyId( ) ) )
283 networkProxy = proxyRegistry.getNetworkProxy( rif.getProxyId( ) );
284 if ( networkProxy == null )
287 "your remote repository is configured to download remote index trought a proxy we cannot find id:{}",
292 final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
293 new WagonFactoryRequest( wagonProtocol, remoteRepository.getExtraHeaders( ) ).networkProxy(
296 int readTimeout = (int) rif.getDownloadTimeout( ).toMillis( ) * 1000;
297 wagon.setReadTimeout( readTimeout );
298 wagon.setTimeout( (int) remoteRepository.getTimeout( ).toMillis( ) * 1000 );
300 if ( wagon instanceof AbstractHttpClientWagon)
302 HttpConfiguration httpConfiguration = new HttpConfiguration( );
303 HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration( );
304 httpMethodConfiguration.setUsePreemptive( true );
305 httpMethodConfiguration.setReadTimeout( readTimeout );
306 httpConfiguration.setGet( httpMethodConfiguration );
307 AbstractHttpClientWagon.class.cast( wagon ).setHttpConfiguration( httpConfiguration );
310 wagon.addTransferListener( new DownloadListener( ) );
311 ProxyInfo proxyInfo = null;
312 if ( networkProxy != null )
314 proxyInfo = new ProxyInfo( );
315 proxyInfo.setType( networkProxy.getProtocol( ) );
316 proxyInfo.setHost( networkProxy.getHost( ) );
317 proxyInfo.setPort( networkProxy.getPort( ) );
318 proxyInfo.setUserName( networkProxy.getUsername( ) );
319 proxyInfo.setPassword( networkProxy.getPassword( ) );
321 AuthenticationInfo authenticationInfo = null;
322 if ( remoteRepository.getLoginCredentials( ) != null && ( remoteRepository.getLoginCredentials( ) instanceof PasswordCredentials) )
324 PasswordCredentials creds = (PasswordCredentials) remoteRepository.getLoginCredentials( );
325 authenticationInfo = new AuthenticationInfo( );
326 authenticationInfo.setUserName( creds.getUsername( ) );
327 authenticationInfo.setPassword( new String( creds.getPassword( ) ) );
329 wagon.connect( new org.apache.maven.wagon.repository.Repository( remoteRepository.getId( ), baseIndexUrl ), authenticationInfo,
332 Path indexDirectory = indexingContext.getIndexDirectoryFile( ).toPath( );
333 if ( !Files.exists( indexDirectory ) )
335 Files.createDirectories( indexDirectory );
338 ResourceFetcher resourceFetcher =
339 new WagonResourceFetcher( log, tempIndexDirectory, wagon, remoteRepository );
340 IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
341 request.setForceFullUpdate( fullUpdate );
342 request.setLocalIndexCacheDir( indexCacheDirectory.toFile( ) );
344 // indexUpdater.fetchAndUpdateIndex( request );
346 indexingContext.updateTimestamp( true );
350 catch ( AuthenticationException e )
352 log.error( "Could not login to the remote proxy for updating index of {}", remoteRepository.getId( ), e );
353 throw new IndexUpdateFailedException( "Login in to proxy failed while updating remote repository " + remoteRepository.getId( ), e );
355 catch ( ConnectionException e )
357 log.error( "Connection error during index update for remote repository {}", remoteRepository.getId( ), e );
358 throw new IndexUpdateFailedException( "Connection error during index update for remote repository " + remoteRepository.getId( ), e );
360 catch ( MalformedURLException e )
362 log.error( "URL for remote index update of remote repository {} is not correct {}", remoteRepository.getId( ), remoteUpdateUri, e );
363 throw new IndexUpdateFailedException( "URL for remote index update of repository is not correct " + remoteUpdateUri, e );
365 catch ( IOException e )
367 log.error( "IOException during index update of remote repository {}: {}", remoteRepository.getId( ), e.getMessage( ), e );
368 throw new IndexUpdateFailedException( "IOException during index update of remote repository " + remoteRepository.getId( )
369 + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
371 catch ( WagonFactoryException e )
373 log.error( "Wagon for remote index download of {} could not be created: {}", remoteRepository.getId( ), e.getMessage( ), e );
374 throw new IndexUpdateFailedException( "Error while updating the remote index of " + remoteRepository.getId( ), e );
381 public void addArtifactsToIndex( final ArchivaIndexingContext context, final Collection<URI> artifactReference ) throws IndexUpdateFailedException
383 final URI ctxUri = context.getPath();
384 executeUpdateFunction(context, indexingContext -> {
385 Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer.getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())).collect(Collectors.toList());
387 indexer.addArtifactsToIndex(artifacts, indexingContext);
388 } catch (IOException e) {
389 log.error("IOException while adding artifact {}", e.getMessage(), e);
390 throw new IndexUpdateFailedException("Error occured while adding artifact to index of "+context.getId()
391 + (StringUtils.isNotEmpty(e.getMessage()) ? ": "+e.getMessage() : ""));
397 public void removeArtifactsFromIndex( ArchivaIndexingContext context, Collection<URI> artifactReference ) throws IndexUpdateFailedException
399 final URI ctxUri = context.getPath();
400 executeUpdateFunction(context, indexingContext -> {
401 Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer.getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())).collect(Collectors.toList());
403 indexer.deleteArtifactsFromIndex(artifacts, indexingContext);
404 } catch (IOException e) {
405 log.error("IOException while removing artifact {}", e.getMessage(), e);
406 throw new IndexUpdateFailedException("Error occured while removing artifact from index of "+context.getId()
407 + (StringUtils.isNotEmpty(e.getMessage()) ? ": "+e.getMessage() : ""));
414 public boolean supportsRepository( RepositoryType type )
416 return type == RepositoryType.MAVEN;
420 public ArchivaIndexingContext createContext( Repository repository ) throws IndexCreationFailedException
422 log.debug("Creating context for repo {}, type: {}", repository.getId(), repository.getType());
423 if ( repository.getType( ) != RepositoryType.MAVEN )
425 throw new UnsupportedRepositoryTypeException( repository.getType( ) );
427 IndexingContext mvnCtx = null;
430 if ( repository instanceof RemoteRepository )
432 mvnCtx = createRemoteContext( (RemoteRepository) repository );
434 else if ( repository instanceof ManagedRepository )
436 mvnCtx = createManagedContext( (ManagedRepository) repository );
439 catch ( IOException e )
441 log.error( "IOException during context creation " + e.getMessage( ), e );
442 throw new IndexCreationFailedException( "Could not create index context for repository " + repository.getId( )
443 + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
445 MavenIndexContextMock context = new MavenIndexContextMock( repository, mvnCtx );
451 public ArchivaIndexingContext reset(ArchivaIndexingContext context) throws IndexUpdateFailedException {
452 ArchivaIndexingContext ctx;
453 executeUpdateFunction(context, indexingContext -> {
455 indexingContext.close(true);
456 } catch (IOException e) {
457 log.warn("Index close failed");
460 FileUtils.deleteDirectory(Paths.get(context.getPath()));
461 } catch (IOException e) {
462 throw new IndexUpdateFailedException("Could not delete index files");
466 Repository repo = context.getRepository();
467 ctx = createContext(context.getRepository());
468 if (repo instanceof EditableRepository) {
469 ((EditableRepository)repo).setIndexingContext(ctx);
471 } catch (IndexCreationFailedException e) {
472 throw new IndexUpdateFailedException("Could not create index");
478 public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
482 if (context.supports(IndexingContext.class)) {
484 StorageAsset newPath = getIndexPath(repo);
485 IndexingContext ctx = context.getBaseContext(IndexingContext.class);
486 Path oldPath = ctx.getIndexDirectoryFile().toPath();
487 if (oldPath.equals(newPath)) {
488 // Nothing to do, if path does not change
491 if (!Files.exists(oldPath)) {
492 return createContext(repo);
493 } else if (context.isEmpty()) {
495 return createContext(repo);
497 context.close(false);
498 Files.move(oldPath, newPath.getFilePath());
499 return createContext(repo);
501 } catch (IOException e) {
502 log.error("IOException while moving index directory {}", e.getMessage(), e);
503 throw new IndexCreationFailedException("Could not recreated the index.", e);
504 } catch (UnsupportedBaseContextException e) {
505 throw new IndexCreationFailedException("The given context, is not a maven context.");
508 throw new IndexCreationFailedException("Bad context type. This is not a maven context.");
513 public void updateLocalIndexPath(Repository repo) {
514 if (repo.supportsFeature(IndexCreationFeature.class)) {
515 IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
517 icf.setLocalIndexPath(getIndexPath(repo));
518 } catch (IOException e) {
519 log.error("Could not set local index path for {}. New URI: {}", repo.getId(), icf.getIndexPath());
525 public ArchivaIndexingContext mergeContexts(Repository destinationRepo, List<ArchivaIndexingContext> contexts, boolean packIndex) throws UnsupportedOperationException, IndexCreationFailedException {
530 private StorageAsset getIndexPath( Repository repo) throws IOException {
531 IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
532 Path repoDir = repo.getAsset( "" ).getFilePath();
533 URI indexDir = icf.getIndexPath();
534 String indexPath = indexDir.getPath();
535 Path indexDirectory = null;
536 if ( ! StringUtils.isEmpty(indexDir.toString( ) ) )
539 indexDirectory = PathUtil.getPathFromUri( indexDir );
540 // not absolute so create it in repository directory
541 if ( indexDirectory.isAbsolute( ) )
543 indexPath = indexDirectory.getFileName().toString();
547 indexDirectory = repoDir.resolve( indexDirectory );
552 indexDirectory = repoDir.resolve( ".index" );
553 indexPath = ".index";
556 if ( !Files.exists( indexDirectory ) )
558 Files.createDirectories( indexDirectory );
560 return new FilesystemAsset( indexPath, indexDirectory );
563 private IndexingContext createRemoteContext(RemoteRepository remoteRepository ) throws IOException
565 Path appServerBase = archivaConfiguration.getAppServerBaseDir( );
567 String contextKey = "remote-" + remoteRepository.getId( );
570 // create remote repository path
571 Path repoDir = remoteRepository.getAsset("").getFilePath();
572 if ( !Files.exists( repoDir ) )
574 Files.createDirectories( repoDir );
577 StorageAsset indexDirectory = null;
579 // is there configured indexDirectory ?
580 if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
582 RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
583 indexDirectory = getIndexPath(remoteRepository);
584 String remoteIndexUrl = calculateIndexRemoteUrl( remoteRepository.getLocation( ), rif );
588 return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
590 catch ( IndexFormatTooOldException e )
592 // existing index with an old lucene format so we need to delete it!!!
593 // delete it first then recreate it.
594 log.warn( "the index of repository {} is too old we have to delete and recreate it", //
595 remoteRepository.getId( ) );
596 org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory.getFilePath() );
597 return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
603 throw new IOException( "No remote index defined" );
607 private IndexingContext getIndexingContext( Repository repository, String contextKey, Path repoDir, StorageAsset indexDirectory, String indexUrl ) throws IOException
609 return indexer.createIndexingContext( contextKey, repository.getId( ), repoDir.toFile( ), indexDirectory.getFilePath().toFile( ),
610 repository.getLocation( ) == null ? null : repository.getLocation( ).toString( ),
616 private IndexingContext createManagedContext( ManagedRepository repository ) throws IOException
619 IndexingContext context;
620 // take care first about repository location as can be relative
621 Path repositoryDirectory = repository.getAsset("").getFilePath();
623 if ( !Files.exists( repositoryDirectory ) )
627 Files.createDirectories( repositoryDirectory );
629 catch ( IOException e )
631 log.error( "Could not create directory {}", repositoryDirectory );
635 StorageAsset indexDirectory = null;
637 if ( repository.supportsFeature( IndexCreationFeature.class ) )
639 indexDirectory = getIndexPath(repository);
641 String indexUrl = repositoryDirectory.toUri( ).toURL( ).toExternalForm( );
644 context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
645 context.setSearchable( repository.isScanned( ) );
647 catch ( IndexFormatTooOldException e )
649 // existing index with an old lucene format so we need to delete it!!!
650 // delete it first then recreate it.
651 log.warn( "the index of repository {} is too old we have to delete and recreate it", //
652 repository.getId( ) );
653 org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory.getFilePath() );
654 context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
655 context.setSearchable( repository.isScanned( ) );
661 throw new IOException( "No repository index defined" );
665 private String calculateIndexRemoteUrl( URI baseUri, RemoteIndexFeature rif )
667 if ( rif.getIndexUri( ) == null )
669 return baseUri.resolve( ".index" ).toString( );
673 return baseUri.resolve( rif.getIndexUri( ) ).toString( );
677 private static final class DownloadListener
678 implements TransferListener
680 private Logger log = LoggerFactory.getLogger( getClass( ) );
682 private String resourceName;
684 private long startTime;
686 private int totalLength = 0;
689 public void transferInitiated( TransferEvent transferEvent )
691 startTime = System.currentTimeMillis( );
692 resourceName = transferEvent.getResource( ).getName( );
693 log.debug( "initiate transfer of {}", resourceName );
697 public void transferStarted( TransferEvent transferEvent )
699 this.totalLength = 0;
700 resourceName = transferEvent.getResource( ).getName( );
701 log.info( "start transfer of {}", transferEvent.getResource( ).getName( ) );
705 public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
707 log.debug( "transfer of {} : {}/{}", transferEvent.getResource( ).getName( ), buffer.length, length );
708 this.totalLength += length;
712 public void transferCompleted( TransferEvent transferEvent )
714 resourceName = transferEvent.getResource( ).getName( );
715 long endTime = System.currentTimeMillis( );
716 log.info( "end of transfer file {} {} kb: {}s", transferEvent.getResource( ).getName( ),
717 this.totalLength / 1024, ( endTime - startTime ) / 1000 );
721 public void transferError( TransferEvent transferEvent )
723 log.info( "error of transfer file {}: {}", transferEvent.getResource( ).getName( ),
724 transferEvent.getException( ).getMessage( ), transferEvent.getException( ) );
728 public void debug( String message )
730 log.debug( "transfer debug {}", message );
734 private static class WagonResourceFetcher
735 implements ResourceFetcher
740 Path tempIndexDirectory;
744 RemoteRepository remoteRepository;
746 private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
747 RemoteRepository remoteRepository )
750 this.tempIndexDirectory = tempIndexDirectory;
752 this.remoteRepository = remoteRepository;
756 public void connect( String id, String url )
763 public void disconnect( )
770 public InputStream retrieve(String name )
771 throws IOException, FileNotFoundException
775 log.info( "index update retrieve file, name:{}", name );
776 Path file = tempIndexDirectory.resolve( name );
777 Files.deleteIfExists( file );
778 file.toFile( ).deleteOnExit( );
779 wagon.get( addParameters( name, remoteRepository ), file.toFile( ) );
780 return Files.newInputStream( file );
782 catch ( AuthorizationException | TransferFailedException e )
784 throw new IOException( e.getMessage( ), e );
786 catch ( ResourceDoesNotExistException e )
788 FileNotFoundException fnfe = new FileNotFoundException( e.getMessage( ) );
794 // FIXME remove crappy copy/paste
795 protected String addParameters( String path, RemoteRepository remoteRepository )
797 if ( remoteRepository.getExtraParameters( ).isEmpty( ) )
802 boolean question = false;
804 StringBuilder res = new StringBuilder( path == null ? "" : path );
806 for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters( ).entrySet( ) )
810 res.append( '?' ).append( entry.getKey( ) ).append( '=' ).append( entry.getValue( ) );
814 return res.toString( );