diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/AbstractWagon.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/AbstractWagon.java index 25e4a3683..10a5acaa3 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/AbstractWagon.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/AbstractWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.List; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authentication.AuthenticationInfo; @@ -36,18 +47,6 @@ import org.apache.maven.wagon.resource.Resource; import org.codehaus.plexus.util.IOUtil; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.util.List; - import static java.lang.Math.max; import static java.lang.Math.min; @@ -56,9 +55,7 @@ * * @author Michal Maczka */ -public abstract class AbstractWagon - implements Wagon -{ +public abstract class AbstractWagon implements Wagon { protected static final int DEFAULT_BUFFER_SIZE = 4 * 1024; protected static final int MAXIMUM_BUFFER_SIZE = 512 * 1024; @@ -88,7 +85,6 @@ public abstract class AbstractWagon protected boolean interactive = true; - private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; /** @@ -97,7 +93,7 @@ public abstract class AbstractWagon * @since 2.2 */ private int readTimeout = - Integer.parseInt( System.getProperty( "maven.wagon.rto", Integer.toString( Wagon.DEFAULT_READ_TIMEOUT ) ) ); + Integer.parseInt(System.getProperty("maven.wagon.rto", Integer.toString(Wagon.DEFAULT_READ_TIMEOUT))); private ProxyInfoProvider proxyInfoProvider; @@ -112,18 +108,15 @@ public abstract class AbstractWagon // Accessors // ---------------------------------------------------------------------- - public Repository getRepository() - { + public Repository getRepository() { return repository; } - public ProxyInfo getProxyInfo() - { - return proxyInfoProvider != null ? proxyInfoProvider.getProxyInfo( null ) : null; + public ProxyInfo getProxyInfo() { + return proxyInfoProvider != null ? proxyInfoProvider.getProxyInfo(null) : null; } - public AuthenticationInfo getAuthenticationInfo() - { + public AuthenticationInfo getAuthenticationInfo() { return authenticationInfo; } @@ -131,101 +124,76 @@ public AuthenticationInfo getAuthenticationInfo() // Connection // ---------------------------------------------------------------------- - public void openConnection() - throws ConnectionException, AuthenticationException - { - try - { + public void openConnection() throws ConnectionException, AuthenticationException { + try { openConnectionInternal(); - } - catch ( ConnectionException e ) - { + } catch (ConnectionException e) { fireSessionConnectionRefused(); throw e; - } - catch ( AuthenticationException e ) - { + } catch (AuthenticationException e) { fireSessionConnectionRefused(); throw e; } } - public void connect( Repository repository ) - throws ConnectionException, AuthenticationException - { - connect( repository, null, (ProxyInfoProvider) null ); + public void connect(Repository repository) throws ConnectionException, AuthenticationException { + connect(repository, null, (ProxyInfoProvider) null); } - public void connect( Repository repository, ProxyInfo proxyInfo ) - throws ConnectionException, AuthenticationException - { - connect( repository, null, proxyInfo ); + public void connect(Repository repository, ProxyInfo proxyInfo) + throws ConnectionException, AuthenticationException { + connect(repository, null, proxyInfo); } - public void connect( Repository repository, ProxyInfoProvider proxyInfoProvider ) - throws ConnectionException, AuthenticationException - { - connect( repository, null, proxyInfoProvider ); + public void connect(Repository repository, ProxyInfoProvider proxyInfoProvider) + throws ConnectionException, AuthenticationException { + connect(repository, null, proxyInfoProvider); } - public void connect( Repository repository, AuthenticationInfo authenticationInfo ) - throws ConnectionException, AuthenticationException - { - connect( repository, authenticationInfo, (ProxyInfoProvider) null ); + public void connect(Repository repository, AuthenticationInfo authenticationInfo) + throws ConnectionException, AuthenticationException { + connect(repository, authenticationInfo, (ProxyInfoProvider) null); } - public void connect( Repository repository, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo ) - throws ConnectionException, AuthenticationException - { + public void connect(Repository repository, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo) + throws ConnectionException, AuthenticationException { final ProxyInfo proxy = proxyInfo; - connect( repository, authenticationInfo, new ProxyInfoProvider() - { - public ProxyInfo getProxyInfo( String protocol ) - { - if ( protocol == null || proxy == null || protocol.equalsIgnoreCase( proxy.getType() ) ) - { + connect(repository, authenticationInfo, new ProxyInfoProvider() { + public ProxyInfo getProxyInfo(String protocol) { + if (protocol == null || proxy == null || protocol.equalsIgnoreCase(proxy.getType())) { return proxy; - } - else - { + } else { return null; } } - } ); + }); } - public void connect( Repository repository, AuthenticationInfo authenticationInfo, - ProxyInfoProvider proxyInfoProvider ) - throws ConnectionException, AuthenticationException - { - if ( repository == null ) - { - throw new NullPointerException( "repository cannot be null" ); + public void connect( + Repository repository, AuthenticationInfo authenticationInfo, ProxyInfoProvider proxyInfoProvider) + throws ConnectionException, AuthenticationException { + if (repository == null) { + throw new NullPointerException("repository cannot be null"); } - if ( permissionsOverride != null ) - { - repository.setPermissions( permissionsOverride ); + if (permissionsOverride != null) { + repository.setPermissions(permissionsOverride); } this.repository = repository; - if ( authenticationInfo == null ) - { + if (authenticationInfo == null) { authenticationInfo = new AuthenticationInfo(); } - if ( authenticationInfo.getUserName() == null ) - { + if (authenticationInfo.getUserName() == null) { // Get user/pass that were encoded in the URL. - if ( repository.getUsername() != null ) - { - authenticationInfo.setUserName( repository.getUsername() ); - if ( repository.getPassword() != null && authenticationInfo.getPassword() == null ) - { - authenticationInfo.setPassword( repository.getPassword() ); + if (repository.getUsername() != null) { + authenticationInfo.setUserName(repository.getUsername()); + if (repository.getPassword() != null && authenticationInfo.getPassword() == null) { + authenticationInfo.setPassword(repository.getPassword()); } } } @@ -241,60 +209,44 @@ public void connect( Repository repository, AuthenticationInfo authenticationInf fireSessionOpened(); } - protected abstract void openConnectionInternal() - throws ConnectionException, AuthenticationException; + protected abstract void openConnectionInternal() throws ConnectionException, AuthenticationException; - public void disconnect() - throws ConnectionException - { + public void disconnect() throws ConnectionException { fireSessionDisconnecting(); - try - { + try { closeConnection(); - } - catch ( ConnectionException e ) - { - fireSessionError( e ); + } catch (ConnectionException e) { + fireSessionError(e); throw e; } fireSessionDisconnected(); } - protected abstract void closeConnection() - throws ConnectionException; + protected abstract void closeConnection() throws ConnectionException; - protected void createParentDirectories( File destination ) - throws TransferFailedException - { + protected void createParentDirectories(File destination) throws TransferFailedException { File destinationDirectory = destination.getParentFile(); - try - { + try { destinationDirectory = destinationDirectory.getCanonicalFile(); - } - catch ( IOException e ) - { + } catch (IOException e) { // not essential to have a canonical file } - if ( destinationDirectory != null && !destinationDirectory.exists() ) - { + if (destinationDirectory != null && !destinationDirectory.exists()) { destinationDirectory.mkdirs(); - if ( !destinationDirectory.exists() ) - { + if (!destinationDirectory.exists()) { throw new TransferFailedException( - "Specified destination directory cannot be created: " + destinationDirectory ); + "Specified destination directory cannot be created: " + destinationDirectory); } } } - public void setTimeout( int timeoutValue ) - { + public void setTimeout(int timeoutValue) { connectionTimeout = timeoutValue; } - public int getTimeout() - { + public int getTimeout() { return connectionTimeout; } @@ -302,144 +254,112 @@ public int getTimeout() // Stream i/o // ---------------------------------------------------------------------- - protected void getTransfer( Resource resource, File destination, InputStream input ) - throws TransferFailedException - { - getTransfer( resource, destination, input, true, Long.MAX_VALUE ); + protected void getTransfer(Resource resource, File destination, InputStream input) throws TransferFailedException { + getTransfer(resource, destination, input, true, Long.MAX_VALUE); } - protected void getTransfer( Resource resource, OutputStream output, InputStream input ) - throws TransferFailedException - { - getTransfer( resource, output, input, true, Long.MAX_VALUE ); + protected void getTransfer(Resource resource, OutputStream output, InputStream input) + throws TransferFailedException { + getTransfer(resource, output, input, true, Long.MAX_VALUE); } @Deprecated - protected void getTransfer( Resource resource, File destination, InputStream input, boolean closeInput, - int maxSize ) - throws TransferFailedException - { - getTransfer( resource, destination, input, closeInput, (long) maxSize ); + protected void getTransfer(Resource resource, File destination, InputStream input, boolean closeInput, int maxSize) + throws TransferFailedException { + getTransfer(resource, destination, input, closeInput, (long) maxSize); } - protected void getTransfer( Resource resource, File destination, InputStream input, boolean closeInput, - long maxSize ) - throws TransferFailedException - { + protected void getTransfer(Resource resource, File destination, InputStream input, boolean closeInput, long maxSize) + throws TransferFailedException { // ensure that the destination is created only when we are ready to transfer - fireTransferDebug( "attempting to create parent directories for destination: " + destination.getName() ); - createParentDirectories( destination ); + fireTransferDebug("attempting to create parent directories for destination: " + destination.getName()); + createParentDirectories(destination); - fireGetStarted( resource, destination ); + fireGetStarted(resource, destination); OutputStream output = null; - try - { - output = new LazyFileOutputStream( destination ); - getTransfer( resource, output, input, closeInput, maxSize ); + try { + output = new LazyFileOutputStream(destination); + getTransfer(resource, output, input, closeInput, maxSize); output.close(); output = null; - } - catch ( final IOException e ) - { - if ( destination.exists() ) - { + } catch (final IOException e) { + if (destination.exists()) { boolean deleted = destination.delete(); - if ( !deleted ) - { + if (!deleted) { destination.deleteOnExit(); } } - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + fireTransferError(resource, e, TransferEvent.REQUEST_GET); String msg = "GET request of: " + resource.getName() + " from " + repository.getName() + " failed"; - throw new TransferFailedException( msg, e ); - } - catch ( TransferFailedException e ) - { - if ( destination.exists() ) - { + throw new TransferFailedException(msg, e); + } catch (TransferFailedException e) { + if (destination.exists()) { boolean deleted = destination.delete(); - if ( !deleted ) - { + if (!deleted) { destination.deleteOnExit(); } } throw e; - } - finally - { - IOUtil.close( output ); + } finally { + IOUtil.close(output); } - fireGetCompleted( resource, destination ); + fireGetCompleted(resource, destination); } @Deprecated - protected void getTransfer( Resource resource, OutputStream output, InputStream input, boolean closeInput, - int maxSize ) - throws TransferFailedException - { - getTransfer( resource, output, input, closeInput, (long) maxSize ); + protected void getTransfer( + Resource resource, OutputStream output, InputStream input, boolean closeInput, int maxSize) + throws TransferFailedException { + getTransfer(resource, output, input, closeInput, (long) maxSize); } - protected void getTransfer( Resource resource, OutputStream output, InputStream input, boolean closeInput, - long maxSize ) - throws TransferFailedException - { - try - { - transfer( resource, input, output, TransferEvent.REQUEST_GET, maxSize ); + protected void getTransfer( + Resource resource, OutputStream output, InputStream input, boolean closeInput, long maxSize) + throws TransferFailedException { + try { + transfer(resource, input, output, TransferEvent.REQUEST_GET, maxSize); - finishGetTransfer( resource, input, output ); + finishGetTransfer(resource, input, output); - if ( closeInput ) - { + if (closeInput) { input.close(); input = null; } - } - catch ( IOException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + } catch (IOException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); String msg = "GET request of: " + resource.getName() + " from " + repository.getName() + " failed"; - throw new TransferFailedException( msg, e ); - } - finally - { - if ( closeInput ) - { - IOUtil.close( input ); + throw new TransferFailedException(msg, e); + } finally { + if (closeInput) { + IOUtil.close(input); } - cleanupGetTransfer( resource ); + cleanupGetTransfer(resource); } } - protected void finishGetTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException - { - } + protected void finishGetTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException {} - protected void cleanupGetTransfer( Resource resource ) - { - } + protected void cleanupGetTransfer(Resource resource) {} - protected void putTransfer( Resource resource, File source, OutputStream output, boolean closeOutput ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - firePutStarted( resource, source ); + protected void putTransfer(Resource resource, File source, OutputStream output, boolean closeOutput) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + firePutStarted(resource, source); - transfer( resource, source, output, closeOutput ); + transfer(resource, source, output, closeOutput); - firePutCompleted( resource, source ); + firePutCompleted(resource, source); } /** @@ -454,83 +374,67 @@ protected void putTransfer( Resource resource, File source, OutputStream output, * @throws AuthorizationException * @since 1.0-beta-1 */ - protected void transfer( Resource resource, File source, OutputStream output, boolean closeOutput ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { + protected void transfer(Resource resource, File source, OutputStream output, boolean closeOutput) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { InputStream input = null; - try - { - input = new FileInputStream( source ); + try { + input = new FileInputStream(source); - putTransfer( resource, input, output, closeOutput ); + putTransfer(resource, input, output, closeOutput); input.close(); input = null; - } - catch ( FileNotFoundException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + } catch (FileNotFoundException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( "Specified source file does not exist: " + source, e ); - } - catch ( final IOException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + throw new TransferFailedException("Specified source file does not exist: " + source, e); + } catch (final IOException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( "Failure transferring " + source, e ); - } - finally - { - IOUtil.close( input ); + throw new TransferFailedException("Failure transferring " + source, e); + } finally { + IOUtil.close(input); } } - protected void putTransfer( Resource resource, InputStream input, OutputStream output, boolean closeOutput ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - try - { - transfer( resource, input, output, TransferEvent.REQUEST_PUT, - resource.getContentLength() == WagonConstants.UNKNOWN_LENGTH - ? Long.MAX_VALUE - : resource.getContentLength() ); + protected void putTransfer(Resource resource, InputStream input, OutputStream output, boolean closeOutput) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + try { + transfer( + resource, + input, + output, + TransferEvent.REQUEST_PUT, + resource.getContentLength() == WagonConstants.UNKNOWN_LENGTH + ? Long.MAX_VALUE + : resource.getContentLength()); - finishPutTransfer( resource, input, output ); + finishPutTransfer(resource, input, output); - if ( closeOutput ) - { + if (closeOutput) { output.close(); output = null; } - } - catch ( IOException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + } catch (IOException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); String msg = "PUT request to: " + resource.getName() + " in " + repository.getName() + " failed"; - throw new TransferFailedException( msg, e ); - } - finally - { - if ( closeOutput ) - { - IOUtil.close( output ); + throw new TransferFailedException(msg, e); + } finally { + if (closeOutput) { + IOUtil.close(output); } - cleanupPutTransfer( resource ); + cleanupPutTransfer(resource); } } - protected void cleanupPutTransfer( Resource resource ) - { - } + protected void cleanupPutTransfer(Resource resource) {} - protected void finishPutTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - } + protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {} /** * Write from {@link InputStream} to {@link OutputStream}. @@ -543,10 +447,9 @@ protected void finishPutTransfer( Resource resource, InputStream input, OutputSt * @param requestType one of {@link TransferEvent#REQUEST_GET} or {@link TransferEvent#REQUEST_PUT} * @throws IOException */ - protected void transfer( Resource resource, InputStream input, OutputStream output, int requestType ) - throws IOException - { - transfer( resource, input, output, requestType, Long.MAX_VALUE ); + protected void transfer(Resource resource, InputStream input, OutputStream output, int requestType) + throws IOException { + transfer(resource, input, output, requestType, Long.MAX_VALUE); } /** @@ -563,10 +466,9 @@ protected void transfer( Resource resource, InputStream input, OutputStream outp * @deprecated Please use the transfer using long as type of maxSize */ @Deprecated - protected void transfer( Resource resource, InputStream input, OutputStream output, int requestType, int maxSize ) - throws IOException - { - transfer( resource, input, output, requestType, (long) maxSize ); + protected void transfer(Resource resource, InputStream input, OutputStream output, int requestType, int maxSize) + throws IOException { + transfer(resource, input, output, requestType, (long) maxSize); } /** @@ -581,31 +483,27 @@ protected void transfer( Resource resource, InputStream input, OutputStream outp * @param maxSize size of the buffer * @throws IOException */ - protected void transfer( Resource resource, InputStream input, OutputStream output, int requestType, long maxSize ) - throws IOException - { - ByteBuffer buffer = ByteBuffer.allocate( getBufferCapacityForTransfer( resource.getContentLength() ) ); + protected void transfer(Resource resource, InputStream input, OutputStream output, int requestType, long maxSize) + throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(getBufferCapacityForTransfer(resource.getContentLength())); int halfBufferCapacity = buffer.capacity() / 2; - TransferEvent transferEvent = new TransferEvent( this, resource, TransferEvent.TRANSFER_PROGRESS, requestType ); - transferEvent.setTimestamp( System.currentTimeMillis() ); + TransferEvent transferEvent = new TransferEvent(this, resource, TransferEvent.TRANSFER_PROGRESS, requestType); + transferEvent.setTimestamp(System.currentTimeMillis()); - ReadableByteChannel in = Channels.newChannel( input ); + ReadableByteChannel in = Channels.newChannel(input); long remaining = maxSize; - while ( remaining > 0L ) - { - int read = in.read( buffer ); + while (remaining > 0L) { + int read = in.read(buffer); - if ( read == -1 ) - { + if (read == -1) { // EOF, but some data has not been written yet. - if ( ( (Buffer) buffer ).position() != 0 ) - { - ( (Buffer) buffer ).flip(); - fireTransferProgress( transferEvent, buffer.array(), ( (Buffer) buffer ).limit() ); - output.write( buffer.array(), 0, ( (Buffer) buffer ).limit() ); - ( (Buffer) buffer ).clear(); + if (((Buffer) buffer).position() != 0) { + ((Buffer) buffer).flip(); + fireTransferProgress(transferEvent, buffer.array(), ((Buffer) buffer).limit()); + output.write(buffer.array(), 0, ((Buffer) buffer).limit()); + ((Buffer) buffer).clear(); } break; @@ -613,16 +511,15 @@ protected void transfer( Resource resource, InputStream input, OutputStream outp // Prevent minichunking/fragmentation: when less than half the buffer is utilized, // read some more bytes before writing and firing progress. - if ( ( (Buffer) buffer ).position() < halfBufferCapacity ) - { + if (((Buffer) buffer).position() < halfBufferCapacity) { continue; } - ( (Buffer) buffer ).flip(); - fireTransferProgress( transferEvent, buffer.array(), ( (Buffer) buffer ).limit() ); - output.write( buffer.array(), 0, ( (Buffer) buffer ).limit() ); - remaining -= ( (Buffer) buffer ).limit(); - ( (Buffer) buffer ).clear(); + ((Buffer) buffer).flip(); + fireTransferProgress(transferEvent, buffer.array(), ((Buffer) buffer).limit()); + output.write(buffer.array(), 0, ((Buffer) buffer).limit()); + remaining -= ((Buffer) buffer).limit(); + ((Buffer) buffer).clear(); } output.flush(); } @@ -638,269 +535,235 @@ protected void transfer( Resource resource, InputStream input, OutputStream outp * @param numberOfBytes can be 0 or less, in which case a default buffer size is used. * @return a byte buffer suitable for transferring the given amount of bytes without too many chunks. */ - protected int getBufferCapacityForTransfer( long numberOfBytes ) - { - if ( numberOfBytes <= 0L ) - { + protected int getBufferCapacityForTransfer(long numberOfBytes) { + if (numberOfBytes <= 0L) { return DEFAULT_BUFFER_SIZE; } - final long numberOfBufferSegments = numberOfBytes - / ( BUFFER_SEGMENT_SIZE * MINIMUM_AMOUNT_OF_TRANSFER_CHUNKS ); + final long numberOfBufferSegments = numberOfBytes / (BUFFER_SEGMENT_SIZE * MINIMUM_AMOUNT_OF_TRANSFER_CHUNKS); final long potentialBufferSize = numberOfBufferSegments * BUFFER_SEGMENT_SIZE; - if ( potentialBufferSize > Integer.MAX_VALUE ) - { + if (potentialBufferSize > Integer.MAX_VALUE) { return MAXIMUM_BUFFER_SIZE; } - return min( MAXIMUM_BUFFER_SIZE, max( DEFAULT_BUFFER_SIZE, (int) potentialBufferSize ) ); + return min(MAXIMUM_BUFFER_SIZE, max(DEFAULT_BUFFER_SIZE, (int) potentialBufferSize)); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - protected void fireTransferProgress( TransferEvent transferEvent, byte[] buffer, int n ) - { - transferEventSupport.fireTransferProgress( transferEvent, buffer, n ); + protected void fireTransferProgress(TransferEvent transferEvent, byte[] buffer, int n) { + transferEventSupport.fireTransferProgress(transferEvent, buffer, n); } - protected void fireGetCompleted( Resource resource, File localFile ) - { + protected void fireGetCompleted(Resource resource, File localFile) { long timestamp = System.currentTimeMillis(); TransferEvent transferEvent = - new TransferEvent( this, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET ); + new TransferEvent(this, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET); - transferEvent.setTimestamp( timestamp ); + transferEvent.setTimestamp(timestamp); - transferEvent.setLocalFile( localFile ); + transferEvent.setLocalFile(localFile); - transferEventSupport.fireTransferCompleted( transferEvent ); + transferEventSupport.fireTransferCompleted(transferEvent); } - protected void fireGetStarted( Resource resource, File localFile ) - { + protected void fireGetStarted(Resource resource, File localFile) { long timestamp = System.currentTimeMillis(); TransferEvent transferEvent = - new TransferEvent( this, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_GET ); + new TransferEvent(this, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_GET); - transferEvent.setTimestamp( timestamp ); + transferEvent.setTimestamp(timestamp); - transferEvent.setLocalFile( localFile ); + transferEvent.setLocalFile(localFile); - transferEventSupport.fireTransferStarted( transferEvent ); + transferEventSupport.fireTransferStarted(transferEvent); } - protected void fireGetInitiated( Resource resource, File localFile ) - { + protected void fireGetInitiated(Resource resource, File localFile) { long timestamp = System.currentTimeMillis(); TransferEvent transferEvent = - new TransferEvent( this, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET ); + new TransferEvent(this, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET); - transferEvent.setTimestamp( timestamp ); + transferEvent.setTimestamp(timestamp); - transferEvent.setLocalFile( localFile ); + transferEvent.setLocalFile(localFile); - transferEventSupport.fireTransferInitiated( transferEvent ); + transferEventSupport.fireTransferInitiated(transferEvent); } - protected void firePutInitiated( Resource resource, File localFile ) - { + protected void firePutInitiated(Resource resource, File localFile) { long timestamp = System.currentTimeMillis(); TransferEvent transferEvent = - new TransferEvent( this, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_PUT ); + new TransferEvent(this, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_PUT); - transferEvent.setTimestamp( timestamp ); + transferEvent.setTimestamp(timestamp); - transferEvent.setLocalFile( localFile ); + transferEvent.setLocalFile(localFile); - transferEventSupport.fireTransferInitiated( transferEvent ); + transferEventSupport.fireTransferInitiated(transferEvent); } - protected void firePutCompleted( Resource resource, File localFile ) - { + protected void firePutCompleted(Resource resource, File localFile) { long timestamp = System.currentTimeMillis(); TransferEvent transferEvent = - new TransferEvent( this, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_PUT ); + new TransferEvent(this, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_PUT); - transferEvent.setTimestamp( timestamp ); + transferEvent.setTimestamp(timestamp); - transferEvent.setLocalFile( localFile ); + transferEvent.setLocalFile(localFile); - transferEventSupport.fireTransferCompleted( transferEvent ); + transferEventSupport.fireTransferCompleted(transferEvent); } - protected void firePutStarted( Resource resource, File localFile ) - { + protected void firePutStarted(Resource resource, File localFile) { long timestamp = System.currentTimeMillis(); TransferEvent transferEvent = - new TransferEvent( this, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_PUT ); + new TransferEvent(this, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_PUT); - transferEvent.setTimestamp( timestamp ); + transferEvent.setTimestamp(timestamp); - transferEvent.setLocalFile( localFile ); + transferEvent.setLocalFile(localFile); - transferEventSupport.fireTransferStarted( transferEvent ); + transferEventSupport.fireTransferStarted(transferEvent); } - protected void fireSessionDisconnected() - { + protected void fireSessionDisconnected() { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, SessionEvent.SESSION_DISCONNECTED ); + SessionEvent sessionEvent = new SessionEvent(this, SessionEvent.SESSION_DISCONNECTED); - sessionEvent.setTimestamp( timestamp ); + sessionEvent.setTimestamp(timestamp); - sessionEventSupport.fireSessionDisconnected( sessionEvent ); + sessionEventSupport.fireSessionDisconnected(sessionEvent); } - protected void fireSessionDisconnecting() - { + protected void fireSessionDisconnecting() { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, SessionEvent.SESSION_DISCONNECTING ); + SessionEvent sessionEvent = new SessionEvent(this, SessionEvent.SESSION_DISCONNECTING); - sessionEvent.setTimestamp( timestamp ); + sessionEvent.setTimestamp(timestamp); - sessionEventSupport.fireSessionDisconnecting( sessionEvent ); + sessionEventSupport.fireSessionDisconnecting(sessionEvent); } - protected void fireSessionLoggedIn() - { + protected void fireSessionLoggedIn() { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, SessionEvent.SESSION_LOGGED_IN ); + SessionEvent sessionEvent = new SessionEvent(this, SessionEvent.SESSION_LOGGED_IN); - sessionEvent.setTimestamp( timestamp ); + sessionEvent.setTimestamp(timestamp); - sessionEventSupport.fireSessionLoggedIn( sessionEvent ); + sessionEventSupport.fireSessionLoggedIn(sessionEvent); } - protected void fireSessionLoggedOff() - { + protected void fireSessionLoggedOff() { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, SessionEvent.SESSION_LOGGED_OFF ); + SessionEvent sessionEvent = new SessionEvent(this, SessionEvent.SESSION_LOGGED_OFF); - sessionEvent.setTimestamp( timestamp ); + sessionEvent.setTimestamp(timestamp); - sessionEventSupport.fireSessionLoggedOff( sessionEvent ); + sessionEventSupport.fireSessionLoggedOff(sessionEvent); } - protected void fireSessionOpened() - { + protected void fireSessionOpened() { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, SessionEvent.SESSION_OPENED ); + SessionEvent sessionEvent = new SessionEvent(this, SessionEvent.SESSION_OPENED); - sessionEvent.setTimestamp( timestamp ); + sessionEvent.setTimestamp(timestamp); - sessionEventSupport.fireSessionOpened( sessionEvent ); + sessionEventSupport.fireSessionOpened(sessionEvent); } - protected void fireSessionOpening() - { + protected void fireSessionOpening() { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, SessionEvent.SESSION_OPENING ); + SessionEvent sessionEvent = new SessionEvent(this, SessionEvent.SESSION_OPENING); - sessionEvent.setTimestamp( timestamp ); + sessionEvent.setTimestamp(timestamp); - sessionEventSupport.fireSessionOpening( sessionEvent ); + sessionEventSupport.fireSessionOpening(sessionEvent); } - protected void fireSessionConnectionRefused() - { + protected void fireSessionConnectionRefused() { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, SessionEvent.SESSION_CONNECTION_REFUSED ); + SessionEvent sessionEvent = new SessionEvent(this, SessionEvent.SESSION_CONNECTION_REFUSED); - sessionEvent.setTimestamp( timestamp ); + sessionEvent.setTimestamp(timestamp); - sessionEventSupport.fireSessionConnectionRefused( sessionEvent ); + sessionEventSupport.fireSessionConnectionRefused(sessionEvent); } - protected void fireSessionError( Exception exception ) - { + protected void fireSessionError(Exception exception) { long timestamp = System.currentTimeMillis(); - SessionEvent sessionEvent = new SessionEvent( this, exception ); - - sessionEvent.setTimestamp( timestamp ); + SessionEvent sessionEvent = new SessionEvent(this, exception); - sessionEventSupport.fireSessionError( sessionEvent ); + sessionEvent.setTimestamp(timestamp); + sessionEventSupport.fireSessionError(sessionEvent); } - protected void fireTransferDebug( String message ) - { - transferEventSupport.fireDebug( message ); + protected void fireTransferDebug(String message) { + transferEventSupport.fireDebug(message); } - protected void fireSessionDebug( String message ) - { - sessionEventSupport.fireDebug( message ); + protected void fireSessionDebug(String message) { + sessionEventSupport.fireDebug(message); } - public boolean hasTransferListener( TransferListener listener ) - { - return transferEventSupport.hasTransferListener( listener ); + public boolean hasTransferListener(TransferListener listener) { + return transferEventSupport.hasTransferListener(listener); } - public void addTransferListener( TransferListener listener ) - { - transferEventSupport.addTransferListener( listener ); + public void addTransferListener(TransferListener listener) { + transferEventSupport.addTransferListener(listener); } - public void removeTransferListener( TransferListener listener ) - { - transferEventSupport.removeTransferListener( listener ); + public void removeTransferListener(TransferListener listener) { + transferEventSupport.removeTransferListener(listener); } - public void addSessionListener( SessionListener listener ) - { - sessionEventSupport.addSessionListener( listener ); + public void addSessionListener(SessionListener listener) { + sessionEventSupport.addSessionListener(listener); } - public boolean hasSessionListener( SessionListener listener ) - { - return sessionEventSupport.hasSessionListener( listener ); + public boolean hasSessionListener(SessionListener listener) { + return sessionEventSupport.hasSessionListener(listener); } - public void removeSessionListener( SessionListener listener ) - { - sessionEventSupport.removeSessionListener( listener ); + public void removeSessionListener(SessionListener listener) { + sessionEventSupport.removeSessionListener(listener); } - protected void fireTransferError( Resource resource, Exception e, int requestType ) - { - TransferEvent transferEvent = new TransferEvent( this, resource, e, requestType ); - transferEventSupport.fireTransferError( transferEvent ); + protected void fireTransferError(Resource resource, Exception e, int requestType) { + TransferEvent transferEvent = new TransferEvent(this, resource, e, requestType); + transferEventSupport.fireTransferError(transferEvent); } - - public SessionEventSupport getSessionEventSupport() - { + public SessionEventSupport getSessionEventSupport() { return sessionEventSupport; } - public void setSessionEventSupport( SessionEventSupport sessionEventSupport ) - { + public void setSessionEventSupport(SessionEventSupport sessionEventSupport) { this.sessionEventSupport = sessionEventSupport; } - public TransferEventSupport getTransferEventSupport() - { + public TransferEventSupport getTransferEventSupport() { return transferEventSupport; } - public void setTransferEventSupport( TransferEventSupport transferEventSupport ) - { + public void setTransferEventSupport(TransferEventSupport transferEventSupport) { this.transferEventSupport = transferEventSupport; } @@ -908,122 +771,98 @@ public void setTransferEventSupport( TransferEventSupport transferEventSupport ) * This method is used if you are not streaming the transfer, to make sure any listeners dependent on state * (eg checksum observers) succeed. */ - protected void postProcessListeners( Resource resource, File source, int requestType ) - throws TransferFailedException - { + protected void postProcessListeners(Resource resource, File source, int requestType) + throws TransferFailedException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - TransferEvent transferEvent = new TransferEvent( this, resource, TransferEvent.TRANSFER_PROGRESS, requestType ); - transferEvent.setTimestamp( System.currentTimeMillis() ); - transferEvent.setLocalFile( source ); + TransferEvent transferEvent = new TransferEvent(this, resource, TransferEvent.TRANSFER_PROGRESS, requestType); + transferEvent.setTimestamp(System.currentTimeMillis()); + transferEvent.setLocalFile(source); InputStream input = null; - try - { - input = new FileInputStream( source ); + try { + input = new FileInputStream(source); - while ( true ) - { - int n = input.read( buffer ); + while (true) { + int n = input.read(buffer); - if ( n == -1 ) - { + if (n == -1) { break; } - fireTransferProgress( transferEvent, buffer, n ); + fireTransferProgress(transferEvent, buffer, n); } input.close(); input = null; - } - catch ( IOException e ) - { - fireTransferError( resource, e, requestType ); + } catch (IOException e) { + fireTransferError(resource, e, requestType); - throw new TransferFailedException( "Failed to post-process the source file", e ); - } - finally - { - IOUtil.close( input ); + throw new TransferFailedException("Failed to post-process the source file", e); + } finally { + IOUtil.close(input); } } - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - throw new UnsupportedOperationException( "The wagon you are using has not implemented putDirectory()" ); + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + throw new UnsupportedOperationException("The wagon you are using has not implemented putDirectory()"); } - public boolean supportsDirectoryCopy() - { + public boolean supportsDirectoryCopy() { return false; } - protected static String getPath( String basedir, String dir ) - { + protected static String getPath(String basedir, String dir) { String path; path = basedir; - if ( !basedir.endsWith( "/" ) && !dir.startsWith( "/" ) ) - { + if (!basedir.endsWith("/") && !dir.startsWith("/")) { path += "/"; } path += dir; return path; } - public boolean isInteractive() - { + public boolean isInteractive() { return interactive; } - public void setInteractive( boolean interactive ) - { + public void setInteractive(boolean interactive) { this.interactive = interactive; } - public List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - throw new UnsupportedOperationException( "The wagon you are using has not implemented getFileList()" ); + public List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + throw new UnsupportedOperationException("The wagon you are using has not implemented getFileList()"); } - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - throw new UnsupportedOperationException( "The wagon you are using has not implemented resourceExists()" ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + throw new UnsupportedOperationException("The wagon you are using has not implemented resourceExists()"); } - protected ProxyInfo getProxyInfo( String protocol, String host ) - { - if ( proxyInfoProvider != null ) - { - ProxyInfo proxyInfo = proxyInfoProvider.getProxyInfo( protocol ); - if ( !ProxyUtils.validateNonProxyHosts( proxyInfo, host ) ) - { + protected ProxyInfo getProxyInfo(String protocol, String host) { + if (proxyInfoProvider != null) { + ProxyInfo proxyInfo = proxyInfoProvider.getProxyInfo(protocol); + if (!ProxyUtils.validateNonProxyHosts(proxyInfo, host)) { return proxyInfo; } } return null; } - public RepositoryPermissions getPermissionsOverride() - { + public RepositoryPermissions getPermissionsOverride() { return permissionsOverride; } - public void setPermissionsOverride( RepositoryPermissions permissionsOverride ) - { + public void setPermissionsOverride(RepositoryPermissions permissionsOverride) { this.permissionsOverride = permissionsOverride; } - public void setReadTimeout( int readTimeout ) - { + public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } - public int getReadTimeout() - { + public int getReadTimeout() { return this.readTimeout; } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutionException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutionException.java index 5568e1d9a..9755a5382 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutionException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * Exception which should be thrown when a command fails to execute on the repository. @@ -25,24 +24,19 @@ * @author Brett Porter * */ -public class CommandExecutionException - extends WagonException -{ +public class CommandExecutionException extends WagonException { /** * @see org.apache.maven.wagon.WagonException */ - public CommandExecutionException( String message ) - { - super( message ); + public CommandExecutionException(String message) { + super(message); } /** * @see org.apache.maven.wagon.WagonException */ - public CommandExecutionException( String message, Throwable cause ) - { - super( message, cause ); + public CommandExecutionException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutor.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutor.java index 5476c8fd1..d3e501f8f 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutor.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/CommandExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * @author Brett Porter * */ -public interface CommandExecutor - extends Wagon -{ +public interface CommandExecutor extends Wagon { String ROLE = CommandExecutor.class.getName(); - void executeCommand( String command ) - throws CommandExecutionException; + void executeCommand(String command) throws CommandExecutionException; - Streams executeCommand( String command, boolean ignoreFailures ) - throws CommandExecutionException; + Streams executeCommand(String command, boolean ignoreFailures) throws CommandExecutionException; } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/ConnectionException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/ConnectionException.java index ad4a64ed2..a2e699a26 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/ConnectionException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/ConnectionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * The exception is thrown when a connection @@ -26,25 +25,19 @@ * @author Michal Maczka * */ -public class ConnectionException - extends WagonException -{ - +public class ConnectionException extends WagonException { /** * @see org.apache.maven.wagon.WagonException */ - public ConnectionException( final String message ) - { - super( message ); + public ConnectionException(final String message) { + super(message); } /** * @see org.apache.maven.wagon.WagonException */ - public ConnectionException( final String message, final Throwable cause ) - { - super( message, cause ); + public ConnectionException(final String message, final Throwable cause) { + super(message, cause); } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/InputData.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/InputData.java index c9b4b6b55..c9fd1edb0 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/InputData.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/InputData.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,39 +16,34 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.resource.Resource; +package org.apache.maven.wagon; import java.io.InputStream; +import org.apache.maven.wagon.resource.Resource; + /** * @author Michal Maczka * */ -public class InputData -{ +public class InputData { private InputStream inputStream; private Resource resource; - public InputStream getInputStream() - { + public InputStream getInputStream() { return inputStream; } - public void setInputStream( InputStream inputStream ) - { + public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } - public Resource getResource() - { + public Resource getResource() { return resource; } - public void setResource( Resource resource ) - { + public void setResource(Resource resource) { this.resource = resource; } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/LazyFileOutputStream.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/LazyFileOutputStream.java index bb37340d7..ca248e36e 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/LazyFileOutputStream.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/LazyFileOutputStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.File; import java.io.FileDescriptor; @@ -27,7 +26,6 @@ import java.io.OutputStream; import java.nio.channels.FileChannel; - /** * Variant of FileOutputStream which creates the file only when first portion * of data is written. @@ -35,122 +33,87 @@ * @author Michal Maczka * */ -public class LazyFileOutputStream - extends OutputStream -{ +public class LazyFileOutputStream extends OutputStream { private File file; private FileOutputStream delegee; - - public LazyFileOutputStream( String filename ) - { - this.file = new File( filename ); + public LazyFileOutputStream(String filename) { + this.file = new File(filename); } - public LazyFileOutputStream( File file ) - { + public LazyFileOutputStream(File file) { this.file = file; } - - public void close() - throws IOException - { - if ( delegee != null ) - { + public void close() throws IOException { + if (delegee != null) { delegee.close(); } } - - public boolean equals( Object obj ) - { - return delegee.equals( obj ); + public boolean equals(Object obj) { + return delegee.equals(obj); } - - public void flush() - throws IOException - { - if ( delegee != null ) - { + public void flush() throws IOException { + if (delegee != null) { delegee.flush(); } } - - public FileChannel getChannel() - { + public FileChannel getChannel() { return delegee.getChannel(); } - - public FileDescriptor getFD() - throws IOException - { + public FileDescriptor getFD() throws IOException { return delegee.getFD(); } - public int hashCode() - { + public int hashCode() { return delegee.hashCode(); } - - public String toString() - { + public String toString() { return delegee.toString(); } - public void write( byte[] b ) - throws IOException - { - if ( delegee == null ) - { + public void write(byte[] b) throws IOException { + if (delegee == null) { initialize(); } - delegee.write( b ); + delegee.write(b); } /** * @see java.io.OutputStream#write(byte[], int, int) */ - public void write( byte[] b, int off, int len ) - throws IOException - { - if ( delegee == null ) - { + public void write(byte[] b, int off, int len) throws IOException { + if (delegee == null) { initialize(); } - delegee.write( b, off, len ); + delegee.write(b, off, len); } /** * @param b * @throws java.io.IOException */ - public void write( int b ) - throws IOException - { - if ( delegee == null ) - { + public void write(int b) throws IOException { + if (delegee == null) { initialize(); } - delegee.write( b ); + delegee.write(b); } - /** - * + * */ - private void initialize() - throws FileNotFoundException - { - delegee = new FileOutputStream( file ); + private void initialize() throws FileNotFoundException { + delegee = new FileOutputStream(file); } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/OutputData.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/OutputData.java index 792f78533..92d26eacc 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/OutputData.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/OutputData.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,38 +16,34 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.resource.Resource; +package org.apache.maven.wagon; import java.io.OutputStream; +import org.apache.maven.wagon.resource.Resource; + /** * @author Michal Maczka * */ -public class OutputData -{ +public class OutputData { private OutputStream outputStream; private Resource resource; - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { return outputStream; } - public void setOutputStream( OutputStream outputStream ) - { + public void setOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } - public Resource getResource() - { + public Resource getResource() { return resource; } - public void setResource( Resource resource ) - { + public void setResource(Resource resource) { this.resource = resource; } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/PathUtils.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/PathUtils.java index bee85b324..998bca055 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/PathUtils.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/PathUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.File; import java.util.StringTokenizer; @@ -28,11 +27,8 @@ * @author Michal Maczka * */ -public final class PathUtils -{ - private PathUtils() - { - } +public final class PathUtils { + private PathUtils() {} /** * Returns the directory path portion of a file specification string. @@ -40,11 +36,10 @@ private PathUtils() * * @return The directory portion excluding the ending file separator. */ - public static String dirname( final String path ) - { - final int i = path.lastIndexOf( "/" ); + public static String dirname(final String path) { + final int i = path.lastIndexOf("/"); - return ( ( i >= 0 ) ? path.substring( 0, i ) : "" ); + return ((i >= 0) ? path.substring(0, i) : ""); } /** @@ -52,38 +47,30 @@ public static String dirname( final String path ) * * @return The filename string with extension. */ - public static String filename( final String path ) - { - final int i = path.lastIndexOf( "/" ); - return ( ( i >= 0 ) ? path.substring( i + 1 ) : path ); + public static String filename(final String path) { + final int i = path.lastIndexOf("/"); + return ((i >= 0) ? path.substring(i + 1) : path); } - public static String[] dirnames( final String path ) - { - final String dirname = PathUtils.dirname( path ); - return split( dirname, "/", -1 ); - + public static String[] dirnames(final String path) { + final String dirname = PathUtils.dirname(path); + return split(dirname, "/", -1); } - private static String[] split( final String str, final String separator, final int max ) - { + private static String[] split(final String str, final String separator, final int max) { final StringTokenizer tok; - if ( separator == null ) - { + if (separator == null) { // Null separator means we're using StringTokenizer's default // delimiter, which comprises all whitespace characters. - tok = new StringTokenizer( str ); - } - else - { - tok = new StringTokenizer( str, separator ); + tok = new StringTokenizer(str); + } else { + tok = new StringTokenizer(str, separator); } int listSize = tok.countTokens(); - if ( max > 0 && listSize > max ) - { + if (max > 0 && listSize > max) { listSize = max; } @@ -94,27 +81,23 @@ private static String[] split( final String str, final String separator, final i int lastTokenBegin; int lastTokenEnd = 0; - while ( tok.hasMoreTokens() ) - { - if ( max > 0 && i == listSize - 1 ) - { + while (tok.hasMoreTokens()) { + if (max > 0 && i == listSize - 1) { // In the situation where we hit the max yet have // tokens left over in our input, the last list // element gets all remaining text. final String endToken = tok.nextToken(); - lastTokenBegin = str.indexOf( endToken, lastTokenEnd ); + lastTokenBegin = str.indexOf(endToken, lastTokenEnd); - list[i] = str.substring( lastTokenBegin ); + list[i] = str.substring(lastTokenBegin); break; - } - else - { + } else { list[i] = tok.nextToken(); - lastTokenBegin = str.indexOf( list[i], lastTokenEnd ); + lastTokenBegin = str.indexOf(list[i], lastTokenEnd); lastTokenEnd = lastTokenBegin + list[i].length(); } @@ -131,84 +114,73 @@ private static String[] split( final String str, final String separator, final i * @param url the url * @return the host name */ - public static String host( final String url ) - { - if ( url == null || url.length() == 0 ) - { + public static String host(final String url) { + if (url == null || url.length() == 0) { return "localhost"; } - String authorization = authorization( url ); - int index = authorization.indexOf( '@' ); - String host = ( index >= 0 ) ? authorization.substring( index + 1 ) : authorization; + String authorization = authorization(url); + int index = authorization.indexOf('@'); + String host = (index >= 0) ? authorization.substring(index + 1) : authorization; // In case we have IPv6 in the host portion of url // we have to remove brackets '[' and ']' - return ( ( host.charAt( 0 ) == '[' ) && ( host.charAt( host.length() - 1 ) == ']' ) ) - ? host.substring( 1, host.length() - 1 ) - : host; + return ((host.charAt(0) == '[') && (host.charAt(host.length() - 1) == ']')) + ? host.substring(1, host.length() - 1) + : host; } /** * This was changed from private to package local so that it can be unit tested. */ - static String authorization( final String url ) - { - if ( url == null ) - { + static String authorization(final String url) { + if (url == null) { return "localhost"; } - String protocol = PathUtils.protocol( url ); + String protocol = PathUtils.protocol(url); - if ( protocol == null || protocol.equalsIgnoreCase( "file" ) ) - { + if (protocol == null || protocol.equalsIgnoreCase("file")) { return "localhost"; } String host = url; - if ( protocol.equalsIgnoreCase( "scm" ) ) - { + if (protocol.equalsIgnoreCase("scm")) { // skip over type - host = host.substring( host.indexOf( ":", 4 ) + 1 ).trim(); + host = host.substring(host.indexOf(":", 4) + 1).trim(); } - protocol = PathUtils.protocol( host ); + protocol = PathUtils.protocol(host); - if ( protocol.equalsIgnoreCase( "file" ) ) - { + if (protocol.equalsIgnoreCase("file")) { return "localhost"; } // skip over protocol - host = host.substring( host.indexOf( ":" ) + 1 ).trim(); - if ( host.startsWith( "//" ) ) - { - host = host.substring( 2 ); + host = host.substring(host.indexOf(":") + 1).trim(); + if (host.startsWith("//")) { + host = host.substring(2); } - int pos = host.indexOf( "/" ); + int pos = host.indexOf("/"); - if ( pos > 0 ) - { - host = host.substring( 0, pos ); + if (pos > 0) { + host = host.substring(0, pos); } - pos = host.indexOf( '@' ); + pos = host.indexOf('@'); - pos = ( pos > 0 ) ? endOfHostPosition( host, pos ) : endOfHostPosition( host, 0 ); + pos = (pos > 0) ? endOfHostPosition(host, pos) : endOfHostPosition(host, 0); - if ( pos > 0 ) - { - host = host.substring( 0, pos ); + if (pos > 0) { + host = host.substring(0, pos); } return host; } - private static int endOfHostPosition( String host, int pos ) - { + private static int endOfHostPosition(String host, int pos) { // if this is IPv6 then it will be in IPv6 Literal Addresses in URL's format // see: http://www.ietf.org/rfc/rfc2732.txt - int endOfIPv6Pos = host.indexOf( ']', pos ); - return ( endOfIPv6Pos > 0 ) ? endOfIPv6Pos + 1 : host.indexOf( ":", pos ); + int endOfIPv6Pos = host.indexOf(']', pos); + return (endOfIPv6Pos > 0) ? endOfIPv6Pos + 1 : host.indexOf(":", pos); } /** @@ -221,80 +193,66 @@ private static int endOfHostPosition( String host, int pos ) * @param url the url * @return the host name */ - public static String protocol( final String url ) - { - final int pos = url.indexOf( ":" ); + public static String protocol(final String url) { + final int pos = url.indexOf(":"); - if ( pos == -1 ) - { + if (pos == -1) { return ""; } - return url.substring( 0, pos ).trim(); + return url.substring(0, pos).trim(); } /** * @param url * @return the port or {@link WagonConstants#UNKNOWN_PORT} if not existent */ - public static int port( String url ) - { + public static int port(String url) { - final String protocol = PathUtils.protocol( url ); + final String protocol = PathUtils.protocol(url); - if ( protocol == null || protocol.equalsIgnoreCase( "file" ) ) - { + if (protocol == null || protocol.equalsIgnoreCase("file")) { return WagonConstants.UNKNOWN_PORT; } - final String authorization = PathUtils.authorization( url ); + final String authorization = PathUtils.authorization(url); - if ( authorization == null ) - { + if (authorization == null) { return WagonConstants.UNKNOWN_PORT; } - if ( protocol.equalsIgnoreCase( "scm" ) ) - { + if (protocol.equalsIgnoreCase("scm")) { // skip over type - url = url.substring( url.indexOf( ":", 4 ) + 1 ).trim(); + url = url.substring(url.indexOf(":", 4) + 1).trim(); } - if ( url.regionMatches( true, 0, "file:", 0, 5 ) || url.regionMatches( true, 0, "local:", 0, 6 ) ) - { + if (url.regionMatches(true, 0, "file:", 0, 5) || url.regionMatches(true, 0, "local:", 0, 6)) { return WagonConstants.UNKNOWN_PORT; } // skip over protocol - url = url.substring( url.indexOf( ":" ) + 1 ).trim(); - if ( url.startsWith( "//" ) ) - { - url = url.substring( 2 ); + url = url.substring(url.indexOf(":") + 1).trim(); + if (url.startsWith("//")) { + url = url.substring(2); } int start = authorization.length(); - if ( url.length() > start && url.charAt( start ) == ':' ) - { - int end = url.indexOf( '/', start ); + if (url.length() > start && url.charAt(start) == ':') { + int end = url.indexOf('/', start); - if ( end == start + 1 ) - { + if (end == start + 1) { // it is :/ return WagonConstants.UNKNOWN_PORT; } - if ( end == -1 ) - { + if (end == -1) { end = url.length(); } - return Integer.parseInt( url.substring( start + 1, end ) ); - } - else - { + return Integer.parseInt(url.substring(start + 1, end)); + } else { return WagonConstants.UNKNOWN_PORT; } - } /** @@ -304,52 +262,40 @@ public static int port( String url ) * @return the basedir of the repository * @todo need to URL decode for spaces? */ - public static String basedir( String url ) - { - String protocol = PathUtils.protocol( url ); + public static String basedir(String url) { + String protocol = PathUtils.protocol(url); String retValue = null; - if ( protocol.equalsIgnoreCase( "scm" ) ) - { + if (protocol.equalsIgnoreCase("scm")) { // skip over SCM bits - if ( url.regionMatches( true, 0, "scm:svn:", 0, 8 ) ) - { - url = url.substring( url.indexOf( ":", 4 ) + 1 ); - protocol = PathUtils.protocol( url ); + if (url.regionMatches(true, 0, "scm:svn:", 0, 8)) { + url = url.substring(url.indexOf(":", 4) + 1); + protocol = PathUtils.protocol(url); } } - if ( protocol.equalsIgnoreCase( "file" ) ) - { - retValue = url.substring( protocol.length() + 1 ); - retValue = decode( retValue ); + if (protocol.equalsIgnoreCase("file")) { + retValue = url.substring(protocol.length() + 1); + retValue = decode(retValue); // special case: if omitted // on protocol, keep path as is - if ( retValue.startsWith( "//" ) ) - { - retValue = retValue.substring( 2 ); + if (retValue.startsWith("//")) { + retValue = retValue.substring(2); - if ( retValue.length() >= 2 && ( retValue.charAt( 1 ) == '|' || retValue.charAt( 1 ) == ':' ) ) - { + if (retValue.length() >= 2 && (retValue.charAt(1) == '|' || retValue.charAt(1) == ':')) { // special case: if there is a windows drive letter, then keep the original return value - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); - } - else - { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); + } else { // Now we expect the host - int index = retValue.indexOf( "/" ); - if ( index >= 0 ) - { - retValue = retValue.substring( index + 1 ); + int index = retValue.indexOf("/"); + if (index >= 0) { + retValue = retValue.substring(index + 1); } // special case: if there is a windows drive letter, then keep the original return value - if ( retValue.length() >= 2 && ( retValue.charAt( 1 ) == '|' || retValue.charAt( 1 ) == ':' ) ) - { - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); - } - else if ( index >= 0 ) - { + if (retValue.length() >= 2 && (retValue.charAt(1) == '|' || retValue.charAt(1) == ':')) { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); + } else if (index >= 0) { // leading / was previously stripped retValue = "/" + retValue; } @@ -357,56 +303,45 @@ else if ( index >= 0 ) } // special case: if there is a windows drive letter using |, switch to : - if ( retValue.length() >= 2 && retValue.charAt( 1 ) == '|' ) - { - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); + if (retValue.length() >= 2 && retValue.charAt(1) == '|') { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); } - } - else - { - final String authorization = PathUtils.authorization( url ); + } else { + final String authorization = PathUtils.authorization(url); - final int port = PathUtils.port( url ); + final int port = PathUtils.port(url); int pos = 0; - if ( protocol.equalsIgnoreCase( "scm" ) ) - { - pos = url.indexOf( ":", 4 ) + 1; - pos = url.indexOf( ":", pos ) + 1; - } - else - { - int index = url.indexOf( "://" ); - if ( index != -1 ) - { + if (protocol.equalsIgnoreCase("scm")) { + pos = url.indexOf(":", 4) + 1; + pos = url.indexOf(":", pos) + 1; + } else { + int index = url.indexOf("://"); + if (index != -1) { pos = index + 3; } } pos += authorization.length(); - if ( port != WagonConstants.UNKNOWN_PORT ) - { - pos = pos + Integer.toString( port ).length() + 1; + if (port != WagonConstants.UNKNOWN_PORT) { + pos = pos + Integer.toString(port).length() + 1; } - if ( url.length() > pos ) - { - retValue = url.substring( pos ); - if ( retValue.startsWith( ":" ) ) - { + if (url.length() > pos) { + retValue = url.substring(pos); + if (retValue.startsWith(":")) { // this is for :/ after the host - retValue = retValue.substring( 1 ); + retValue = retValue.substring(1); } // one module may be allowed in the path in CVS - retValue = retValue.replace( ':', '/' ); + retValue = retValue.replace(':', '/'); } } - if ( retValue == null ) - { + if (retValue == null) { retValue = "/"; } return retValue.trim(); @@ -419,83 +354,65 @@ else if ( index >= 0 ) * @param url The URL to decode, may be null. * @return The decoded URL or null if the input was null. */ - private static String decode( String url ) - { + private static String decode(String url) { String decoded = url; - if ( url != null ) - { + if (url != null) { int pos = -1; - while ( ( pos = decoded.indexOf( '%', pos + 1 ) ) >= 0 ) - { - if ( pos + 2 < decoded.length() ) - { - String hexStr = decoded.substring( pos + 1, pos + 3 ); - char ch = (char) Integer.parseInt( hexStr, 16 ); - decoded = decoded.substring( 0, pos ) + ch + decoded.substring( pos + 3 ); + while ((pos = decoded.indexOf('%', pos + 1)) >= 0) { + if (pos + 2 < decoded.length()) { + String hexStr = decoded.substring(pos + 1, pos + 3); + char ch = (char) Integer.parseInt(hexStr, 16); + decoded = decoded.substring(0, pos) + ch + decoded.substring(pos + 3); } } } return decoded; } - public static String user( String url ) - { - String host = authorization( url ); - int index = host.indexOf( '@' ); - if ( index > 0 ) - { - String userInfo = host.substring( 0, index ); - index = userInfo.indexOf( ':' ); - if ( index > 0 ) - { - return userInfo.substring( 0, index ); - } - else if ( index < 0 ) - { + public static String user(String url) { + String host = authorization(url); + int index = host.indexOf('@'); + if (index > 0) { + String userInfo = host.substring(0, index); + index = userInfo.indexOf(':'); + if (index > 0) { + return userInfo.substring(0, index); + } else if (index < 0) { return userInfo; } } return null; } - public static String password( String url ) - { - String host = authorization( url ); - int index = host.indexOf( '@' ); - if ( index > 0 ) - { - String userInfo = host.substring( 0, index ); - index = userInfo.indexOf( ':' ); - if ( index >= 0 ) - { - return userInfo.substring( index + 1 ); + public static String password(String url) { + String host = authorization(url); + int index = host.indexOf('@'); + if (index > 0) { + String userInfo = host.substring(0, index); + index = userInfo.indexOf(':'); + if (index >= 0) { + return userInfo.substring(index + 1); } } return null; } // TODO: move to plexus-utils or use something appropriate from there - public static String toRelative( File basedir, String absolutePath ) - { + public static String toRelative(File basedir, String absolutePath) { String relative; - absolutePath = absolutePath.replace( '\\', '/' ); - String basedirPath = basedir.getAbsolutePath().replace( '\\', '/' ); + absolutePath = absolutePath.replace('\\', '/'); + String basedirPath = basedir.getAbsolutePath().replace('\\', '/'); - if ( absolutePath.startsWith( basedirPath ) ) - { - relative = absolutePath.substring( basedirPath.length() ); - if ( relative.startsWith( "/" ) ) - { - relative = relative.substring( 1 ); + if (absolutePath.startsWith(basedirPath)) { + relative = absolutePath.substring(basedirPath.length()); + if (relative.startsWith("/")) { + relative = relative.substring(1); } - if ( relative.length() <= 0 ) - { + if (relative.length() <= 0) { relative = "."; } - } - else - { + } else { relative = absolutePath; } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/PermissionModeUtils.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/PermissionModeUtils.java index bc4c86c10..0bd90b4e5 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/PermissionModeUtils.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/PermissionModeUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * Utility class for common operations for file/directory permissions. @@ -26,47 +25,36 @@ * @see PermissionModeUtils * @since Sep 3, 2005 */ -public final class PermissionModeUtils -{ - private PermissionModeUtils() - { - } - +public final class PermissionModeUtils { + private PermissionModeUtils() {} + /** * See the System Interfaces volume of IEEE Std 1003.1-2001, umask(1) * * @param modeStr permission mode (numeric or symbolic) * @return the mode that can be used with umask to accomplish modeStr. */ - public static String getUserMaskFor( String modeStr ) - { + public static String getUserMaskFor(String modeStr) { String ret = null; - try - { - int mode = Integer.valueOf( modeStr, 8 ).intValue(); + try { + int mode = Integer.valueOf(modeStr, 8).intValue(); - mode = mode % 8 + ( ( mode / 8 ) % 8 ) * 8 + ( ( mode / 64 ) % 8 ) * 64; + mode = mode % 8 + ((mode / 8) % 8) * 8 + ((mode / 64) % 8) * 64; // CHECKSTYLE_OFF: MagicNumber - ret = Integer.toOctalString( 0777 - mode ); + ret = Integer.toOctalString(0777 - mode); // CHECKSTYLE_ON: MagicNumber - } - catch ( final NumberFormatException e ) - { - try - { - Integer.parseInt( modeStr ); - } - catch ( final NumberFormatException e1 ) - { + } catch (final NumberFormatException e) { + try { + Integer.parseInt(modeStr); + } catch (final NumberFormatException e1) { ret = modeStr; } } - if ( ret == null ) - { - throw new IllegalArgumentException( "The mode is a number but is not octal" ); + if (ret == null) { + throw new IllegalArgumentException("The mode is a number but is not octal"); } return ret; diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/ResourceDoesNotExistException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/ResourceDoesNotExistException.java index 8e8919bf6..f331fb604 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/ResourceDoesNotExistException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/ResourceDoesNotExistException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,30 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * @author Michal Maczka * */ -public class ResourceDoesNotExistException - extends WagonException -{ +public class ResourceDoesNotExistException extends WagonException { /** * @param message */ - public ResourceDoesNotExistException( final String message ) - { - super( message ); + public ResourceDoesNotExistException(final String message) { + super(message); } /** * @param message * @param cause */ - public ResourceDoesNotExistException( final String message, final Throwable cause ) - { - super( message, cause ); + public ResourceDoesNotExistException(final String message, final Throwable cause) { + super(message, cause); } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamWagon.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamWagon.java index 5773cf0d2..071171ad0 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamWagon.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.File; import java.io.IOException; @@ -34,120 +33,91 @@ * @author Michal Maczka * */ -public abstract class StreamWagon - extends AbstractWagon - implements StreamingWagon -{ +public abstract class StreamWagon extends AbstractWagon implements StreamingWagon { // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - public abstract void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + public abstract void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; - public abstract void fillOutputData( OutputData outputData ) - throws TransferFailedException; + public abstract void fillOutputData(OutputData outputData) throws TransferFailedException; - public abstract void closeConnection() - throws ConnectionException; + public abstract void closeConnection() throws ConnectionException; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - public void get( String resourceName, File destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - getIfNewer( resourceName, destination, 0 ); + public void get(String resourceName, File destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + getIfNewer(resourceName, destination, 0); } - protected void checkInputStream( InputStream is, Resource resource ) - throws TransferFailedException - { - if ( is == null ) - { - TransferFailedException e = - new TransferFailedException( getRepository().getUrl() - + " - Could not open input stream for resource: '" + resource + "'" ); - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + protected void checkInputStream(InputStream is, Resource resource) throws TransferFailedException { + if (is == null) { + TransferFailedException e = new TransferFailedException( + getRepository().getUrl() + " - Could not open input stream for resource: '" + resource + "'"); + fireTransferError(resource, e, TransferEvent.REQUEST_GET); throw e; } } - public boolean getIfNewer( String resourceName, File destination, long timestamp ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public boolean getIfNewer(String resourceName, File destination, long timestamp) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { boolean retValue = false; - Resource resource = new Resource( resourceName ); + Resource resource = new Resource(resourceName); + + fireGetInitiated(resource, destination); - fireGetInitiated( resource, destination ); + resource.setLastModified(timestamp); - resource.setLastModified( timestamp ); - - InputStream is = getInputStream( resource ); + InputStream is = getInputStream(resource); // always get if timestamp is 0 (ie, target doesn't exist), otherwise only if older than the remote file - if ( timestamp == 0 || timestamp < resource.getLastModified() ) - { + if (timestamp == 0 || timestamp < resource.getLastModified()) { retValue = true; - checkInputStream( is, resource ); + checkInputStream(is, resource); - getTransfer( resource, destination, is ); - } - else - { - try - { - if ( is != null ) - { + getTransfer(resource, destination, is); + } else { + try { + if (is != null) { is.close(); } - } - catch ( final IOException e ) - { - throw new TransferFailedException( "Failure transferring " + resourceName, e ); + } catch (final IOException e) { + throw new TransferFailedException("Failure transferring " + resourceName, e); } } return retValue; } - protected InputStream getInputStream( Resource resource ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + protected InputStream getInputStream(Resource resource) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { InputData inputData = new InputData(); - inputData.setResource( resource ); + inputData.setResource(resource); - try - { - fillInputData( inputData ); - } - catch ( TransferFailedException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); - cleanupGetTransfer( resource ); + try { + fillInputData(inputData); + } catch (TransferFailedException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); + cleanupGetTransfer(resource); throw e; - } - catch ( ResourceDoesNotExistException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); - cleanupGetTransfer( resource ); + } catch (ResourceDoesNotExistException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); + cleanupGetTransfer(resource); throw e; - } - catch ( AuthorizationException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); - cleanupGetTransfer( resource ); + } catch (AuthorizationException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); + cleanupGetTransfer(resource); throw e; - } - finally - { - if ( inputData.getInputStream() == null ) - { - cleanupGetTransfer( resource ); + } finally { + if (inputData.getInputStream() == null) { + cleanupGetTransfer(resource); } } @@ -155,148 +125,123 @@ protected InputStream getInputStream( Resource resource ) } // source doesn't exist exception - public void put( File source, String resourceName ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( resourceName ); + public void put(File source, String resourceName) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(resourceName); - firePutInitiated( resource, source ); + firePutInitiated(resource, source); - resource.setContentLength( source.length() ); + resource.setContentLength(source.length()); - resource.setLastModified( source.lastModified() ); + resource.setLastModified(source.lastModified()); - OutputStream os = getOutputStream( resource ); + OutputStream os = getOutputStream(resource); - checkOutputStream( resource, os ); + checkOutputStream(resource, os); - putTransfer( resource, source, os, true ); + putTransfer(resource, source, os, true); } - protected void checkOutputStream( Resource resource, OutputStream os ) - throws TransferFailedException - { - if ( os == null ) - { - TransferFailedException e = - new TransferFailedException( getRepository().getUrl() - + " - Could not open output stream for resource: '" + resource + "'" ); - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + protected void checkOutputStream(Resource resource, OutputStream os) throws TransferFailedException { + if (os == null) { + TransferFailedException e = new TransferFailedException( + getRepository().getUrl() + " - Could not open output stream for resource: '" + resource + "'"); + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; } } - protected OutputStream getOutputStream( Resource resource ) - throws TransferFailedException - { + protected OutputStream getOutputStream(Resource resource) throws TransferFailedException { OutputData outputData = new OutputData(); - outputData.setResource( resource ); + outputData.setResource(resource); - try - { - fillOutputData( outputData ); - } - catch ( TransferFailedException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + try { + fillOutputData(outputData); + } catch (TransferFailedException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; - } - finally - { - if ( outputData.getOutputStream() == null ) - { - cleanupPutTransfer( resource ); + } finally { + if (outputData.getOutputStream() == null) { + cleanupPutTransfer(resource); } } return outputData.getOutputStream(); } - public boolean getIfNewerToStream( String resourceName, OutputStream stream, long timestamp ) - throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException - { + public boolean getIfNewerToStream(String resourceName, OutputStream stream, long timestamp) + throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException { boolean retValue = false; - Resource resource = new Resource( resourceName ); + Resource resource = new Resource(resourceName); - fireGetInitiated( resource, null ); + fireGetInitiated(resource, null); - InputStream is = getInputStream( resource ); + InputStream is = getInputStream(resource); // always get if timestamp is 0 (ie, target doesn't exist), otherwise only if older than the remote file - if ( timestamp == 0 || timestamp < resource.getLastModified() ) - { + if (timestamp == 0 || timestamp < resource.getLastModified()) { retValue = true; - checkInputStream( is, resource ); + checkInputStream(is, resource); - fireGetStarted( resource, null ); + fireGetStarted(resource, null); - getTransfer( resource, stream, is, true, Integer.MAX_VALUE ); + getTransfer(resource, stream, is, true, Integer.MAX_VALUE); - fireGetCompleted( resource, null ); - } - else - { - try - { - if ( is != null ) - { + fireGetCompleted(resource, null); + } else { + try { + if (is != null) { is.close(); } - } - catch ( final IOException e ) - { - throw new TransferFailedException( "Failure transferring " + resourceName, e ); + } catch (final IOException e) { + throw new TransferFailedException("Failure transferring " + resourceName, e); } } - + return retValue; } - public void getToStream( String resourceName, OutputStream stream ) - throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException - { - getIfNewerToStream( resourceName, stream, 0 ); + public void getToStream(String resourceName, OutputStream stream) + throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException { + getIfNewerToStream(resourceName, stream, 0); } - public void putFromStream( InputStream stream, String destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( destination ); + public void putFromStream(InputStream stream, String destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(destination); - firePutInitiated( resource, null ); + firePutInitiated(resource, null); - putFromStream( stream, resource ); + putFromStream(stream, resource); } - public void putFromStream( InputStream stream, String destination, long contentLength, long lastModified ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( destination ); + public void putFromStream(InputStream stream, String destination, long contentLength, long lastModified) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(destination); - firePutInitiated( resource, null ); + firePutInitiated(resource, null); - resource.setContentLength( contentLength ); + resource.setContentLength(contentLength); - resource.setLastModified( lastModified ); + resource.setLastModified(lastModified); - putFromStream( stream, resource ); + putFromStream(stream, resource); } - protected void putFromStream( InputStream stream, Resource resource ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - OutputStream os = getOutputStream( resource ); + protected void putFromStream(InputStream stream, Resource resource) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + OutputStream os = getOutputStream(resource); - checkOutputStream( resource, os ); + checkOutputStream(resource, os); - firePutStarted( resource, null ); + firePutStarted(resource, null); - putTransfer( resource, stream, os, true ); + putTransfer(resource, stream, os, true); - firePutCompleted( resource, null ); + firePutCompleted(resource, null); } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamingWagon.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamingWagon.java index a6208f22c..3ddbdbfa3 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamingWagon.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/StreamingWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.InputStream; import java.io.OutputStream; @@ -25,28 +24,26 @@ import org.apache.maven.wagon.authorization.AuthorizationException; /** - * + * */ -public interface StreamingWagon - extends Wagon -{ +public interface StreamingWagon extends Wagon { /** * Downloads specified resource from the repository to given output stream. - * + * * @param resourceName * @param stream * @throws TransferFailedException * @throws ResourceDoesNotExistException - * @throws AuthorizationException + * @throws AuthorizationException * @throws AuthorizationException */ - void getToStream( String resourceName, OutputStream stream ) - throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException; + void getToStream(String resourceName, OutputStream stream) + throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException; /** * Downloads specified resource from the repository if it was modified since specified date. The date is measured in * milliseconds, between the current time and midnight, January 1, 1970 UTC and aligned to GMT timezone. - * + * * @param resourceName * @param stream * @param timestamp @@ -54,36 +51,36 @@ void getToStream( String resourceName, OutputStream stream ) * repository is older or has the same age. * @throws TransferFailedException * @throws ResourceDoesNotExistException - * @throws AuthorizationException + * @throws AuthorizationException * @throws AuthorizationException */ - boolean getIfNewerToStream( String resourceName, OutputStream stream, long timestamp ) - throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException; + boolean getIfNewerToStream(String resourceName, OutputStream stream, long timestamp) + throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException; /** * @deprecated due to unknown contentLength various http(s) implementation will use a chuncked transfer encoding * mode you must take care you http target server supports that (ngnix don't !). * So in case of http(s) transport layer avoid using this. Will be remove in 3.0 * Copy from a local input stream to remote. - * + * * @param stream the local stream * @param destination the remote destination * @throws TransferFailedException * @throws ResourceDoesNotExistException * @throws AuthorizationException */ - void putFromStream( InputStream stream, String destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + void putFromStream(InputStream stream, String destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; /** * Copy from a local input stream to remote. - * + * * @param stream the local stream * @param destination the remote destination * @throws TransferFailedException * @throws ResourceDoesNotExistException * @throws AuthorizationException */ - void putFromStream( InputStream stream, String destination, long contentLength, long lastModified ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + void putFromStream(InputStream stream, String destination, long contentLength, long lastModified) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/Streams.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/Streams.java index a3d09d828..e7d06cbbc 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/Streams.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/Streams.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,33 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** - * + * */ -public class Streams -{ +public class Streams { private String out = ""; private String err = ""; - public String getOut() - { + public String getOut() { return out; } - public void setOut( String out ) - { + public void setOut(String out) { this.out = out; } - public String getErr() - { + public String getErr() { return err; } - public void setErr( String err ) - { + public void setErr(String err) { this.err = err; } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/TransferFailedException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/TransferFailedException.java index 9f8f9a8bf..a5be7babc 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/TransferFailedException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/TransferFailedException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * Exception which should be thrown when IO error occurred during @@ -26,24 +25,19 @@ * @author Michal Maczka * */ -public class TransferFailedException - extends WagonException -{ +public class TransferFailedException extends WagonException { /** * @see org.apache.maven.wagon.WagonException */ - public TransferFailedException( final String message ) - { - super( message ); + public TransferFailedException(final String message) { + super(message); } /** * @see org.apache.maven.wagon.WagonException */ - public TransferFailedException( final String message, final Throwable cause ) - { - super( message, cause ); + public TransferFailedException(final String message, final Throwable cause) { + super(message, cause); } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/UnsupportedProtocolException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/UnsupportedProtocolException.java index 73b1a8804..be5fe2ec7 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/UnsupportedProtocolException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/UnsupportedProtocolException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * This exception is thrown when no Wagon provider is supporting protocol required by some repository @@ -25,26 +24,19 @@ * @author Michal Maczka * */ -public class UnsupportedProtocolException - extends WagonException -{ - +public class UnsupportedProtocolException extends WagonException { /** * @see WagonException */ - public UnsupportedProtocolException( final String message ) - { - super( message ); + public UnsupportedProtocolException(final String message) { + super(message); } /** * @see WagonException */ - public UnsupportedProtocolException( final String message, final Throwable cause ) - { - super( message, cause ); + public UnsupportedProtocolException(final String message, final Throwable cause) { + super(message, cause); } - - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/Wagon.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/Wagon.java index 0b7672897..5da751758 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/Wagon.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/Wagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; + +import java.io.File; +import java.util.List; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authentication.AuthenticationInfo; @@ -28,14 +30,10 @@ import org.apache.maven.wagon.proxy.ProxyInfoProvider; import org.apache.maven.wagon.repository.Repository; -import java.io.File; -import java.util.List; - /** - * + * */ -public interface Wagon -{ +public interface Wagon { String ROLE = Wagon.class.getName(); /** @@ -63,8 +61,8 @@ public interface Wagon * @throws ResourceDoesNotExistException * @throws AuthorizationException */ - void get( String resourceName, File destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + void get(String resourceName, File destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; /** * Downloads specified resource from the repository @@ -81,8 +79,8 @@ void get( String resourceName, File destination ) * @throws ResourceDoesNotExistException * @throws AuthorizationException */ - boolean getIfNewer( String resourceName, File destination, long timestamp ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + boolean getIfNewer(String resourceName, File destination, long timestamp) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; /** * Copy a file from local system to remote @@ -93,8 +91,8 @@ boolean getIfNewer( String resourceName, File destination, long timestamp ) * @throws ResourceDoesNotExistException * @throws AuthorizationException */ - void put( File source, String destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + void put(File source, String destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; /** * Copy a directory from local system to remote @@ -105,8 +103,8 @@ void put( File source, String destination ) * @throws ResourceDoesNotExistException * @throws AuthorizationException */ - void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; /** * Check if a remote resource exists @@ -116,8 +114,7 @@ void putDirectory( File sourceDirectory, String destinationDirectory ) * @throws TransferFailedException if there's an error trying to access the remote side * @throws AuthorizationException if not authorized to verify the existence of the resource */ - boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException; + boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException; /** *

@@ -143,8 +140,8 @@ boolean resourceExists( String resourceName ) * @throws ResourceDoesNotExistException if destinationDirectory does not exist or is not a directory * @throws AuthorizationException if not authorized to list the contents of the directory */ - List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; + List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException; /** * Flag indicating if this wagon supports directory copy operations. @@ -167,8 +164,7 @@ List getFileList( String destinationDirectory ) * @throws org.apache.maven.wagon.authentication.AuthenticationException * if the credentials for connecting are not sufficient */ - void connect( Repository source ) - throws ConnectionException, AuthenticationException; + void connect(Repository source) throws ConnectionException, AuthenticationException; /** * Initiate the connection to the repository. @@ -178,8 +174,7 @@ void connect( Repository source ) * @throws org.apache.maven.wagon.authentication.AuthenticationException * if the credentials for connecting are not sufficient */ - void connect( Repository source, ProxyInfo proxyInfo ) - throws ConnectionException, AuthenticationException; + void connect(Repository source, ProxyInfo proxyInfo) throws ConnectionException, AuthenticationException; /** * Initiate the connection to the repository. @@ -190,8 +185,8 @@ void connect( Repository source, ProxyInfo proxyInfo ) * @throws org.apache.maven.wagon.authentication.AuthenticationException * if the credentials for connecting are not sufficient */ - void connect( Repository source, ProxyInfoProvider proxyInfoProvider ) - throws ConnectionException, AuthenticationException; + void connect(Repository source, ProxyInfoProvider proxyInfoProvider) + throws ConnectionException, AuthenticationException; /** * Initiate the connection to the repository. @@ -202,8 +197,8 @@ void connect( Repository source, ProxyInfoProvider proxyInfoProvider ) * @throws org.apache.maven.wagon.authentication.AuthenticationException * if the credentials for connecting are not sufficient */ - void connect( Repository source, AuthenticationInfo authenticationInfo ) - throws ConnectionException, AuthenticationException; + void connect(Repository source, AuthenticationInfo authenticationInfo) + throws ConnectionException, AuthenticationException; /** * Initiate the connection to the repository. @@ -215,8 +210,8 @@ void connect( Repository source, AuthenticationInfo authenticationInfo ) * @throws org.apache.maven.wagon.authentication.AuthenticationException * if the credentials for connecting are not sufficient */ - void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo ) - throws ConnectionException, AuthenticationException; + void connect(Repository source, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo) + throws ConnectionException, AuthenticationException; /** * Initiate the connection to the repository. @@ -228,8 +223,8 @@ void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInf * @throws org.apache.maven.wagon.authentication.AuthenticationException * if the credentials for connecting are not sufficient */ - void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfoProvider proxyInfoProvider ) - throws ConnectionException, AuthenticationException; + void connect(Repository source, AuthenticationInfo authenticationInfo, ProxyInfoProvider proxyInfoProvider) + throws ConnectionException, AuthenticationException; /** * Initiate the connection to the repository. @@ -241,22 +236,20 @@ void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInf * @deprecated connect using the {@link #connect(org.apache.maven.wagon.repository.Repository)} or related methods * - this is an internal method */ - void openConnection() - throws ConnectionException, AuthenticationException; + void openConnection() throws ConnectionException, AuthenticationException; /** * Disconnect from the repository. * * @throws ConnectionException if there is a problem disconnecting */ - void disconnect() - throws ConnectionException; - + void disconnect() throws ConnectionException; + /** * Set the connection timeout limit in milliseconds */ - void setTimeout( int timeoutValue ); - + void setTimeout(int timeoutValue); + /** * Get the connection timeout limit in milliseconds */ @@ -266,7 +259,7 @@ void disconnect() * Set the read timeout limit in milliseconds * @since 2.2 */ - void setReadTimeout( int timeoutValue ); + void setReadTimeout(int timeoutValue); /** * Get the read timeout limit in milliseconds @@ -278,23 +271,23 @@ void disconnect() // Session listener // ---------------------------------------------------------------------- - void addSessionListener( SessionListener listener ); + void addSessionListener(SessionListener listener); - void removeSessionListener( SessionListener listener ); + void removeSessionListener(SessionListener listener); - boolean hasSessionListener( SessionListener listener ); + boolean hasSessionListener(SessionListener listener); // ---------------------------------------------------------------------- // Transfer listener // ---------------------------------------------------------------------- - void addTransferListener( TransferListener listener ); + void addTransferListener(TransferListener listener); - void removeTransferListener( TransferListener listener ); + void removeTransferListener(TransferListener listener); - boolean hasTransferListener( TransferListener listener ); + boolean hasTransferListener(TransferListener listener); boolean isInteractive(); - void setInteractive( boolean interactive ); + void setInteractive(boolean interactive); } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonConstants.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonConstants.java index 27b66b1d0..042b79851 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonConstants.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonConstants.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * This class contains constants used in Wagon API. @@ -25,8 +24,7 @@ * @author Michal Maczka * */ -public final class WagonConstants -{ +public final class WagonConstants { /** * Indicates that port has not been set. */ diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonException.java index 25dc053fe..23f6c8984 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; /** * Root class for all exception in Wagon API @@ -25,15 +24,12 @@ * @author Michal Maczka * */ -public abstract class WagonException - extends Exception -{ +public abstract class WagonException extends Exception { /** * the throwable that caused this exception to get thrown */ private Throwable cause; - /** * Constructs a new WagonException with the specified detail message. * The cause is not initialized, and may subsequently be initialized by a call to initCause @@ -42,10 +38,9 @@ public abstract class WagonException * @param cause - the cause (which is saved for later retrieval by the getCause() method). * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) */ - public WagonException( final String message, final Throwable cause ) - { - super( message ); - initCause( cause ); + public WagonException(final String message, final Throwable cause) { + super(message); + initCause(cause); } /** @@ -53,9 +48,8 @@ public WagonException( final String message, final Throwable cause ) * * @param message - the detail message (which is saved for later retrieval by the getMessage() method). */ - public WagonException( final String message ) - { - super( message ); + public WagonException(final String message) { + super(message); } /** @@ -64,26 +58,24 @@ public WagonException( final String message ) * * @return the cause of this exception or null if the cause is nonexistent or unknown. */ - public Throwable getCause() - { -// try -// { -// Class clazz = getClass().getSuperclass(); -// -// Method method = clazz.getMethod( "gatCause" , null ); -// -// Throwable retValue = (Throwable) method.invoke( this, null ); -// return retValue; -// } -// catch( Exception e) -// { -// -// } - + public Throwable getCause() { + // try + // { + // Class clazz = getClass().getSuperclass(); + // + // Method method = clazz.getMethod( "gatCause" , null ); + // + // Throwable retValue = (Throwable) method.invoke( this, null ); + // return retValue; + // } + // catch( Exception e) + // { + // + // } + return cause; } - /** * Initializes the cause of this throwable to the specified value. * (The cause is the throwable that caused this throwable to get thrown.) @@ -94,23 +86,21 @@ public Throwable getCause() * * @return a reference to this Throwable instance. */ - public Throwable initCause( final Throwable cause ) - { -// try -// { -// Class clazz = getClass().getSuperclass(); -// Class[] parameterTypes = new Class[1]; -// parameterTypes[0] = Throwable.class; -// Method method = clazz.getMethod( "initCause" , parameterTypes); -// Object[] params = { cause }; -// method.invoke( this, params ); -// } -// catch( Exception e) -// { -// -// } + public Throwable initCause(final Throwable cause) { + // try + // { + // Class clazz = getClass().getSuperclass(); + // Class[] parameterTypes = new Class[1]; + // parameterTypes[0] = Throwable.class; + // Method method = clazz.getMethod( "initCause" , parameterTypes); + // Object[] params = { cause }; + // method.invoke( this, params ); + // } + // catch( Exception e) + // { + // + // } this.cause = cause; return this; } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonUtils.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonUtils.java index 426344040..85ae8855f 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonUtils.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/WagonUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,105 +16,80 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.authorization.AuthorizationException; -import org.codehaus.plexus.util.FileUtils; +package org.apache.maven.wagon; import java.io.File; import java.io.IOException; import java.util.LinkedList; +import org.apache.maven.wagon.authorization.AuthorizationException; +import org.codehaus.plexus.util.FileUtils; + /** * @author Michal Maczka * * @deprecated */ -public final class WagonUtils -{ - private WagonUtils() - { - } +public final class WagonUtils { + private WagonUtils() {} - public static String toString( String resource, Wagon wagon ) - throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public static String toString(String resource, Wagon wagon) + throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException { File file = null; - try - { - file = File.createTempFile( "wagon", "tmp" ); + try { + file = File.createTempFile("wagon", "tmp"); - wagon.get( resource, file ); + wagon.get(resource, file); - return FileUtils.fileRead( file ); - } - finally - { - if ( file != null ) - { + return FileUtils.fileRead(file); + } finally { + if (file != null) { boolean deleted = file.delete(); - if ( !deleted ) - { + if (!deleted) { file.deleteOnExit(); } } } - } - - public static void putDirectory( File dir, Wagon wagon, boolean includeBasdir ) - throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException - { + public static void putDirectory(File dir, Wagon wagon, boolean includeBasdir) + throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException { LinkedList queue = new LinkedList(); - if ( includeBasdir ) - { - queue.add( dir.getName() ); - } - else - { - queue.add( "" ); + if (includeBasdir) { + queue.add(dir.getName()); + } else { + queue.add(""); } - while ( !queue.isEmpty() ) - { + while (!queue.isEmpty()) { String path = (String) queue.removeFirst(); - File currentDir = new File( dir, path ); + File currentDir = new File(dir, path); File[] files = currentDir.listFiles(); - for ( int i = 0; i < files.length; i++ ) - { + for (int i = 0; i < files.length; i++) { File file = files[i]; String resource; - if ( path.length() > 0 ) - { + if (path.length() > 0) { resource = path + "/" + file.getName(); - } - else - { + } else { resource = file.getName(); } - if ( file.isDirectory() ) - { - queue.add( resource ); + if (file.isDirectory()) { + queue.add(resource); + } else { + wagon.put(file, resource); } - else - { - wagon.put( file, resource ); - } - } - } - } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationException.java index 9094c750d..7656352b1 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.authentication; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.authentication; import org.apache.maven.wagon.WagonException; @@ -30,24 +29,19 @@ * @author Michal Maczka * */ -public class AuthenticationException - extends WagonException -{ +public class AuthenticationException extends WagonException { /** * @see org.apache.maven.wagon.WagonException */ - public AuthenticationException( final String message ) - { - super( message ); + public AuthenticationException(final String message) { + super(message); } /** * @see org.apache.maven.wagon.WagonException */ - public AuthenticationException( final String message, final Throwable cause ) - { - super( message, cause ); + public AuthenticationException(final String message, final Throwable cause) { + super(message, cause); } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationInfo.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationInfo.java index 6e9271771..089f8bfe3 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationInfo.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/authentication/AuthenticationInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.authentication; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.authentication; import java.io.Serializable; @@ -28,9 +27,7 @@ * @author Michal Maczka * */ -public class AuthenticationInfo - implements Serializable -{ +public class AuthenticationInfo implements Serializable { /** * Username used to login to the host @@ -59,8 +56,7 @@ public class AuthenticationInfo * * @return passphrase of the private key file */ - public String getPassphrase() - { + public String getPassphrase() { return passphrase; } @@ -69,8 +65,7 @@ public String getPassphrase() * * @param passphrase passphrase of the private key file */ - public void setPassphrase( final String passphrase ) - { + public void setPassphrase(final String passphrase) { this.passphrase = passphrase; } @@ -79,8 +74,7 @@ public void setPassphrase( final String passphrase ) * * @return absolute path to private key */ - public String getPrivateKey() - { + public String getPrivateKey() { return privateKey; } @@ -89,8 +83,7 @@ public String getPrivateKey() * * @param privateKey path to private key in local file system */ - public void setPrivateKey( final String privateKey ) - { + public void setPrivateKey(final String privateKey) { this.privateKey = privateKey; } @@ -99,8 +92,7 @@ public void setPrivateKey( final String privateKey ) * * @return password of user */ - public String getPassword() - { + public String getPassword() { return password; } @@ -109,8 +101,7 @@ public String getPassword() * * @param password password of the user */ - public void setPassword( final String password ) - { + public void setPassword(final String password) { this.password = password; } @@ -119,8 +110,7 @@ public void setPassword( final String password ) * * @return username at repository */ - public String getUserName() - { + public String getUserName() { return userName; } @@ -129,8 +119,7 @@ public String getUserName() * * @param userName the username used to access repository */ - public void setUserName( final String userName ) - { + public void setUserName(final String userName) { this.userName = userName; } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/authorization/AuthorizationException.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/authorization/AuthorizationException.java index a3f931042..f0625af2a 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/authorization/AuthorizationException.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/authorization/AuthorizationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.authorization; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.authorization; import org.apache.maven.wagon.WagonException; @@ -28,26 +27,19 @@ * @author Michal Maczka * */ -public class AuthorizationException - extends WagonException -{ - +public class AuthorizationException extends WagonException { /** * @see org.apache.maven.wagon.WagonException */ - public AuthorizationException( final String message ) - { - super( message ); + public AuthorizationException(final String message) { + super(message); } /** * @see org.apache.maven.wagon.WagonException */ - public AuthorizationException( final String message, final Throwable cause ) - { - super( message, cause ); + public AuthorizationException(final String message, final Throwable cause) { + super(message, cause); } - - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEvent.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEvent.java index 712ead611..c123aedae 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEvent.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import org.apache.maven.wagon.Wagon; @@ -39,9 +38,7 @@ * @author Michal Maczka * */ -public class SessionEvent - extends WagonEvent -{ +public class SessionEvent extends WagonEvent { /** * A SESSION was closed. @@ -101,11 +98,9 @@ public class SessionEvent * @param wagon Wagon object which created this event * @param eventType the type of the event */ - public SessionEvent( final Wagon wagon, final int eventType ) - { - super( wagon ); + public SessionEvent(final Wagon wagon, final int eventType) { + super(wagon); this.eventType = eventType; - } /** @@ -114,37 +109,31 @@ public SessionEvent( final Wagon wagon, final int eventType ) * @param wagon Wagon object which created this event * @param exception the exception */ - public SessionEvent( final Wagon wagon, final Exception exception ) - { - super( wagon ); + public SessionEvent(final Wagon wagon, final Exception exception) { + super(wagon); this.exception = exception; this.eventType = SESSION_ERROR_OCCURRED; - } /** * @return Returns the type. */ - public int getEventType() - { + public int getEventType() { return eventType; } /** * @return Returns the exception. */ - public Exception getException() - { + public Exception getException() { return exception; } /** * @param eventType The eventType to set. */ - public void setEventType( final int eventType ) - { - switch ( eventType ) - { + public void setEventType(final int eventType) { + switch (eventType) { case SessionEvent.SESSION_CLOSED: case SessionEvent.SESSION_DISCONNECTED: case SessionEvent.SESSION_DISCONNECTING: @@ -155,8 +144,8 @@ public void setEventType( final int eventType ) case SessionEvent.SESSION_OPENING: case SessionEvent.SESSION_CONNECTION_REFUSED: break; - default : - throw new IllegalArgumentException( "Illegal event type: " + eventType ); + default: + throw new IllegalArgumentException("Illegal event type: " + eventType); } this.eventType = eventType; } @@ -164,62 +153,58 @@ public void setEventType( final int eventType ) /** * @param exception The exception to set. */ - public void setException( final Exception exception ) - { + public void setException(final Exception exception) { this.exception = exception; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( "SessionEvent[" ); + sb.append("SessionEvent["); - switch ( this.eventType ) - { + switch (this.eventType) { case SessionEvent.SESSION_CLOSED: - sb.append( "CONNECTION_CLOSED" ); + sb.append("CONNECTION_CLOSED"); break; case SessionEvent.SESSION_DISCONNECTED: - sb.append( "CONNECTION_DISCONNECTED" ); + sb.append("CONNECTION_DISCONNECTED"); break; case SessionEvent.SESSION_DISCONNECTING: - sb.append( "CONNECTION_DISCONNECTING" ); + sb.append("CONNECTION_DISCONNECTING"); break; case SessionEvent.SESSION_ERROR_OCCURRED: - sb.append( "CONNECTION_ERROR_OCCURRED" ); + sb.append("CONNECTION_ERROR_OCCURRED"); break; case SessionEvent.SESSION_LOGGED_IN: - sb.append( "CONNECTION_LOGGED_IN" ); + sb.append("CONNECTION_LOGGED_IN"); break; case SessionEvent.SESSION_LOGGED_OFF: - sb.append( "CONNECTION_LOGGED_OFF" ); + sb.append("CONNECTION_LOGGED_OFF"); break; case SessionEvent.SESSION_OPENED: - sb.append( "CONNECTION_OPENED" ); + sb.append("CONNECTION_OPENED"); break; case SessionEvent.SESSION_OPENING: - sb.append( "CONNECTION_OPENING" ); + sb.append("CONNECTION_OPENING"); break; case SessionEvent.SESSION_CONNECTION_REFUSED: - sb.append( "CONNECTION_CONNECTION_REFUSED" ); + sb.append("CONNECTION_CONNECTION_REFUSED"); break; default: - sb.append( eventType ); + sb.append(eventType); } - sb.append( "|" ); + sb.append("|"); - sb.append( this.getWagon().getRepository() ).append( "|" ); - sb.append( this.source ); + sb.append(this.getWagon().getRepository()).append("|"); + sb.append(this.source); - if ( exception != null ) - { - sb.append( "|" ); - sb.append( exception.getClass().getName() ).append( ":" ); - sb.append( exception.getMessage() ); + if (exception != null) { + sb.append("|"); + sb.append(exception.getClass().getName()).append(":"); + sb.append(exception.getMessage()); } - sb.append( "]" ); + sb.append("]"); return sb.toString(); } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEventSupport.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEventSupport.java index efe95d042..cd2b6640f 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEventSupport.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionEventSupport.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import java.util.ArrayList; import java.util.List; @@ -28,8 +27,7 @@ * @author Michal Maczka * */ -public final class SessionEventSupport -{ +public final class SessionEventSupport { /** * registered listeners */ @@ -46,11 +44,9 @@ public final class SessionEventSupport * @see #removeSessionListener(SessionListener) * @see TransferListener */ - public void addSessionListener( final SessionListener listener ) - { - if ( listener != null ) - { - listeners.add( listener ); + public void addSessionListener(final SessionListener listener) { + if (listener != null) { + listeners.add(listener); } } @@ -65,9 +61,8 @@ public void addSessionListener( final SessionListener listener ) * @param listener the session listener * @see #addSessionListener(org.apache.maven.wagon.events.SessionListener) */ - public void removeSessionListener( final SessionListener listener ) - { - listeners.remove( listener ); + public void removeSessionListener(final SessionListener listener) { + listeners.remove(listener); } /** @@ -82,9 +77,8 @@ public void removeSessionListener( final SessionListener listener ) * @see org.apache.maven.wagon.events.SessionListener * @see #addSessionListener(org.apache.maven.wagon.events.SessionListener) */ - public boolean hasSessionListener( final SessionListener listener ) - { - return listeners.contains( listener ); + public boolean hasSessionListener(final SessionListener listener) { + return listeners.contains(listener); } /** @@ -94,11 +88,9 @@ public boolean hasSessionListener( final SessionListener listener ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionDisconnected( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionDisconnected( sessionEvent ); + public void fireSessionDisconnected(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionDisconnected(sessionEvent); } } @@ -109,11 +101,9 @@ public void fireSessionDisconnected( final SessionEvent sessionEvent ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionDisconnecting( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionDisconnecting( sessionEvent ); + public void fireSessionDisconnecting(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionDisconnecting(sessionEvent); } } @@ -124,11 +114,9 @@ public void fireSessionDisconnecting( final SessionEvent sessionEvent ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionLoggedIn( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionLoggedIn( sessionEvent ); + public void fireSessionLoggedIn(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionLoggedIn(sessionEvent); } } @@ -139,11 +127,9 @@ public void fireSessionLoggedIn( final SessionEvent sessionEvent ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionLoggedOff( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionLoggedOff( sessionEvent ); + public void fireSessionLoggedOff(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionLoggedOff(sessionEvent); } } @@ -154,11 +140,9 @@ public void fireSessionLoggedOff( final SessionEvent sessionEvent ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionOpened( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionOpened( sessionEvent ); + public void fireSessionOpened(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionOpened(sessionEvent); } } @@ -169,11 +153,9 @@ public void fireSessionOpened( final SessionEvent sessionEvent ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionOpening( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionOpening( sessionEvent ); + public void fireSessionOpening(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionOpening(sessionEvent); } } @@ -184,11 +166,9 @@ public void fireSessionOpening( final SessionEvent sessionEvent ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionConnectionRefused( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionConnectionRefused( sessionEvent ); + public void fireSessionConnectionRefused(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionConnectionRefused(sessionEvent); } } @@ -198,11 +178,9 @@ public void fireSessionConnectionRefused( final SessionEvent sessionEvent ) * * @param message the debug message which will be dispatched to listeners */ - public void fireDebug( final String message ) - { - for ( SessionListener listener : listeners ) - { - listener.debug( message ); + public void fireDebug(final String message) { + for (SessionListener listener : listeners) { + listener.debug(message); } } @@ -214,11 +192,9 @@ public void fireDebug( final String message ) * * @param sessionEvent the SessionEvent which will be dispatched to listeners */ - public void fireSessionError( final SessionEvent sessionEvent ) - { - for ( SessionListener listener : listeners ) - { - listener.sessionError( sessionEvent ); + public void fireSessionError(final SessionEvent sessionEvent) { + for (SessionListener listener : listeners) { + listener.sessionError(sessionEvent); } } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionListener.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionListener.java index d60c71d38..48e030f39 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionListener.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/SessionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; /** * Interface for classes which wants to receive and respond to any session update events. @@ -25,8 +24,7 @@ * @author Michal Maczka * */ -public interface SessionListener -{ +public interface SessionListener { /** * This method will be called when Wagon is about to open @@ -36,7 +34,7 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionOpening( SessionEvent sessionEvent ); + void sessionOpening(SessionEvent sessionEvent); /** * This method will be called when Wagon has successfully connected to @@ -46,7 +44,7 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionOpened( SessionEvent sessionEvent ); + void sessionOpened(SessionEvent sessionEvent); /** * This method will be called when Wagon has closed connection to @@ -56,7 +54,7 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionDisconnecting( SessionEvent sessionEvent ); + void sessionDisconnecting(SessionEvent sessionEvent); /** * This method will be called when Wagon has closed connection to @@ -66,7 +64,7 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionDisconnected( SessionEvent sessionEvent ); + void sessionDisconnected(SessionEvent sessionEvent); /** * This method will be called when Wagon when connection to @@ -77,7 +75,7 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionConnectionRefused( SessionEvent sessionEvent ); + void sessionConnectionRefused(SessionEvent sessionEvent); /** * This method will be called by Wagon when Wagon managed @@ -85,7 +83,7 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionLoggedIn( SessionEvent sessionEvent ); + void sessionLoggedIn(SessionEvent sessionEvent); /** * This method will be called by Wagon has logged off @@ -96,7 +94,7 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionLoggedOff( SessionEvent sessionEvent ); + void sessionLoggedOff(SessionEvent sessionEvent); /** * This method will be called by Wagon when an error occurred. @@ -106,13 +104,12 @@ public interface SessionListener * * @param sessionEvent the session event */ - void sessionError( SessionEvent sessionEvent ); + void sessionError(SessionEvent sessionEvent); /** * This method allows to send arbitrary debug messages. * * @param message the debug message */ - void debug( String message ); - -} \ No newline at end of file + void debug(String message); +} diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEvent.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEvent.java index ac3a71192..0d1c20769 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEvent.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; + +import java.io.File; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.resource.Resource; -import java.io.File; - /** * TransferEvent is used to notify TransferListeners about progress * in transfer of resources form/to the repository @@ -31,9 +30,7 @@ * @author Michal Maczka * */ -public class TransferEvent - extends WagonEvent -{ +public class TransferEvent extends WagonEvent { /** * A transfer was attempted, but has not yet commenced. @@ -80,21 +77,18 @@ public class TransferEvent private File localFile; - public TransferEvent( final Wagon wagon, final Resource resource, final int eventType, final int requestType ) - { - super( wagon ); + public TransferEvent(final Wagon wagon, final Resource resource, final int eventType, final int requestType) { + super(wagon); this.resource = resource; - setEventType( eventType ); - - setRequestType( requestType ); + setEventType(eventType); + setRequestType(requestType); } - public TransferEvent( final Wagon wagon, final Resource resource, final Exception exception, final int requestType ) - { - this( wagon, resource, TRANSFER_ERROR, requestType ); + public TransferEvent(final Wagon wagon, final Resource resource, final Exception exception, final int requestType) { + this(wagon, resource, TRANSFER_ERROR, requestType); this.exception = exception; } @@ -102,16 +96,14 @@ public TransferEvent( final Wagon wagon, final Resource resource, final Exceptio /** * @return Returns the resource. */ - public Resource getResource() - { + public Resource getResource() { return resource; } /** * @return Returns the exception. */ - public Exception getException() - { + public Exception getException() { return exception; } @@ -121,8 +113,7 @@ public Exception getException() * @return Returns the request type. The Request type is one of * TransferEvent.REQUEST_GET or TransferEvent.REQUEST_PUT */ - public int getRequestType() - { + public int getRequestType() { return requestType; } @@ -134,17 +125,14 @@ public int getRequestType() * TransferEvent.REQUEST_GET or TransferEvent.REQUEST_PUT. * @throws IllegalArgumentException when */ - public void setRequestType( final int requestType ) - { - switch ( requestType ) - { - + public void setRequestType(final int requestType) { + switch (requestType) { case REQUEST_PUT: case REQUEST_GET: break; - default : - throw new IllegalArgumentException( "Illegal request type: " + requestType ); + default: + throw new IllegalArgumentException("Illegal request type: " + requestType); } this.requestType = requestType; @@ -153,27 +141,23 @@ public void setRequestType( final int requestType ) /** * @return Returns the eventType. */ - public int getEventType() - { + public int getEventType() { return eventType; } /** * @param eventType The eventType to set. */ - public void setEventType( final int eventType ) - { - switch ( eventType ) - { - + public void setEventType(final int eventType) { + switch (eventType) { case TRANSFER_INITIATED: case TRANSFER_STARTED: case TRANSFER_COMPLETED: case TRANSFER_PROGRESS: case TRANSFER_ERROR: break; - default : - throw new IllegalArgumentException( "Illegal event type: " + eventType ); + default: + throw new IllegalArgumentException("Illegal event type: " + eventType); } this.eventType = eventType; @@ -182,137 +166,114 @@ public void setEventType( final int eventType ) /** * @param resource The resource to set. */ - public void setResource( final Resource resource ) - { + public void setResource(final Resource resource) { this.resource = resource; } /** * @return Returns the local file. */ - public File getLocalFile() - { + public File getLocalFile() { return localFile; } /** * @param localFile The local file to set. */ - public void setLocalFile( File localFile ) - { + public void setLocalFile(File localFile) { this.localFile = localFile; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( "TransferEvent[" ); + sb.append("TransferEvent["); - switch ( this.getRequestType() ) - { + switch (this.getRequestType()) { case REQUEST_GET: - sb.append( "GET" ); + sb.append("GET"); break; case REQUEST_PUT: - sb.append( "PUT" ); + sb.append("PUT"); break; default: - sb.append( this.getRequestType() ); + sb.append(this.getRequestType()); break; } - sb.append( "|" ); - switch ( this.getEventType() ) - { + sb.append("|"); + switch (this.getEventType()) { case TRANSFER_COMPLETED: - sb.append( "COMPLETED" ); + sb.append("COMPLETED"); break; case TRANSFER_ERROR: - sb.append( "ERROR" ); + sb.append("ERROR"); break; case TRANSFER_INITIATED: - sb.append( "INITIATED" ); + sb.append("INITIATED"); break; case TRANSFER_PROGRESS: - sb.append( "PROGRESS" ); + sb.append("PROGRESS"); break; case TRANSFER_STARTED: - sb.append( "STARTED" ); + sb.append("STARTED"); break; default: - sb.append( this.getEventType() ); + sb.append(this.getEventType()); break; } - sb.append( "|" ); + sb.append("|"); - sb.append( this.getWagon().getRepository() ).append( "|" ); - sb.append( this.getLocalFile() ).append( "|" ); - sb.append( this.getResource().inspect() ); - sb.append( "]" ); + sb.append(this.getWagon().getRepository()).append("|"); + sb.append(this.getLocalFile()).append("|"); + sb.append(this.getResource().inspect()); + sb.append("]"); return sb.toString(); } - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + eventType; - result = prime * result + ( ( exception == null ) ? 0 : exception.hashCode() ); - result = prime * result + ( ( localFile == null ) ? 0 : localFile.hashCode() ); + result = prime * result + ((exception == null) ? 0 : exception.hashCode()); + result = prime * result + ((localFile == null) ? 0 : localFile.hashCode()); result = prime * result + requestType; - result = prime * result + ( ( resource == null ) ? 0 : resource.hashCode() ); + result = prime * result + ((resource == null) ? 0 : resource.hashCode()); return result; } - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( ( obj == null ) || ( getClass() != obj.getClass() ) ) - { + if ((obj == null) || (getClass() != obj.getClass())) { return false; } final TransferEvent other = (TransferEvent) obj; - if ( eventType != other.eventType ) - { + if (eventType != other.eventType) { return false; } - if ( exception == null ) - { - if ( other.exception != null ) - { + if (exception == null) { + if (other.exception != null) { return false; } - } - else if ( !exception.getClass().equals( other.exception.getClass() ) ) - { + } else if (!exception.getClass().equals(other.exception.getClass())) { return false; } - if ( requestType != other.requestType ) - { + if (requestType != other.requestType) { return false; } - if ( resource == null ) - { - if ( other.resource != null ) - { + if (resource == null) { + if (other.resource != null) { return false; } - } - else if ( !resource.equals( other.resource ) ) - { + } else if (!resource.equals(other.resource)) { return false; - } - else if ( !source.equals( other.source ) ) - { + } else if (!source.equals(other.source)) { return false; } return true; } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEventSupport.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEventSupport.java index ff5531e05..1132d62de 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEventSupport.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferEventSupport.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import java.util.ArrayList; import java.util.List; @@ -29,8 +28,7 @@ * @author Michal Maczka * */ -public final class TransferEventSupport -{ +public final class TransferEventSupport { /** * registered listeners @@ -48,11 +46,9 @@ public final class TransferEventSupport * @see #removeTransferListener(org.apache.maven.wagon.events.TransferListener) * @see TransferListener */ - public synchronized void addTransferListener( final TransferListener listener ) - { - if ( listener != null ) - { - listeners.add( listener ); + public synchronized void addTransferListener(final TransferListener listener) { + if (listener != null) { + listeners.add(listener); } } @@ -67,9 +63,8 @@ public synchronized void addTransferListener( final TransferListener listener ) * @param listener the transfer listener * @see #addTransferListener(TransferListener) */ - public synchronized void removeTransferListener( final TransferListener listener ) - { - listeners.remove( listener ); + public synchronized void removeTransferListener(final TransferListener listener) { + listeners.remove(listener); } /** @@ -84,12 +79,10 @@ public synchronized void removeTransferListener( final TransferListener listener * @see org.apache.maven.wagon.events.TransferEvent * @see #addTransferListener(TransferListener) */ - public synchronized boolean hasTransferListener( final TransferListener listener ) - { - return listeners.contains( listener ); + public synchronized boolean hasTransferListener(final TransferListener listener) { + return listeners.contains(listener); } - /** * Dispatches the given TransferEvent * to all registered listeners (calls method {@link TransferListener#transferStarted(TransferEvent)} on all of @@ -97,11 +90,9 @@ public synchronized boolean hasTransferListener( final TransferListener listener * * @param transferEvent the TransferEvent which will be dispatched to listeners */ - public synchronized void fireTransferStarted( final TransferEvent transferEvent ) - { - for ( TransferListener listener : listeners ) - { - listener.transferStarted( transferEvent ); + public synchronized void fireTransferStarted(final TransferEvent transferEvent) { + for (TransferListener listener : listeners) { + listener.transferStarted(transferEvent); } } @@ -114,12 +105,9 @@ public synchronized void fireTransferStarted( final TransferEvent transferEvent * @param buffer the buffer containing the additional content * @param length the length of the content in the buffer */ - public synchronized void fireTransferProgress( final TransferEvent transferEvent, byte[] buffer, int length ) - { - for ( TransferListener listener : listeners ) - { - listener.transferProgress( transferEvent, buffer, length ); - + public synchronized void fireTransferProgress(final TransferEvent transferEvent, byte[] buffer, int length) { + for (TransferListener listener : listeners) { + listener.transferProgress(transferEvent, buffer, length); } } @@ -130,12 +118,9 @@ public synchronized void fireTransferProgress( final TransferEvent transferEvent * * @param transferEvent the TransferEvent which will be dispatched to listeners */ - public synchronized void fireTransferCompleted( final TransferEvent transferEvent ) - { - for ( TransferListener listener : listeners ) - { - listener.transferCompleted( transferEvent ); - + public synchronized void fireTransferCompleted(final TransferEvent transferEvent) { + for (TransferListener listener : listeners) { + listener.transferCompleted(transferEvent); } } @@ -147,12 +132,9 @@ public synchronized void fireTransferCompleted( final TransferEvent transferEven * * @param transferEvent the TransferEvent which will be dispatched to listeners */ - public synchronized void fireTransferError( final TransferEvent transferEvent ) - { - for ( TransferListener listener : listeners ) - { - listener.transferError( transferEvent ); - + public synchronized void fireTransferError(final TransferEvent transferEvent) { + for (TransferListener listener : listeners) { + listener.transferError(transferEvent); } } @@ -162,13 +144,10 @@ public synchronized void fireTransferError( final TransferEvent transferEvent ) * * @param message the debug message which will be dispatched to listeners */ - public synchronized void fireDebug( final String message ) - { - - for ( TransferListener listener : listeners ) - { - listener.debug( message ); + public synchronized void fireDebug(final String message) { + for (TransferListener listener : listeners) { + listener.debug(message); } } @@ -179,11 +158,9 @@ public synchronized void fireDebug( final String message ) * * @param transferEvent the TransferEvent which will be dispatched to listeners */ - public synchronized void fireTransferInitiated( final TransferEvent transferEvent ) - { - for ( TransferListener listener : listeners ) - { - listener.transferInitiated( transferEvent ); + public synchronized void fireTransferInitiated(final TransferEvent transferEvent) { + for (TransferListener listener : listeners) { + listener.transferInitiated(transferEvent); } } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferListener.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferListener.java index d254a47c7..21e77b5d4 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferListener.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/TransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,41 +16,39 @@ * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.wagon.events; /** * @author Michal Maczka * */ -public interface TransferListener -{ +public interface TransferListener { /** * @param transferEvent */ - void transferInitiated( TransferEvent transferEvent ); + void transferInitiated(TransferEvent transferEvent); /** * @param transferEvent */ - void transferStarted( TransferEvent transferEvent ); + void transferStarted(TransferEvent transferEvent); /** * @param transferEvent */ - void transferProgress( TransferEvent transferEvent, byte[] buffer, int length ); + void transferProgress(TransferEvent transferEvent, byte[] buffer, int length); /** * @param transferEvent */ - void transferCompleted( TransferEvent transferEvent ); + void transferCompleted(TransferEvent transferEvent); /** * @param transferEvent */ - void transferError( TransferEvent transferEvent ); + void transferError(TransferEvent transferEvent); /** * @param message */ - void debug( String message ); - + void debug(String message); } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/WagonEvent.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/WagonEvent.java index c23a4ea82..fac786a8b 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/WagonEvent.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/events/WagonEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import java.util.EventObject; @@ -29,9 +28,7 @@ * @author Michal Maczka * */ -public class WagonEvent - extends EventObject -{ +public class WagonEvent extends EventObject { /** * The time when event occurred */ @@ -40,9 +37,8 @@ public class WagonEvent /** * @param source The Wagon object on which the WagonEvent initially occurred */ - public WagonEvent( final Wagon source ) - { - super( source ); + public WagonEvent(final Wagon source) { + super(source); } /** @@ -50,8 +46,7 @@ public WagonEvent( final Wagon source ) * * @return The Wagon object on which the WagonEvent initially occurred */ - public Wagon getWagon() - { + public Wagon getWagon() { return (Wagon) getSource(); } @@ -60,8 +55,7 @@ public Wagon getWagon() * * @return Returns the timestamp. */ - public long getTimestamp() - { + public long getTimestamp() { return timestamp; } @@ -70,9 +64,7 @@ public long getTimestamp() * * @param timestamp The timestamp to set. */ - public void setTimestamp( final long timestamp ) - { + public void setTimestamp(final long timestamp) { this.timestamp = timestamp; } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/AbstractTransferListener.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/AbstractTransferListener.java index 5a550f6b4..14e148470 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/AbstractTransferListener.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/AbstractTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.observers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.observers; import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.events.TransferListener; @@ -28,36 +27,22 @@ * @author Michal Maczka * */ -public abstract class AbstractTransferListener - implements TransferListener -{ - public void transferInitiated( TransferEvent transferEvent ) - { - } +public abstract class AbstractTransferListener implements TransferListener { + public void transferInitiated(TransferEvent transferEvent) {} /** * @see org.apache.maven.wagon.events.TransferListener#transferStarted(org.apache.maven.wagon.events.TransferEvent) */ - public void transferStarted( TransferEvent transferEvent ) - { - } + public void transferStarted(TransferEvent transferEvent) {} /** * @see org.apache.maven.wagon.events.TransferListener#transferProgress(org.apache.maven.wagon.events.TransferEvent,byte[],int) */ - public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length ) - { - } + public void transferProgress(TransferEvent transferEvent, byte[] buffer, int length) {} - public void transferCompleted( TransferEvent transferEvent ) - { - } + public void transferCompleted(TransferEvent transferEvent) {} - public void transferError( TransferEvent transferEvent ) - { - } + public void transferError(TransferEvent transferEvent) {} - public void debug( String message ) - { - } + public void debug(String message) {} } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/ChecksumObserver.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/ChecksumObserver.java index 07f62ab1c..b5a0cb863 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/ChecksumObserver.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/ChecksumObserver.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.observers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,51 +16,44 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.events.TransferEvent; -import org.apache.maven.wagon.events.TransferListener; +package org.apache.maven.wagon.observers; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import org.apache.maven.wagon.events.TransferEvent; +import org.apache.maven.wagon.events.TransferListener; + /** * TransferListeners which computes MD5 checksum on the fly when files are transfered. * * @author Michal Maczka * */ -public class ChecksumObserver - implements TransferListener -{ +public class ChecksumObserver implements TransferListener { private MessageDigest digester = null; private String actualChecksum; - public ChecksumObserver() - throws NoSuchAlgorithmException - { - this( "MD5" ); + public ChecksumObserver() throws NoSuchAlgorithmException { + this("MD5"); } /** * @param algorithm One of the algorithms supported by JDK: MD5, MD2 or SHA-1 */ - public ChecksumObserver( String algorithm ) - throws NoSuchAlgorithmException - { - digester = MessageDigest.getInstance( algorithm ); + public ChecksumObserver(String algorithm) throws NoSuchAlgorithmException { + digester = MessageDigest.getInstance(algorithm); } - public void transferInitiated( TransferEvent transferEvent ) - { + public void transferInitiated(TransferEvent transferEvent) { // This space left intentionally blank } /** * @see org.apache.maven.wagon.events.TransferListener#transferStarted(org.apache.maven.wagon.events.TransferEvent) */ - public void transferStarted( TransferEvent transferEvent ) - { + public void transferStarted(TransferEvent transferEvent) { actualChecksum = null; digester.reset(); @@ -71,25 +62,21 @@ public void transferStarted( TransferEvent transferEvent ) /** * @see org.apache.maven.wagon.events.TransferListener#transferProgress(org.apache.maven.wagon.events.TransferEvent, byte[], int) */ - public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length ) - { - digester.update( buffer, 0, length ); + public void transferProgress(TransferEvent transferEvent, byte[] buffer, int length) { + digester.update(buffer, 0, length); } - public void transferCompleted( TransferEvent transferEvent ) - { - actualChecksum = encode( digester.digest() ); + public void transferCompleted(TransferEvent transferEvent) { + actualChecksum = encode(digester.digest()); } - public void transferError( TransferEvent transferEvent ) - { + public void transferError(TransferEvent transferEvent) { digester.reset(); actualChecksum = null; } - public void debug( String message ) - { + public void debug(String message) { // left intentionally blank } @@ -98,8 +85,7 @@ public void debug( String message ) * * @return */ - public String getActualChecksum() - { + public String getActualChecksum() { return actualChecksum; } @@ -109,34 +95,26 @@ public String getActualChecksum() * @param binaryData Array containing the digest * @return Encoded hex string, or null if encoding failed */ - @SuppressWarnings( "checkstyle:magicnumber" ) - protected String encode( byte[] binaryData ) - { - - if ( binaryData.length != 16 && binaryData.length != 20 ) - { + @SuppressWarnings("checkstyle:magicnumber") + protected String encode(byte[] binaryData) { + + if (binaryData.length != 16 && binaryData.length != 20) { int bitLength = binaryData.length * 8; - throw new IllegalArgumentException( "Unrecognised length for binary data: " + bitLength + " bits" ); + throw new IllegalArgumentException("Unrecognised length for binary data: " + bitLength + " bits"); } StringBuilder retValue = new StringBuilder(); - for ( byte b : binaryData ) - { - String t = Integer.toHexString( b & 0xff ); + for (byte b : binaryData) { + String t = Integer.toHexString(b & 0xff); - if ( t.length() == 1 ) - { - retValue.append( '0' ).append( t ); - } - else - { - retValue.append( t ); + if (t.length() == 1) { + retValue.append('0').append(t); + } else { + retValue.append(t); } } return retValue.toString().trim(); } - - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/Debug.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/Debug.java index fad22870f..30b69ece2 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/Debug.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/observers/Debug.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.observers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,185 +16,154 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.observers; + +import java.io.PrintStream; import org.apache.maven.wagon.events.SessionEvent; import org.apache.maven.wagon.events.SessionListener; import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.events.TransferListener; -import java.io.PrintStream; - /** * @author Michal Maczka * */ -public class Debug - implements SessionListener, TransferListener -{ +public class Debug implements SessionListener, TransferListener { private PrintStream out; long timestamp; long transfer; - public Debug() - { - this( System.out ); + public Debug() { + this(System.out); } - public Debug( PrintStream out ) - { + public Debug(PrintStream out) { this.out = out; } /** * @see SessionListener#sessionOpening(SessionEvent) */ - public void sessionOpening( final SessionEvent sessionEvent ) - { - //out.println( .getUrl() + " - Session: Opening "); + public void sessionOpening(final SessionEvent sessionEvent) { + // out.println( .getUrl() + " - Session: Opening "); } /** * @see SessionListener#sessionOpened(SessionEvent) */ - public void sessionOpened( final SessionEvent sessionEvent ) - { - out.println( sessionEvent.getWagon().getRepository().getUrl() + " - Session: Opened " ); + public void sessionOpened(final SessionEvent sessionEvent) { + out.println(sessionEvent.getWagon().getRepository().getUrl() + " - Session: Opened "); } /** * @see SessionListener#sessionDisconnecting(SessionEvent) */ - public void sessionDisconnecting( final SessionEvent sessionEvent ) - { - out.println( sessionEvent.getWagon().getRepository().getUrl() + " - Session: Disconnecting " ); - + public void sessionDisconnecting(final SessionEvent sessionEvent) { + out.println(sessionEvent.getWagon().getRepository().getUrl() + " - Session: Disconnecting "); } /** * @see SessionListener#sessionDisconnected(SessionEvent) */ - public void sessionDisconnected( final SessionEvent sessionEvent ) - { - out.println( sessionEvent.getWagon().getRepository().getUrl() + " - Session: Disconnected" ); + public void sessionDisconnected(final SessionEvent sessionEvent) { + out.println(sessionEvent.getWagon().getRepository().getUrl() + " - Session: Disconnected"); } /** * @see SessionListener#sessionConnectionRefused(SessionEvent) */ - public void sessionConnectionRefused( final SessionEvent sessionEvent ) - { - out.println( sessionEvent.getWagon().getRepository().getUrl() + " - Session: Connection refused" ); - + public void sessionConnectionRefused(final SessionEvent sessionEvent) { + out.println(sessionEvent.getWagon().getRepository().getUrl() + " - Session: Connection refused"); } /** * @see SessionListener#sessionLoggedIn(SessionEvent) */ - public void sessionLoggedIn( final SessionEvent sessionEvent ) - { - out.println( sessionEvent.getWagon().getRepository().getUrl() + " - Session: Logged in" ); - + public void sessionLoggedIn(final SessionEvent sessionEvent) { + out.println(sessionEvent.getWagon().getRepository().getUrl() + " - Session: Logged in"); } /** * @see SessionListener#sessionLoggedOff(SessionEvent) */ - public void sessionLoggedOff( final SessionEvent sessionEvent ) - { - out.println( sessionEvent.getWagon().getRepository().getUrl() + " - Session: Logged off" ); - + public void sessionLoggedOff(final SessionEvent sessionEvent) { + out.println(sessionEvent.getWagon().getRepository().getUrl() + " - Session: Logged off"); } /** * @see TransferListener#debug(String) */ - public void debug( final String message ) - { - out.println( message ); - + public void debug(final String message) { + out.println(message); } - public void transferInitiated( TransferEvent transferEvent ) - { + public void transferInitiated(TransferEvent transferEvent) { // This space left intentionally blank } /** * @see TransferListener#transferStarted(TransferEvent) */ - public void transferStarted( final TransferEvent transferEvent ) - { + public void transferStarted(final TransferEvent transferEvent) { timestamp = transferEvent.getTimestamp(); transfer = 0; - if ( transferEvent.getRequestType() == TransferEvent.REQUEST_GET ) - { + if (transferEvent.getRequestType() == TransferEvent.REQUEST_GET) { final String message = "Downloading: " + transferEvent.getResource().getName() + " from " - + transferEvent.getWagon().getRepository().getUrl(); + + transferEvent.getWagon().getRepository().getUrl(); - out.println( message ); - } - else - { + out.println(message); + } else { final String message = "Uploading: " + transferEvent.getResource().getName() + " to " - + transferEvent.getWagon().getRepository().getUrl(); - - out.println( message ); + + transferEvent.getWagon().getRepository().getUrl(); + out.println(message); } } /** * @see TransferListener#transferProgress(TransferEvent,byte[],int) */ - public void transferProgress( final TransferEvent transferEvent, byte[] buffer, int length ) - { + public void transferProgress(final TransferEvent transferEvent, byte[] buffer, int length) { - out.print( "#" ); - //String data = new String( transferEvent.getData(),0, transferEvent.getDataLength()); - //out.println(data); + out.print("#"); + // String data = new String( transferEvent.getData(),0, transferEvent.getDataLength()); + // out.println(data); transfer += length; } /** * @see TransferListener#transferCompleted(TransferEvent) */ - public void transferCompleted( final TransferEvent transferEvent ) - { - final double duration = (double) ( transferEvent.getTimestamp() - timestamp ) / 1000; + public void transferCompleted(final TransferEvent transferEvent) { + final double duration = (double) (transferEvent.getTimestamp() - timestamp) / 1000; out.println(); final String message = "Transfer finished. " + transfer + " bytes copied in " + duration + " seconds"; - out.println( message ); - + out.println(message); } /** * @see TransferListener#transferError(TransferEvent) */ - public void transferError( final TransferEvent transferEvent ) - { - out.println( " Transfer error: " + transferEvent.getException() ); - + public void transferError(final TransferEvent transferEvent) { + out.println(" Transfer error: " + transferEvent.getException()); } /** * @see SessionListener#sessionError(SessionEvent) */ - public void sessionError( final SessionEvent sessionEvent ) - { - out.println( " Session error: " + sessionEvent.getException() ); - + public void sessionError(final SessionEvent sessionEvent) { + out.println(" Session error: " + sessionEvent.getException()); } - public PrintStream getOut() - { + public PrintStream getOut() { return out; } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfo.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfo.java index 1b1085ab8..50d23892a 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfo.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.proxy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.WagonConstants; +package org.apache.maven.wagon.proxy; import java.io.Serializable; +import org.apache.maven.wagon.WagonConstants; + /** * Contains set of properties used by Wagon objects * while connection to the repository must go thru a proxy server. @@ -32,9 +31,7 @@ * @todo Propose standard types of proxy servers (e.g. SOCKSv4), * which can be shared between wagon api and providers */ -public class ProxyInfo - implements Serializable -{ +public class ProxyInfo implements Serializable { public static final String PROXY_SOCKS5 = "SOCKS_5"; public static final String PROXY_SOCKS4 = "SOCKS4"; @@ -86,8 +83,7 @@ public class ProxyInfo * * @return proxy server host name */ - public String getHost() - { + public String getHost() { return host; } @@ -96,8 +92,7 @@ public String getHost() * * @param host proxy server host name */ - public void setHost( final String host ) - { + public void setHost(final String host) { this.host = host; } @@ -106,8 +101,7 @@ public void setHost( final String host ) * * @return user's password at proxy host */ - public String getPassword() - { + public String getPassword() { return password; } @@ -116,8 +110,7 @@ public String getPassword() * * @param password password to use to login to a proxy server */ - public void setPassword( final String password ) - { + public void setPassword(final String password) { this.password = password; } @@ -126,8 +119,7 @@ public void setPassword( final String password ) * * @return proxy server port */ - public int getPort() - { + public int getPort() { return port; } @@ -136,8 +128,7 @@ public int getPort() * * @param port proxy server port */ - public void setPort( final int port ) - { + public void setPort(final int port) { this.port = port; } @@ -146,8 +137,7 @@ public void setPort( final int port ) * * @return username for the proxy server */ - public String getUserName() - { + public String getUserName() { return userName; } @@ -156,8 +146,7 @@ public String getUserName() * * @param userName username for the proxy server */ - public void setUserName( final String userName ) - { + public void setUserName(final String userName) { this.userName = userName; } @@ -166,53 +155,44 @@ public void setUserName( final String userName ) * * @return the type of the proxy server */ - public String getType() - { + public String getType() { return type; } /** * @param type the type of the proxy server like SOCKSv4 */ - public void setType( final String type ) - { + public void setType(final String type) { this.type = type; } - public String getNonProxyHosts() - { + public String getNonProxyHosts() { return nonProxyHosts; } - public void setNonProxyHosts( String nonProxyHosts ) - { + public void setNonProxyHosts(String nonProxyHosts) { this.nonProxyHosts = nonProxyHosts; } - public String getNtlmHost() - { + public String getNtlmHost() { return ntlmHost; } - public void setNtlmHost( String ntlmHost ) - { + public void setNtlmHost(String ntlmHost) { this.ntlmHost = ntlmHost; } - public void setNtlmDomain( String ntlmDomain ) - { + public void setNtlmDomain(String ntlmDomain) { this.ntlmDomain = ntlmDomain; } - public String getNtlmDomain() - { + public String getNtlmDomain() { return ntlmDomain; } @Override - public String toString() - { + public String toString() { return "ProxyInfo{" + "host='" + host + '\'' + ", userName='" + userName + '\'' + ", port=" + port + ", type='" - + type + '\'' + ", nonProxyHosts='" + nonProxyHosts + '\'' + '}'; + + type + '\'' + ", nonProxyHosts='" + nonProxyHosts + '\'' + '}'; } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfoProvider.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfoProvider.java index f63e251c6..608101c91 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfoProvider.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyInfoProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.proxy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.proxy; /** * Interface of an object, which provides the proxy settings. Typically, this is the artifact manager. */ -public interface ProxyInfoProvider -{ +public interface ProxyInfoProvider { /** * Returns the proxy settings for the given protocol. - * + * * @return Proxy settings or null, if no proxy is configured for this protocol. */ - ProxyInfo getProxyInfo( String protocol ); + ProxyInfo getProxyInfo(String protocol); } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyUtils.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyUtils.java index dbff0525e..7d0891f8d 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyUtils.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/proxy/ProxyUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.proxy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,49 +16,41 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.proxy; import java.util.StringTokenizer; /** * @author Thomas Champagne */ -public final class ProxyUtils -{ - private ProxyUtils() - { - } +public final class ProxyUtils { + private ProxyUtils() {} /** * Check if the specified host is in the list of non proxy hosts. - * + * * @param proxy the proxy info object contains set of properties. * @param targetHost the target hostname * @return true if the hostname is in the list of non proxy hosts, false otherwise. */ - public static boolean validateNonProxyHosts( ProxyInfo proxy, String targetHost ) - { - if ( targetHost == null ) - { + public static boolean validateNonProxyHosts(ProxyInfo proxy, String targetHost) { + if (targetHost == null) { targetHost = new String(); } - if ( proxy == null ) - { + if (proxy == null) { return false; } String nonProxyHosts = proxy.getNonProxyHosts(); - if ( nonProxyHosts == null ) - { + if (nonProxyHosts == null) { return false; } - StringTokenizer tokenizer = new StringTokenizer( nonProxyHosts, "|" ); + StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|"); - while ( tokenizer.hasMoreTokens() ) - { + while (tokenizer.hasMoreTokens()) { String pattern = tokenizer.nextToken(); - pattern = pattern.replaceAll( "\\.", "\\\\." ).replaceAll( "\\*", ".*" ); - if ( targetHost.matches( pattern ) ) - { + pattern = pattern.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"); + if (targetHost.matches(pattern)) { return true; } } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/Repository.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/Repository.java index 456115a1c..8111a13a2 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/Repository.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/Repository.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.repository; + +import java.io.Serializable; +import java.util.Properties; import org.apache.maven.wagon.PathUtils; import org.apache.maven.wagon.WagonConstants; import org.codehaus.plexus.util.StringUtils; -import java.io.Serializable; -import java.util.Properties; - /** * This class is an abstraction of the location from/to resources * can be transfered. @@ -34,9 +33,7 @@ * * @todo [BP] some things are specific to certain wagons (eg key stuff in authInfo, permissions) */ -public class Repository - implements Serializable -{ +public class Repository implements Serializable { private static final long serialVersionUID = 1312227676322136247L; private String id; @@ -69,35 +66,27 @@ public class Repository /** * @deprecated use {@link #Repository(String, String)} */ - public Repository() - { - - } + public Repository() {} - public Repository( String id, String url ) - { - if ( id == null ) - { - throw new NullPointerException( "id cannot be null" ); + public Repository(String id, String url) { + if (id == null) { + throw new NullPointerException("id cannot be null"); } - setId( id ); + setId(id); - if ( url == null ) - { - throw new NullPointerException( "url cannot be null" ); + if (url == null) { + throw new NullPointerException("url cannot be null"); } - setUrl( url ); + setUrl(url); } - public String getId() - { + public String getId() { return id; } - public void setId( String id ) - { + public void setId(String id) { this.id = id; } @@ -107,56 +96,48 @@ public void setId( String id ) * * @return the base directory */ - public String getBasedir() - { + public String getBasedir() { return basedir; } - public void setBasedir( String basedir ) - { + public void setBasedir(String basedir) { this.basedir = basedir; } - public void setName( String name ) - { + public void setName(String name) { this.name = name; } - public int getPort() - { + public int getPort() { return port; } - public void setPort( int port ) - { + public void setPort(int port) { this.port = port; } - public void setUrl( String url ) - { + public void setUrl(String url) { this.url = url; // TODO [BP]: refactor out the PathUtils URL stuff into a class like java.net.URL, so you only parse once // can't use URL class as is because it won't recognise our protocols, though perhaps we could attempt to // register handlers for scp, etc? - this.protocol = PathUtils.protocol( url ); + this.protocol = PathUtils.protocol(url); - this.host = PathUtils.host( url ); + this.host = PathUtils.host(url); - this.port = PathUtils.port( url ); + this.port = PathUtils.port(url); - this.basedir = PathUtils.basedir( url ); + this.basedir = PathUtils.basedir(url); - String username = PathUtils.user( url ); + String username = PathUtils.user(url); this.username = username; - if ( username != null ) - { - String password = PathUtils.password( url ); + if (username != null) { + String password = PathUtils.password(url); - if ( password != null ) - { + if (password != null) { this.password = password; username += ":" + password; @@ -164,43 +145,37 @@ public void setUrl( String url ) username += "@"; - int index = url.indexOf( username ); - this.url = url.substring( 0, index ) + url.substring( index + username.length() ); + int index = url.indexOf(username); + this.url = url.substring(0, index) + url.substring(index + username.length()); } } - public String getUrl() - { - if ( url != null ) - { + public String getUrl() { + if (url != null) { return url; } StringBuilder sb = new StringBuilder(); - sb.append( protocol ); + sb.append(protocol); - sb.append( "://" ); + sb.append("://"); - if ( isIPv6Address() ) - { + if (isIPv6Address()) { // If this is IPv6 then we have to surround it // with brackets '[' and ']' - sb.append( "[" ).append( getHost() ).append( "]" ); - } - else - { - sb.append( getHost() ); + sb.append("[").append(getHost()).append("]"); + } else { + sb.append(getHost()); } - if ( port != WagonConstants.UNKNOWN_PORT ) - { - sb.append( ":" ); + if (port != WagonConstants.UNKNOWN_PORT) { + sb.append(":"); - sb.append( port ); + sb.append(port); } - sb.append( basedir ); + sb.append(basedir); return sb.toString(); } @@ -210,121 +185,96 @@ public String getUrl() * * @return true if provide host part is of IPv6 format */ - private boolean isIPv6Address() - { - return getHost().contains( ":" ); + private boolean isIPv6Address() { + return getHost().contains(":"); } - public String getHost() - { - if ( host == null ) - { + public String getHost() { + if (host == null) { return "localhost"; } return host; } - public String getName() - { - if ( name == null ) - { + public String getName() { + if (name == null) { return getId(); } return name; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( "Repository[" ); + sb.append("Repository["); - if ( StringUtils.isNotEmpty( getName() ) ) - { - sb.append( getName() ).append( "|" ); + if (StringUtils.isNotEmpty(getName())) { + sb.append(getName()).append("|"); } - sb.append( getUrl() ); - sb.append( "]" ); + sb.append(getUrl()); + sb.append("]"); return sb.toString(); } - public String getProtocol() - { + public String getProtocol() { return protocol; } - public RepositoryPermissions getPermissions() - { + public RepositoryPermissions getPermissions() { return permissions; } - public void setPermissions( RepositoryPermissions permissions ) - { + public void setPermissions(RepositoryPermissions permissions) { this.permissions = permissions; } - public String getParameter( String key ) - { - return parameters.getProperty( key ); + public String getParameter(String key) { + return parameters.getProperty(key); } - public void setParameters( Properties parameters ) - { + public void setParameters(Properties parameters) { this.parameters = parameters; } - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( ( id == null ) ? 0 : id.hashCode() ); + result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } final Repository other = (Repository) obj; - if ( id == null ) - { - if ( other.id != null ) - { + if (id == null) { + if (other.id != null) { return false; } - } - else if ( !id.equals( other.id ) ) - { + } else if (!id.equals(other.id)) { return false; } return true; } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } - public void setProtocol( String protocol ) - { + public void setProtocol(String protocol) { this.protocol = protocol; } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/RepositoryPermissions.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/RepositoryPermissions.java index 37caa6f32..76673aa66 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/RepositoryPermissions.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/repository/RepositoryPermissions.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.repository; import java.io.Serializable; @@ -27,8 +26,7 @@ * @author Brett Porter * */ -public class RepositoryPermissions implements Serializable -{ +public class RepositoryPermissions implements Serializable { /** * Repository group name. */ @@ -50,8 +48,7 @@ public class RepositoryPermissions implements Serializable * * @return mode */ - public String getDirectoryMode() - { + public String getDirectoryMode() { return directoryMode; } @@ -60,8 +57,7 @@ public String getDirectoryMode() * * @param directoryMode repository directory mode for deployed artifacts */ - public void setDirectoryMode( final String directoryMode ) - { + public void setDirectoryMode(final String directoryMode) { this.directoryMode = directoryMode; } @@ -71,8 +67,7 @@ public void setDirectoryMode( final String directoryMode ) * * @return repository group name */ - public String getFileMode() - { + public String getFileMode() { return fileMode; } @@ -81,8 +76,7 @@ public String getFileMode() * * @param fileMode repository file mode for deployed artifacts */ - public void setFileMode( final String fileMode ) - { + public void setFileMode(final String fileMode) { this.fileMode = fileMode; } @@ -93,8 +87,7 @@ public void setFileMode( final String fileMode ) * * @return repository group name */ - public String getGroup() - { + public String getGroup() { return group; } @@ -103,9 +96,7 @@ public String getGroup() * * @param group repository group for deployed artifacts */ - public void setGroup( final String group ) - { + public void setGroup(final String group) { this.group = group; } - } diff --git a/wagon-provider-api/src/main/java/org/apache/maven/wagon/resource/Resource.java b/wagon-provider-api/src/main/java/org/apache/maven/wagon/resource/Resource.java index f57561921..2dfd083c7 100644 --- a/wagon-provider-api/src/main/java/org/apache/maven/wagon/resource/Resource.java +++ b/wagon-provider-api/src/main/java/org/apache/maven/wagon/resource/Resource.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.resource; import org.apache.maven.wagon.WagonConstants; @@ -31,32 +30,24 @@ * @author Michal Maczka * */ - -public class Resource -{ +public class Resource { private String name; private long lastModified; private long contentLength = WagonConstants.UNKNOWN_LENGTH; - public Resource() - { + public Resource() {} - } - - public Resource( String name ) - { + public Resource(String name) { this.name = name; } - public String getName() - { + public String getName() { return name; } - public void setName( String name ) - { + public void setName(String name) { this.name = name; } @@ -67,78 +58,61 @@ public void setName( String name ) * @return the date the resource was last modified, or WagonConstants.UNKNOWN_LENGTH * if not known. */ - public long getLastModified() - { + public long getLastModified() { return lastModified; } - public void setLastModified( long lastModified ) - { + public void setLastModified(long lastModified) { this.lastModified = lastModified; } - public long getContentLength() - { + public long getContentLength() { return contentLength; } - public void setContentLength( long contentLength ) - { + public void setContentLength(long contentLength) { this.contentLength = contentLength; } - public String toString() - { + public String toString() { return name; } - - public String inspect() - { + + public String inspect() { return name + "[len = " + contentLength + "; mod = " + lastModified + "]"; } - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (int) ( contentLength ^ ( contentLength >>> 32 ) ); - result = prime * result + (int) ( lastModified ^ ( lastModified >>> 32 ) ); - result = prime * result + ( ( name == null ) ? 0 : name.hashCode() ); + result = prime * result + (int) (contentLength ^ (contentLength >>> 32)); + result = prime * result + (int) (lastModified ^ (lastModified >>> 32)); + result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } final Resource other = (Resource) obj; - if ( contentLength != other.contentLength ) - { + if (contentLength != other.contentLength) { return false; } - if ( lastModified != other.lastModified ) - { + if (lastModified != other.lastModified) { return false; } - if ( name == null ) - { - if ( other.name != null ) - { + if (name == null) { + if (other.name != null) { return false; } - } - else if ( !name.equals( other.name ) ) - { + } else if (!name.equals(other.name)) { return false; } return true; diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/AbstractWagonTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/AbstractWagonTest.java index 81b07dbdd..5ae69460d 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/AbstractWagonTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/AbstractWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import junit.framework.TestCase; import org.apache.maven.wagon.authentication.AuthenticationException; @@ -38,46 +43,25 @@ import static org.easymock.EasyMock.*; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - /** * @author Michal Maczka */ -public class AbstractWagonTest - extends TestCase -{ - private static class TestWagon - extends AbstractWagon - { - protected void closeConnection() - throws ConnectionException - { - } +public class AbstractWagonTest extends TestCase { + private static class TestWagon extends AbstractWagon { + protected void closeConnection() throws ConnectionException {} - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { - } + protected void openConnectionInternal() throws ConnectionException, AuthenticationException {} - public void get( String resourceName, File destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - } + public void get(String resourceName, File destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {} - public boolean getIfNewer( String resourceName, File destination, long timestamp ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public boolean getIfNewer(String resourceName, File destination, long timestamp) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { return false; } - public void put( File source, String destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - } + public void put(File source, String destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {} } private String basedir; @@ -94,140 +78,122 @@ public void put( File source, String destination ) private TransferListener transferListener = null; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - basedir = System.getProperty( "basedir" ); + basedir = System.getProperty("basedir"); - destination = new File( basedir, "target/folder/subfolder" ); + destination = new File(basedir, "target/folder/subfolder"); - source = new File( basedir, "pom.xml" ); + source = new File(basedir, "pom.xml"); wagon = new WagonMock(); - sessionListener = createMock( SessionListener.class ); - - wagon.addSessionListener( sessionListener ); + sessionListener = createMock(SessionListener.class); - transferListener = createMock( TransferListener.class ); + wagon.addSessionListener(sessionListener); - wagon.addTransferListener( transferListener ); + transferListener = createMock(TransferListener.class); + wagon.addTransferListener(transferListener); } public void testCalculationOfTransferBufferSize() { // 1 KiB -> Default buffer size (4 KiB) - assertEquals( 4096, wagon.getBufferCapacityForTransfer(1024L ) ); + assertEquals(4096, wagon.getBufferCapacityForTransfer(1024L)); // 1 MiB -> Twice the default buffer size (8 KiB) - assertEquals( 4096 * 2, wagon.getBufferCapacityForTransfer(1024L * 1024 ) ); + assertEquals(4096 * 2, wagon.getBufferCapacityForTransfer(1024L * 1024)); // 100 MiB -> Maximum buffer size (512 KiB) - assertEquals( 4096 * 128, wagon.getBufferCapacityForTransfer(1024L * 1024 * 100 ) ); + assertEquals(4096 * 128, wagon.getBufferCapacityForTransfer(1024L * 1024 * 100)); // 1 GiB -> Maximum buffer size (512 KiB) - assertEquals( 4096 * 128, wagon.getBufferCapacityForTransfer(1024L * 1024 * 1024 ) ); + assertEquals(4096 * 128, wagon.getBufferCapacityForTransfer(1024L * 1024 * 1024)); // 100 GiB -> Maximum buffer size (512 KiB) - assertEquals( 4096 * 128, wagon.getBufferCapacityForTransfer(1024L * 1024 * 1024 * 100 ) ); + assertEquals(4096 * 128, wagon.getBufferCapacityForTransfer(1024L * 1024 * 1024 * 100)); } - public void testSessionListenerRegistration() - { - assertTrue( wagon.hasSessionListener( sessionListener ) ); + public void testSessionListenerRegistration() { + assertTrue(wagon.hasSessionListener(sessionListener)); - wagon.removeSessionListener( sessionListener ); + wagon.removeSessionListener(sessionListener); - assertFalse( wagon.hasSessionListener( sessionListener ) ); + assertFalse(wagon.hasSessionListener(sessionListener)); } - public void testTransferListenerRegistration() - { - assertTrue( wagon.hasTransferListener( transferListener ) ); + public void testTransferListenerRegistration() { + assertTrue(wagon.hasTransferListener(transferListener)); - wagon.removeTransferListener( transferListener ); + wagon.removeTransferListener(transferListener); - assertFalse( wagon.hasTransferListener( transferListener ) ); + assertFalse(wagon.hasTransferListener(transferListener)); } - public void testNoProxyConfiguration() - throws ConnectionException, AuthenticationException - { + public void testNoProxyConfiguration() throws ConnectionException, AuthenticationException { Repository repository = new Repository(); - wagon.connect( repository ); - assertNull( wagon.getProxyInfo() ); - assertNull( wagon.getProxyInfo( "http", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "dav", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "scp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "ftp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "http", "localhost" ) ); + wagon.connect(repository); + assertNull(wagon.getProxyInfo()); + assertNull(wagon.getProxyInfo("http", "www.example.com")); + assertNull(wagon.getProxyInfo("dav", "www.example.com")); + assertNull(wagon.getProxyInfo("scp", "www.example.com")); + assertNull(wagon.getProxyInfo("ftp", "www.example.com")); + assertNull(wagon.getProxyInfo("http", "localhost")); } - public void testNullProxyConfiguration() - throws ConnectionException, AuthenticationException - { + public void testNullProxyConfiguration() throws ConnectionException, AuthenticationException { Repository repository = new Repository(); - wagon.connect( repository, (ProxyInfo) null ); - assertNull( wagon.getProxyInfo() ); - assertNull( wagon.getProxyInfo( "http", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "dav", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "scp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "ftp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "http", "localhost" ) ); - - wagon.connect( repository ); - assertNull( wagon.getProxyInfo() ); - assertNull( wagon.getProxyInfo( "http", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "dav", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "scp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "ftp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "http", "localhost" ) ); - - wagon.connect( repository, new AuthenticationInfo() ); - assertNull( wagon.getProxyInfo() ); - assertNull( wagon.getProxyInfo( "http", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "dav", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "scp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "ftp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "http", "localhost" ) ); + wagon.connect(repository, (ProxyInfo) null); + assertNull(wagon.getProxyInfo()); + assertNull(wagon.getProxyInfo("http", "www.example.com")); + assertNull(wagon.getProxyInfo("dav", "www.example.com")); + assertNull(wagon.getProxyInfo("scp", "www.example.com")); + assertNull(wagon.getProxyInfo("ftp", "www.example.com")); + assertNull(wagon.getProxyInfo("http", "localhost")); + + wagon.connect(repository); + assertNull(wagon.getProxyInfo()); + assertNull(wagon.getProxyInfo("http", "www.example.com")); + assertNull(wagon.getProxyInfo("dav", "www.example.com")); + assertNull(wagon.getProxyInfo("scp", "www.example.com")); + assertNull(wagon.getProxyInfo("ftp", "www.example.com")); + assertNull(wagon.getProxyInfo("http", "localhost")); + + wagon.connect(repository, new AuthenticationInfo()); + assertNull(wagon.getProxyInfo()); + assertNull(wagon.getProxyInfo("http", "www.example.com")); + assertNull(wagon.getProxyInfo("dav", "www.example.com")); + assertNull(wagon.getProxyInfo("scp", "www.example.com")); + assertNull(wagon.getProxyInfo("ftp", "www.example.com")); + assertNull(wagon.getProxyInfo("http", "localhost")); } - public void testLegacyProxyConfiguration() - throws ConnectionException, AuthenticationException - { + public void testLegacyProxyConfiguration() throws ConnectionException, AuthenticationException { ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setType( "http" ); + proxyInfo.setType("http"); Repository repository = new Repository(); - wagon.connect( repository, proxyInfo ); - assertEquals( proxyInfo, wagon.getProxyInfo() ); - assertEquals( proxyInfo, wagon.getProxyInfo( "http", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "dav", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "scp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "ftp", "www.example.com" ) ); + wagon.connect(repository, proxyInfo); + assertEquals(proxyInfo, wagon.getProxyInfo()); + assertEquals(proxyInfo, wagon.getProxyInfo("http", "www.example.com")); + assertNull(wagon.getProxyInfo("dav", "www.example.com")); + assertNull(wagon.getProxyInfo("scp", "www.example.com")); + assertNull(wagon.getProxyInfo("ftp", "www.example.com")); } - public void testProxyConfiguration() - throws ConnectionException, AuthenticationException - { + public void testProxyConfiguration() throws ConnectionException, AuthenticationException { final ProxyInfo httpProxyInfo = new ProxyInfo(); - httpProxyInfo.setType( "http" ); + httpProxyInfo.setType("http"); final ProxyInfo socksProxyInfo = new ProxyInfo(); - socksProxyInfo.setType( "http" ); - - ProxyInfoProvider proxyInfoProvider = new ProxyInfoProvider() - { - public ProxyInfo getProxyInfo( String protocol ) - { - if ( "http".equals( protocol ) || "dav".equals( protocol ) ) - { + socksProxyInfo.setType("http"); + + ProxyInfoProvider proxyInfoProvider = new ProxyInfoProvider() { + public ProxyInfo getProxyInfo(String protocol) { + if ("http".equals(protocol) || "dav".equals(protocol)) { return httpProxyInfo; - } - else if ( "scp".equals( protocol ) ) - { + } else if ("scp".equals(protocol)) { return socksProxyInfo; } return null; @@ -235,359 +201,300 @@ else if ( "scp".equals( protocol ) ) }; Repository repository = new Repository(); - wagon.connect( repository, proxyInfoProvider ); - assertNull( wagon.getProxyInfo() ); - assertEquals( httpProxyInfo, wagon.getProxyInfo( "http", "www.example.com" ) ); - assertEquals( httpProxyInfo, wagon.getProxyInfo( "dav", "www.example.com" ) ); - assertEquals( socksProxyInfo, wagon.getProxyInfo( "scp", "www.example.com" ) ); - assertNull( wagon.getProxyInfo( "ftp", "www.example.com" ) ); + wagon.connect(repository, proxyInfoProvider); + assertNull(wagon.getProxyInfo()); + assertEquals(httpProxyInfo, wagon.getProxyInfo("http", "www.example.com")); + assertEquals(httpProxyInfo, wagon.getProxyInfo("dav", "www.example.com")); + assertEquals(socksProxyInfo, wagon.getProxyInfo("scp", "www.example.com")); + assertNull(wagon.getProxyInfo("ftp", "www.example.com")); } - public void testSessionOpenEvents() - throws Exception - { + public void testSessionOpenEvents() throws Exception { Repository repository = new Repository(); - sessionListener.sessionOpening( anyObject( SessionEvent.class ) ); - sessionListener.sessionOpened( anyObject( SessionEvent.class ) ); - replay( sessionListener ); + sessionListener.sessionOpening(anyObject(SessionEvent.class)); + sessionListener.sessionOpened(anyObject(SessionEvent.class)); + replay(sessionListener); - wagon.connect( repository ); + wagon.connect(repository); - verify( sessionListener ); + verify(sessionListener); - assertEquals( repository, wagon.getRepository() ); + assertEquals(repository, wagon.getRepository()); } - public void testSessionConnectionRefusedEventConnectionException() - throws Exception - { - final WagonException exception = new ConnectionException( "" ); + public void testSessionConnectionRefusedEventConnectionException() throws Exception { + final WagonException exception = new ConnectionException(""); - try - { - runTestSessionConnectionRefusedEvent( exception ); + try { + runTestSessionConnectionRefusedEvent(exception); fail(); - } - catch ( ConnectionException e ) - { - assertTrue( true ); + } catch (ConnectionException e) { + assertTrue(true); } } - public void testSessionConnectionRefusedEventAuthenticationException() - throws Exception - { - final WagonException exception = new AuthenticationException( "" ); + public void testSessionConnectionRefusedEventAuthenticationException() throws Exception { + final WagonException exception = new AuthenticationException(""); - try - { - runTestSessionConnectionRefusedEvent( exception ); + try { + runTestSessionConnectionRefusedEvent(exception); fail(); - } - catch ( AuthenticationException e ) - { - assertTrue( true ); + } catch (AuthenticationException e) { + assertTrue(true); } } - private void runTestSessionConnectionRefusedEvent( final WagonException exception ) - throws ConnectionException, AuthenticationException - { + private void runTestSessionConnectionRefusedEvent(final WagonException exception) + throws ConnectionException, AuthenticationException { Repository repository = new Repository(); - sessionListener.sessionOpening( anyObject( SessionEvent.class ) ); - sessionListener.sessionConnectionRefused( anyObject( SessionEvent.class ) ); - replay( sessionListener ); - - Wagon wagon = new TestWagon() - { - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { - if ( exception instanceof ConnectionException ) - { + sessionListener.sessionOpening(anyObject(SessionEvent.class)); + sessionListener.sessionConnectionRefused(anyObject(SessionEvent.class)); + replay(sessionListener); + + Wagon wagon = new TestWagon() { + protected void openConnectionInternal() throws ConnectionException, AuthenticationException { + if (exception instanceof ConnectionException) { throw (ConnectionException) exception; } - if ( exception instanceof AuthenticationException ) - { + if (exception instanceof AuthenticationException) { throw (AuthenticationException) exception; } } }; - wagon.addSessionListener( sessionListener ); + wagon.addSessionListener(sessionListener); - try - { - wagon.connect( repository ); + try { + wagon.connect(repository); fail(); - } - finally - { - verify( sessionListener ); + } finally { + verify(sessionListener); - assertEquals( repository, wagon.getRepository() ); + assertEquals(repository, wagon.getRepository()); } } - public void testSessionCloseEvents() - throws Exception - { - sessionListener.sessionDisconnecting( anyObject( SessionEvent.class ) ); - sessionListener.sessionDisconnected( anyObject( SessionEvent.class ) ); - replay( sessionListener ); + public void testSessionCloseEvents() throws Exception { + sessionListener.sessionDisconnecting(anyObject(SessionEvent.class)); + sessionListener.sessionDisconnected(anyObject(SessionEvent.class)); + replay(sessionListener); wagon.disconnect(); - verify( sessionListener ); + verify(sessionListener); } - public void testSessionCloseRefusedEventConnectionException() - throws Exception - { + public void testSessionCloseRefusedEventConnectionException() throws Exception { Repository repository = new Repository(); - sessionListener.sessionDisconnecting( anyObject( SessionEvent.class ) ); - sessionListener.sessionError( anyObject( SessionEvent.class ) ); - replay( sessionListener ); + sessionListener.sessionDisconnecting(anyObject(SessionEvent.class)); + sessionListener.sessionError(anyObject(SessionEvent.class)); + replay(sessionListener); - Wagon wagon = new TestWagon() - { - protected void closeConnection() - throws ConnectionException - { - throw new ConnectionException( "" ); + Wagon wagon = new TestWagon() { + protected void closeConnection() throws ConnectionException { + throw new ConnectionException(""); } }; - wagon.addSessionListener( sessionListener ); + wagon.addSessionListener(sessionListener); - try - { + try { wagon.disconnect(); fail(); - } - catch ( ConnectionException e ) - { - assertTrue( true ); - } - finally - { - verify( sessionListener ); + } catch (ConnectionException e) { + assertTrue(true); + } finally { + verify(sessionListener); } } - public void testGetTransferEvents() - throws Exception - { - transferListener.debug( "fetch debug message" ); - transferListener.transferInitiated( anyObject( TransferEvent.class ) ); - transferListener.transferStarted( anyObject( TransferEvent.class ) ); - transferListener.debug( anyString() ); + public void testGetTransferEvents() throws Exception { + transferListener.debug("fetch debug message"); + transferListener.transferInitiated(anyObject(TransferEvent.class)); + transferListener.transferStarted(anyObject(TransferEvent.class)); + transferListener.debug(anyString()); expectLastCall().anyTimes(); - transferListener.transferProgress( anyObject( TransferEvent.class ), anyObject( byte[].class ), anyInt() ); - expectLastCall().times( 5 ); - transferListener.transferCompleted( anyObject( TransferEvent.class ) ); - replay( transferListener ); + transferListener.transferProgress(anyObject(TransferEvent.class), anyObject(byte[].class), anyInt()); + expectLastCall().times(5); + transferListener.transferCompleted(anyObject(TransferEvent.class)); + replay(transferListener); - wagon.fireTransferDebug( "fetch debug message" ); + wagon.fireTransferDebug("fetch debug message"); Repository repository = new Repository(); - wagon.connect( repository ); + wagon.connect(repository); - wagon.get( artifact, destination ); + wagon.get(artifact, destination); - verify( transferListener ); + verify(transferListener); } - public void testGetError() - throws Exception - { - transferListener.transferInitiated( anyObject( TransferEvent.class ) ); - transferListener.transferStarted( anyObject( TransferEvent.class ) ); - transferListener.debug( anyString() ); + public void testGetError() throws Exception { + transferListener.transferInitiated(anyObject(TransferEvent.class)); + transferListener.transferStarted(anyObject(TransferEvent.class)); + transferListener.debug(anyString()); expectLastCall().anyTimes(); - transferListener.transferError( anyObject( TransferEvent.class ) ); - replay( transferListener ); + transferListener.transferError(anyObject(TransferEvent.class)); + replay(transferListener); - try - { + try { Repository repository = new Repository(); - WagonMock wagon = new WagonMock( true ); + WagonMock wagon = new WagonMock(true); - wagon.addTransferListener( transferListener ); + wagon.addTransferListener(transferListener); - wagon.connect( repository ); + wagon.connect(repository); - wagon.get( artifact, destination ); + wagon.get(artifact, destination); - fail( "Transfer error was expected during deploy" ); - } - catch ( TransferFailedException expected ) - { - assertTrue( true ); + fail("Transfer error was expected during deploy"); + } catch (TransferFailedException expected) { + assertTrue(true); } - verify( transferListener ); + verify(transferListener); } public void testPutTransferEvents() - throws ConnectionException, AuthenticationException, ResourceDoesNotExistException, TransferFailedException, - AuthorizationException - { - transferListener.debug( "deploy debug message" ); - transferListener.transferInitiated( anyObject( TransferEvent.class ) ); - transferListener.transferStarted( anyObject( TransferEvent.class ) ); - transferListener.transferProgress( anyObject( TransferEvent.class ), anyObject( byte[].class ), anyInt() ); - transferListener.transferCompleted( anyObject( TransferEvent.class ) ); - replay( transferListener ); - - wagon.fireTransferDebug( "deploy debug message" ); + throws ConnectionException, AuthenticationException, ResourceDoesNotExistException, TransferFailedException, + AuthorizationException { + transferListener.debug("deploy debug message"); + transferListener.transferInitiated(anyObject(TransferEvent.class)); + transferListener.transferStarted(anyObject(TransferEvent.class)); + transferListener.transferProgress(anyObject(TransferEvent.class), anyObject(byte[].class), anyInt()); + transferListener.transferCompleted(anyObject(TransferEvent.class)); + replay(transferListener); + + wagon.fireTransferDebug("deploy debug message"); Repository repository = new Repository(); - wagon.connect( repository ); + wagon.connect(repository); - wagon.put( source, artifact ); + wagon.put(source, artifact); - verify( transferListener ); + verify(transferListener); } - public void testStreamShutdown() - { - IOUtil.close( (InputStream) null ); + public void testStreamShutdown() { + IOUtil.close((InputStream) null); - IOUtil.close( (OutputStream) null ); + IOUtil.close((OutputStream) null); InputStreamMock inputStream = new InputStreamMock(); - assertFalse( inputStream.isClosed() ); + assertFalse(inputStream.isClosed()); - IOUtil.close( inputStream ); + IOUtil.close(inputStream); - assertTrue( inputStream.isClosed() ); + assertTrue(inputStream.isClosed()); OutputStreamMock outputStream = new OutputStreamMock(); - assertFalse( outputStream.isClosed() ); + assertFalse(outputStream.isClosed()); - IOUtil.close( outputStream ); + IOUtil.close(outputStream); - assertTrue( outputStream.isClosed() ); + assertTrue(outputStream.isClosed()); } - public void testRepositoryPermissionsOverride() - throws ConnectionException, AuthenticationException - { + public void testRepositoryPermissionsOverride() throws ConnectionException, AuthenticationException { Repository repository = new Repository(); RepositoryPermissions original = new RepositoryPermissions(); - original.setFileMode( "664" ); - repository.setPermissions( original ); + original.setFileMode("664"); + repository.setPermissions(original); RepositoryPermissions override = new RepositoryPermissions(); - override.setFileMode( "644" ); - wagon.setPermissionsOverride( override ); + override.setFileMode("644"); + wagon.setPermissionsOverride(override); - wagon.connect( repository ); + wagon.connect(repository); - assertEquals( override, repository.getPermissions() ); - assertEquals( "644", repository.getPermissions().getFileMode() ); + assertEquals(override, repository.getPermissions()); + assertEquals("644", repository.getPermissions().getFileMode()); } - public void testRepositoryUserName() - throws ConnectionException, AuthenticationException - { - Repository repository = new Repository( "id", "http://bporter:password@www.example.com/path/to/resource" ); + public void testRepositoryUserName() throws ConnectionException, AuthenticationException { + Repository repository = new Repository("id", "http://bporter:password@www.example.com/path/to/resource"); AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setUserName( "brett" ); - authenticationInfo.setPassword( "pass" ); - wagon.connect( repository, authenticationInfo ); + authenticationInfo.setUserName("brett"); + authenticationInfo.setPassword("pass"); + wagon.connect(repository, authenticationInfo); - assertEquals( authenticationInfo, wagon.getAuthenticationInfo() ); - assertEquals( "brett", authenticationInfo.getUserName() ); - assertEquals( "pass", authenticationInfo.getPassword() ); + assertEquals(authenticationInfo, wagon.getAuthenticationInfo()); + assertEquals("brett", authenticationInfo.getUserName()); + assertEquals("pass", authenticationInfo.getPassword()); } - public void testRepositoryUserNameNotGivenInCredentials() - throws ConnectionException, AuthenticationException - { - Repository repository = new Repository( "id", "http://bporter:password@www.example.com/path/to/resource" ); + public void testRepositoryUserNameNotGivenInCredentials() throws ConnectionException, AuthenticationException { + Repository repository = new Repository("id", "http://bporter:password@www.example.com/path/to/resource"); AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - wagon.connect( repository, authenticationInfo ); + wagon.connect(repository, authenticationInfo); - assertEquals( authenticationInfo, wagon.getAuthenticationInfo() ); - assertEquals( "bporter", authenticationInfo.getUserName() ); - assertEquals( "password", authenticationInfo.getPassword() ); + assertEquals(authenticationInfo, wagon.getAuthenticationInfo()); + assertEquals("bporter", authenticationInfo.getUserName()); + assertEquals("password", authenticationInfo.getPassword()); } - public void testConnectNullRepository() - throws ConnectionException, AuthenticationException - { - try - { - wagon.connect( null ); + public void testConnectNullRepository() throws ConnectionException, AuthenticationException { + try { + wagon.connect(null); fail(); - } - catch ( NullPointerException e ) - { - assertTrue( true ); + } catch (NullPointerException e) { + assertTrue(true); } } - public void testPostProcessListeners() - throws TransferFailedException, IOException - { - File tempFile = File.createTempFile( "wagon", "tmp" ); + public void testPostProcessListeners() throws TransferFailedException, IOException { + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); String content = "content"; - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); - Resource resource = new Resource( "resource" ); + Resource resource = new Resource("resource"); - transferListener.transferInitiated( anyObject( TransferEvent.class ) ); - transferListener.transferStarted( anyObject( TransferEvent.class ) ); + transferListener.transferInitiated(anyObject(TransferEvent.class)); + transferListener.transferStarted(anyObject(TransferEvent.class)); TransferEvent event = - new TransferEvent( wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_PUT ); - event.setLocalFile( tempFile ); - transferListener.transferProgress( eq( event ), anyObject( byte[].class ), eq( content.length() ) ); + new TransferEvent(wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_PUT); + event.setLocalFile(tempFile); + transferListener.transferProgress(eq(event), anyObject(byte[].class), eq(content.length())); ProgressAnswer answer = new ProgressAnswer(); - expectLastCall().andAnswer( answer ); - transferListener.transferCompleted( anyObject( TransferEvent.class ) ); - replay( transferListener ); + expectLastCall().andAnswer(answer); + transferListener.transferCompleted(anyObject(TransferEvent.class)); + replay(transferListener); - wagon.postProcessListeners( resource, tempFile, TransferEvent.REQUEST_PUT ); + wagon.postProcessListeners(resource, tempFile, TransferEvent.REQUEST_PUT); - assertEquals( content.length(), answer.getSize() ); - assertEquals( new String( content.getBytes() ), new String( answer.getBytes() ) ); + assertEquals(content.length(), answer.getSize()); + assertEquals(new String(content.getBytes()), new String(answer.getBytes())); tempFile.delete(); } - static final class ProgressAnswer implements IAnswer - { + static final class ProgressAnswer implements IAnswer { private ByteArrayOutputStream baos = new ByteArrayOutputStream(); private int size; - - public Object answer() throws Throwable - { + + public Object answer() throws Throwable { byte[] buffer = (byte[]) getCurrentArguments()[1]; int length = (Integer) getCurrentArguments()[2]; - baos.write( buffer, 0, length ); + baos.write(buffer, 0, length); size += length; return null; } - public int getSize() - { + public int getSize() { return size; } - public byte[] getBytes() - { + public byte[] getBytes() { return baos.toByteArray(); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/CannotConnectExceptionTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/CannotConnectExceptionTest.java index cb798c827..2f31141e2 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/CannotConnectExceptionTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/CannotConnectExceptionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import junit.framework.TestCase; @@ -25,19 +24,16 @@ * @author Jason van Zyl * */ -public class CannotConnectExceptionTest - extends TestCase -{ - public void testCannotConnectExceptionTest() - { - ConnectionException ae = new ConnectionException( "message" ); +public class CannotConnectExceptionTest extends TestCase { + public void testCannotConnectExceptionTest() { + ConnectionException ae = new ConnectionException("message"); - assertEquals( "message", ae.getMessage() ); + assertEquals("message", ae.getMessage()); - ae = new ConnectionException( "full-message", new Throwable( "cause" ) ); + ae = new ConnectionException("full-message", new Throwable("cause")); - assertEquals( "full-message", ae.getMessage() ); + assertEquals("full-message", ae.getMessage()); - assertEquals( "cause", ae.getCause().getMessage() ); + assertEquals("cause", ae.getCause().getMessage()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/InputStreamMock.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/InputStreamMock.java index c624764e5..d1f2384c0 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/InputStreamMock.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/InputStreamMock.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,53 +16,45 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.IOException; import java.io.InputStream; - /** * @author Michal Maczka * */ -public class InputStreamMock - extends InputStream -{ +public class InputStreamMock extends InputStream { private boolean closed = false; boolean forcedError = false; - public void close() - { + public void close() { closed = true; } /** * @return Returns the closed. */ - public boolean isClosed() - { + public boolean isClosed() { return closed; } /** * @return Returns the forcedError. */ - public boolean isForcedError() - { + public boolean isForcedError() { return forcedError; } /** * @see java.io.InputStream#read() */ - public int read() - throws IOException - { - if ( forcedError ) - { - throw new IOException( "Mock exception" ); + public int read() throws IOException { + if (forcedError) { + throw new IOException("Mock exception"); } return 0; } @@ -72,9 +62,7 @@ public int read() /** * @param forcedError The forcedError to set. */ - public void setForcedError( final boolean forcedError ) - { + public void setForcedError(final boolean forcedError) { this.forcedError = forcedError; } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/LazyFileOutputStreamTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/LazyFileOutputStreamTest.java index 006a5625e..d630f0355 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/LazyFileOutputStreamTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/LazyFileOutputStreamTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,45 +16,40 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; + +import java.io.File; import junit.framework.TestCase; import org.codehaus.plexus.util.FileUtils; -import java.io.File; - /** * @author Michal Maczka * */ -public class LazyFileOutputStreamTest - extends TestCase -{ +public class LazyFileOutputStreamTest extends TestCase { - public void testFileCreation() - throws Exception - { - File file = File.createTempFile( getName(), null ); + public void testFileCreation() throws Exception { + File file = File.createTempFile(getName(), null); file.delete(); - assertFalse( file.exists() ); + assertFalse(file.exists()); - LazyFileOutputStream stream = new LazyFileOutputStream( file ); + LazyFileOutputStream stream = new LazyFileOutputStream(file); - assertFalse( file.exists() ); + assertFalse(file.exists()); String expected = "michal"; - stream.write( expected.getBytes() ); + stream.write(expected.getBytes()); stream.close(); - assertTrue( file.exists() ); + assertTrue(file.exists()); - String actual = FileUtils.fileRead( file ); - - assertEquals( expected, actual ); + String actual = FileUtils.fileRead(file); + assertEquals(expected, actual); } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/NotAuthorizedExceptionTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/NotAuthorizedExceptionTest.java index c86e53893..99b173135 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/NotAuthorizedExceptionTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/NotAuthorizedExceptionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import junit.framework.TestCase; import org.apache.maven.wagon.authorization.AuthorizationException; @@ -26,19 +25,16 @@ * @author Jason van Zyl * */ -public class NotAuthorizedExceptionTest - extends TestCase -{ - public void testNotAuthorizedExceptionTest() - { - AuthorizationException ae = new AuthorizationException( "message" ); +public class NotAuthorizedExceptionTest extends TestCase { + public void testNotAuthorizedExceptionTest() { + AuthorizationException ae = new AuthorizationException("message"); - assertEquals( "message", ae.getMessage() ); + assertEquals("message", ae.getMessage()); - ae = new AuthorizationException( "full-message", new Throwable( "cause" ) ); + ae = new AuthorizationException("full-message", new Throwable("cause")); - assertEquals( "full-message", ae.getMessage() ); + assertEquals("full-message", ae.getMessage()); - assertEquals( "cause", ae.getCause().getMessage() ); + assertEquals("cause", ae.getCause().getMessage()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/OutputStreamMock.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/OutputStreamMock.java index 9266b3486..cfd10fd58 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/OutputStreamMock.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/OutputStreamMock.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.IOException; import java.io.OutputStream; @@ -26,55 +25,43 @@ * @author Michal Maczka * */ -public class OutputStreamMock - extends OutputStream -{ +public class OutputStreamMock extends OutputStream { private boolean closed = false; private boolean forcedError = false; - public void close() - { + public void close() { closed = true; } /** * @see java.io.OutputStream#write(int) */ - public void write( final int b ) - throws IOException - { - if ( forcedError ) - { - throw new IOException( "Mock exception" ); + public void write(final int b) throws IOException { + if (forcedError) { + throw new IOException("Mock exception"); } - } /** * @return Returns the closed. */ - public boolean isClosed() - { + public boolean isClosed() { return closed; } - /** * @return Returns the forcedError. */ - public boolean isForcedError() - { + public boolean isForcedError() { return forcedError; } /** * @param forcedError The forcedError to set. */ - public void setForcedError( final boolean forcedError ) - { + public void setForcedError(final boolean forcedError) { this.forcedError = forcedError; } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/PathUtilsTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/PathUtilsTest.java index 0f092027b..c2556eed1 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/PathUtilsTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/PathUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.File; @@ -27,310 +26,377 @@ * @author Michal Maczka * */ -public class PathUtilsTest - extends TestCase -{ - public void testFilenameResolving() - { - assertEquals( "filename", PathUtils.filename( "dir/filename" ) ); +public class PathUtilsTest extends TestCase { + public void testFilenameResolving() { + assertEquals("filename", PathUtils.filename("dir/filename")); - assertEquals( "filename", PathUtils.filename( "filename" ) ); + assertEquals("filename", PathUtils.filename("filename")); - assertEquals( "filename", PathUtils.filename( "dir1/dir2/filename" ) ); + assertEquals("filename", PathUtils.filename("dir1/dir2/filename")); } - public void testDirResolving() - { - assertEquals( "dir", PathUtils.dirname( "dir/filename" ) ); + public void testDirResolving() { + assertEquals("dir", PathUtils.dirname("dir/filename")); - assertEquals( "", PathUtils.dirname( "filename" ) ); + assertEquals("", PathUtils.dirname("filename")); - assertEquals( "dir1/dir2", PathUtils.dirname( "dir1/dir2/filename" ) ); + assertEquals("dir1/dir2", PathUtils.dirname("dir1/dir2/filename")); } - public void testDirSpliting() - { + public void testDirSpliting() { final String path = "a/b/c"; - final String[] dirs = PathUtils.dirnames( path ); + final String[] dirs = PathUtils.dirnames(path); - assertNotNull( dirs ); + assertNotNull(dirs); - assertEquals( 2, dirs.length ); + assertEquals(2, dirs.length); - assertEquals( "a", dirs[0] ); - - assertEquals( "b", dirs[1] ); + assertEquals("a", dirs[0]); + assertEquals("b", dirs[1]); } - public void testHostResolving() - { - assertEquals( "www.codehaus.org", PathUtils.host( "http://www.codehaus.org" ) ); - assertEquals( "www.codehaus.org", PathUtils.host( "HTTP://www.codehaus.org" ) ); - - assertEquals( "localhost", PathUtils.host( null ) ); - assertEquals( "localhost", PathUtils.host( "file:///c:/temp" ) ); - assertEquals( "localhost", PathUtils.host( "FILE:///c:/temp" ) ); + public void testHostResolving() { + assertEquals("www.codehaus.org", PathUtils.host("http://www.codehaus.org")); + assertEquals("www.codehaus.org", PathUtils.host("HTTP://www.codehaus.org")); + assertEquals("localhost", PathUtils.host(null)); + assertEquals("localhost", PathUtils.host("file:///c:/temp")); + assertEquals("localhost", PathUtils.host("FILE:///c:/temp")); } - public void testScmHostResolving() - { - assertEquals( "www.codehaus.org", PathUtils.host( "scm:svn:http://www.codehaus.org" ) ); - assertEquals( "www.codehaus.org", PathUtils.host( "SCM:SVN:HTTP://www.codehaus.org" ) ); - assertEquals( "www.codehaus.org", PathUtils.host( "scm:svn:http://www.codehaus.org/repos/module" ) ); - assertEquals( "www.codehaus.org", PathUtils.host( "SCM:SVN:HTTP://www.codehaus.org/repos/module" ) ); - assertEquals( "www.codehaus.org", PathUtils.host( "scm:cvs:pserver:anoncvs@www.codehaus.org:/root" ) ); - assertEquals( "www.codehaus.org", PathUtils.host( "SCM:CVS:pserver:anoncvs@www.codehaus.org:/root" ) ); + public void testScmHostResolving() { + assertEquals("www.codehaus.org", PathUtils.host("scm:svn:http://www.codehaus.org")); + assertEquals("www.codehaus.org", PathUtils.host("SCM:SVN:HTTP://www.codehaus.org")); + assertEquals("www.codehaus.org", PathUtils.host("scm:svn:http://www.codehaus.org/repos/module")); + assertEquals("www.codehaus.org", PathUtils.host("SCM:SVN:HTTP://www.codehaus.org/repos/module")); + assertEquals("www.codehaus.org", PathUtils.host("scm:cvs:pserver:anoncvs@www.codehaus.org:/root")); + assertEquals("www.codehaus.org", PathUtils.host("SCM:CVS:pserver:anoncvs@www.codehaus.org:/root")); } - public void testProtocolResolving() - { - assertEquals( "http", PathUtils.protocol( "http://www.codehause.org" ) ); - assertEquals( "HTTP", PathUtils.protocol( "HTTP://www.codehause.org" ) ); - assertEquals( "file", PathUtils.protocol( "file:///c:/temp" ) ); - assertEquals( "scm", PathUtils.protocol( "scm:svn:http://localhost/repos/module" ) ); - assertEquals( "scm", PathUtils.protocol( "scm:cvs:pserver:anoncvs@cvs.apache.org:/home/cvspublic" ) ); + public void testProtocolResolving() { + assertEquals("http", PathUtils.protocol("http://www.codehause.org")); + assertEquals("HTTP", PathUtils.protocol("HTTP://www.codehause.org")); + assertEquals("file", PathUtils.protocol("file:///c:/temp")); + assertEquals("scm", PathUtils.protocol("scm:svn:http://localhost/repos/module")); + assertEquals("scm", PathUtils.protocol("scm:cvs:pserver:anoncvs@cvs.apache.org:/home/cvspublic")); } - public void testUserInfo() - { + public void testUserInfo() { String urlWithUsername = "http://brett@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUsername ) ); - assertNull( PathUtils.password( urlWithUsername ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUsername ) ); - assertEquals( "/", PathUtils.basedir( urlWithUsername ) ); + assertEquals("brett", PathUtils.user(urlWithUsername)); + assertNull(PathUtils.password(urlWithUsername)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUsername)); + assertEquals("/", PathUtils.basedir(urlWithUsername)); String urlWithUsernamePassword = "http://brett:porter@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUsernamePassword ) ); - assertEquals( "porter", PathUtils.password( urlWithUsernamePassword ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUsernamePassword ) ); - assertEquals( "/", PathUtils.basedir( urlWithUsernamePassword ) ); + assertEquals("brett", PathUtils.user(urlWithUsernamePassword)); + assertEquals("porter", PathUtils.password(urlWithUsernamePassword)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUsernamePassword)); + assertEquals("/", PathUtils.basedir(urlWithUsernamePassword)); } - public void testSubversionUserInfo() - { + public void testSubversionUserInfo() { String urlWithUsername = "scm:svn:http://brett@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUsername ) ); - assertNull( PathUtils.password( urlWithUsername ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUsername ) ); - assertEquals( "/", PathUtils.basedir( urlWithUsername ) ); + assertEquals("brett", PathUtils.user(urlWithUsername)); + assertNull(PathUtils.password(urlWithUsername)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUsername)); + assertEquals("/", PathUtils.basedir(urlWithUsername)); String urlWithUsernamePassword = "scm:svn:http://brett:porter@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUsernamePassword ) ); - assertEquals( "porter", PathUtils.password( urlWithUsernamePassword ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUsernamePassword ) ); - assertEquals( "/", PathUtils.basedir( urlWithUsernamePassword ) ); + assertEquals("brett", PathUtils.user(urlWithUsernamePassword)); + assertEquals("porter", PathUtils.password(urlWithUsernamePassword)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUsernamePassword)); + assertEquals("/", PathUtils.basedir(urlWithUsernamePassword)); String urlWithUpperCaseProtocol = "SCM:SVN:HTTP://brett@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUpperCaseProtocol ) ); - assertNull( PathUtils.password( urlWithUpperCaseProtocol ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUpperCaseProtocol ) ); - assertEquals( "/", PathUtils.basedir( urlWithUpperCaseProtocol ) ); + assertEquals("brett", PathUtils.user(urlWithUpperCaseProtocol)); + assertNull(PathUtils.password(urlWithUpperCaseProtocol)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUpperCaseProtocol)); + assertEquals("/", PathUtils.basedir(urlWithUpperCaseProtocol)); } - public void testCvsUserInfo() - { + public void testCvsUserInfo() { String urlWithUsername = "scm:cvs:pserver:brett@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUsername ) ); - assertNull( PathUtils.password( urlWithUsername ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUsername ) ); - assertEquals( "/", PathUtils.basedir( urlWithUsername ) ); + assertEquals("brett", PathUtils.user(urlWithUsername)); + assertNull(PathUtils.password(urlWithUsername)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUsername)); + assertEquals("/", PathUtils.basedir(urlWithUsername)); String urlWithUsernamePassword = "scm:cvs:pserver:brett:porter@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUsernamePassword ) ); - assertEquals( "porter", PathUtils.password( urlWithUsernamePassword ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUsernamePassword ) ); - assertEquals( "/", PathUtils.basedir( urlWithUsernamePassword ) ); + assertEquals("brett", PathUtils.user(urlWithUsernamePassword)); + assertEquals("porter", PathUtils.password(urlWithUsernamePassword)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUsernamePassword)); + assertEquals("/", PathUtils.basedir(urlWithUsernamePassword)); String urlWithUpperCaseProtocol = "SCM:CVS:pserver:brett@www.codehaus.org"; - assertEquals( "brett", PathUtils.user( urlWithUpperCaseProtocol ) ); - assertNull( PathUtils.password( urlWithUpperCaseProtocol ) ); - assertEquals( "www.codehaus.org", PathUtils.host( urlWithUpperCaseProtocol ) ); - assertEquals( "/", PathUtils.basedir( urlWithUpperCaseProtocol ) ); + assertEquals("brett", PathUtils.user(urlWithUpperCaseProtocol)); + assertNull(PathUtils.password(urlWithUpperCaseProtocol)); + assertEquals("www.codehaus.org", PathUtils.host(urlWithUpperCaseProtocol)); + assertEquals("/", PathUtils.basedir(urlWithUpperCaseProtocol)); } - public void testFileBasedir() - { + public void testFileBasedir() { // see http://www.mozilla.org/quality/networking/testing/filetests.html // strict forms - assertEquals( "c:/temp", PathUtils.basedir( "file:///c|/temp" ) ); - assertEquals( "localhost", PathUtils.host( "file:///c|/temp" ) ); - assertEquals( "c:/temp", PathUtils.basedir( "file://localhost/c|/temp" ) ); - assertEquals( "localhost", PathUtils.host( "file://localhost/c|/temp" ) ); - assertEquals( "/temp", PathUtils.basedir( "file:///temp" ) ); - assertEquals( "localhost", PathUtils.host( "file:///temp" ) ); - assertEquals( "/temp", PathUtils.basedir( "file://localhost/temp" ) ); - assertEquals( "localhost", PathUtils.host( "file://localhost/temp" ) ); + assertEquals("c:/temp", PathUtils.basedir("file:///c|/temp")); + assertEquals("localhost", PathUtils.host("file:///c|/temp")); + assertEquals("c:/temp", PathUtils.basedir("file://localhost/c|/temp")); + assertEquals("localhost", PathUtils.host("file://localhost/c|/temp")); + assertEquals("/temp", PathUtils.basedir("file:///temp")); + assertEquals("localhost", PathUtils.host("file:///temp")); + assertEquals("/temp", PathUtils.basedir("file://localhost/temp")); + assertEquals("localhost", PathUtils.host("file://localhost/temp")); // strict form, with : for drive separator - assertEquals( "c:/temp", PathUtils.basedir( "file:///c:/temp" ) ); - assertEquals( "localhost", PathUtils.host( "file:///c:/temp" ) ); - assertEquals( "c:/temp", PathUtils.basedir( "file://localhost/c:/temp" ) ); - assertEquals( "localhost", PathUtils.host( "file://localhost/c:/temp" ) ); + assertEquals("c:/temp", PathUtils.basedir("file:///c:/temp")); + assertEquals("localhost", PathUtils.host("file:///c:/temp")); + assertEquals("c:/temp", PathUtils.basedir("file://localhost/c:/temp")); + assertEquals("localhost", PathUtils.host("file://localhost/c:/temp")); // convenience forms - assertEquals( "c:/temp", PathUtils.basedir( "file://c:/temp" ) ); - assertEquals( "c:/temp", PathUtils.basedir( "file://c|/temp" ) ); - assertEquals( "c:/temp", PathUtils.basedir( "file:c:/temp" ) ); - assertEquals( "c:/temp", PathUtils.basedir( "file:c|/temp" ) ); - assertEquals( "/temp", PathUtils.basedir( "file:/temp" ) ); + assertEquals("c:/temp", PathUtils.basedir("file://c:/temp")); + assertEquals("c:/temp", PathUtils.basedir("file://c|/temp")); + assertEquals("c:/temp", PathUtils.basedir("file:c:/temp")); + assertEquals("c:/temp", PathUtils.basedir("file:c|/temp")); + assertEquals("/temp", PathUtils.basedir("file:/temp")); // URL decoding - assertEquals( "c:/my docs", PathUtils.basedir( "file:///c:/my docs" ) ); - assertEquals( "c:/my docs", PathUtils.basedir( "file:///c:/my%20docs" ) ); - assertEquals( "c:/name #%20?{}[]<>.txt", PathUtils.basedir( "file:///c:/name%20%23%2520%3F%7B%7D%5B%5D%3C%3E.txt" ) ); + assertEquals("c:/my docs", PathUtils.basedir("file:///c:/my docs")); + assertEquals("c:/my docs", PathUtils.basedir("file:///c:/my%20docs")); + assertEquals( + "c:/name #%20?{}[]<>.txt", PathUtils.basedir("file:///c:/name%20%23%2520%3F%7B%7D%5B%5D%3C%3E.txt")); - assertEquals( "c:/temp", PathUtils.basedir( "FILE:///c:/temp" ) ); - assertEquals( "localhost", PathUtils.host( "FILE:///c:/temp" ) ); + assertEquals("c:/temp", PathUtils.basedir("FILE:///c:/temp")); + assertEquals("localhost", PathUtils.host("FILE:///c:/temp")); } - public void testEmptyBasedir() - { - assertEquals( "/", PathUtils.basedir( "http://www.codehaus.org:80" ) ); - assertEquals( "/", PathUtils.basedir( "http://www.codehaus.org" ) ); - assertEquals( "/", PathUtils.basedir( "http://www.codehaus.org:80/" ) ); - assertEquals( "/", PathUtils.basedir( "http://www.codehaus.org/" ) ); - assertEquals( "/", PathUtils.basedir( "HTTP://www.codehaus.org/" ) ); + public void testEmptyBasedir() { + assertEquals("/", PathUtils.basedir("http://www.codehaus.org:80")); + assertEquals("/", PathUtils.basedir("http://www.codehaus.org")); + assertEquals("/", PathUtils.basedir("http://www.codehaus.org:80/")); + assertEquals("/", PathUtils.basedir("http://www.codehaus.org/")); + assertEquals("/", PathUtils.basedir("HTTP://www.codehaus.org/")); } - public void testEmptyProtocol() - { - assertEquals( "", PathUtils.protocol( "placeholder-only" ) ); - assertEquals( "", PathUtils.protocol( "placeholder-only/module-a" ) ); + public void testEmptyProtocol() { + assertEquals("", PathUtils.protocol("placeholder-only")); + assertEquals("", PathUtils.protocol("placeholder-only/module-a")); - assertEquals( "placeholder-only", PathUtils.authorization( "placeholder-only" ) ); - assertEquals( "placeholder-only", PathUtils.authorization( "placeholder-only/module-a" ) ); + assertEquals("placeholder-only", PathUtils.authorization("placeholder-only")); + assertEquals("placeholder-only", PathUtils.authorization("placeholder-only/module-a")); - assertEquals( -1, PathUtils.port( "placeholder-only" ) ); - assertEquals( -1, PathUtils.port( "placeholder-only/module-a" ) ); + assertEquals(-1, PathUtils.port("placeholder-only")); + assertEquals(-1, PathUtils.port("placeholder-only/module-a")); - assertEquals( "/", PathUtils.basedir( "placeholder-only" ) ); - assertEquals( "/module-a", PathUtils.basedir( "placeholder-only/module-a" ) ); + assertEquals("/", PathUtils.basedir("placeholder-only")); + assertEquals("/module-a", PathUtils.basedir("placeholder-only/module-a")); } - public void testPortResolving() - { - assertEquals( 80, PathUtils.port( "http://www.codehause.org:80/maven" ) ); - assertEquals( 80, PathUtils.port( "HTTP://www.codehause.org:80/maven" ) ); - assertEquals( WagonConstants.UNKNOWN_PORT, PathUtils.port( "http://localhost/temp" ) ); + public void testPortResolving() { + assertEquals(80, PathUtils.port("http://www.codehause.org:80/maven")); + assertEquals(80, PathUtils.port("HTTP://www.codehause.org:80/maven")); + assertEquals(WagonConstants.UNKNOWN_PORT, PathUtils.port("http://localhost/temp")); - assertEquals( 10, PathUtils.port( "ftp://localhost:10" ) ); - assertEquals( 10, PathUtils.port( "FTP://localhost:10" ) ); + assertEquals(10, PathUtils.port("ftp://localhost:10")); + assertEquals(10, PathUtils.port("FTP://localhost:10")); } - public void testScmPortResolving() - { - assertEquals( 80, PathUtils.port( "scm:svn:http://www.codehaus.org:80/maven" ) ); - assertEquals( 80, PathUtils.port( "SCM:SVN:HTTP://www.codehaus.org:80/maven" ) ); - assertEquals( WagonConstants.UNKNOWN_PORT, PathUtils.port( "scm:cvs:pserver:anoncvs@localhost:/temp:module" ) ); + public void testScmPortResolving() { + assertEquals(80, PathUtils.port("scm:svn:http://www.codehaus.org:80/maven")); + assertEquals(80, PathUtils.port("SCM:SVN:HTTP://www.codehaus.org:80/maven")); + assertEquals(WagonConstants.UNKNOWN_PORT, PathUtils.port("scm:cvs:pserver:anoncvs@localhost:/temp:module")); - assertEquals( 2402, PathUtils.port( "scm:cvs:pserver:anoncvs@localhost:2402/temp:module" ) ); - assertEquals( 2402, PathUtils.port( "SCM:CVS:pserver:anoncvs@localhost:2402/temp:module" ) ); + assertEquals(2402, PathUtils.port("scm:cvs:pserver:anoncvs@localhost:2402/temp:module")); + assertEquals(2402, PathUtils.port("SCM:CVS:pserver:anoncvs@localhost:2402/temp:module")); } - public void testScmBasedir() - { - assertEquals( "/maven", PathUtils.basedir( "scm:svn:http://www.codehause.org/maven" ) ); - assertEquals( "/maven", PathUtils.basedir( "SCM:SVN:HTTP://www.codehause.org/maven" ) ); - assertEquals( "/maven", PathUtils.basedir( "scm:svn:http://www.codehause.org:80/maven" ) ); - assertEquals( "/maven", PathUtils.basedir( "scm:cvs:pserver:anoncvs@www.codehause.org:80/maven" ) ); - assertEquals( "/maven", PathUtils.basedir( "scm:cvs:pserver:anoncvs@www.codehause.org:/maven" ) ); - assertEquals( "/maven/module", PathUtils.basedir( "scm:cvs:pserver:anoncvs@www.codehause.org:80/maven:module" ) ); - assertEquals( "/maven/module", PathUtils.basedir( "scm:cvs:pserver:anoncvs@www.codehause.org:/maven:module" ) ); - assertEquals( "/maven/module", PathUtils.basedir( "SCM:CVS:pserver:anoncvs@www.codehause.org:/maven:module" ) ); + public void testScmBasedir() { + assertEquals("/maven", PathUtils.basedir("scm:svn:http://www.codehause.org/maven")); + assertEquals("/maven", PathUtils.basedir("SCM:SVN:HTTP://www.codehause.org/maven")); + assertEquals("/maven", PathUtils.basedir("scm:svn:http://www.codehause.org:80/maven")); + assertEquals("/maven", PathUtils.basedir("scm:cvs:pserver:anoncvs@www.codehause.org:80/maven")); + assertEquals("/maven", PathUtils.basedir("scm:cvs:pserver:anoncvs@www.codehause.org:/maven")); + assertEquals("/maven/module", PathUtils.basedir("scm:cvs:pserver:anoncvs@www.codehause.org:80/maven:module")); + assertEquals("/maven/module", PathUtils.basedir("scm:cvs:pserver:anoncvs@www.codehause.org:/maven:module")); + assertEquals("/maven/module", PathUtils.basedir("SCM:CVS:pserver:anoncvs@www.codehause.org:/maven:module")); } - public void testPortBasedir() - { - assertEquals( "/maven", PathUtils.basedir( "http://www.codehause.org:80/maven" ) ); - assertEquals( "/temp", PathUtils.basedir( "http://localhost/temp" ) ); + public void testPortBasedir() { + assertEquals("/maven", PathUtils.basedir("http://www.codehause.org:80/maven")); + assertEquals("/temp", PathUtils.basedir("http://localhost/temp")); - assertEquals( "c:/temp", PathUtils.basedir( "file://c:/temp" ) ); - assertEquals( "/", PathUtils.basedir( "http://localhost:80/" ) ); - assertEquals( "/", PathUtils.basedir( "http://localhost/" ) ); + assertEquals("c:/temp", PathUtils.basedir("file://c:/temp")); + assertEquals("/", PathUtils.basedir("http://localhost:80/")); + assertEquals("/", PathUtils.basedir("http://localhost/")); } - public void testIpV4() - { - assertUrl( "http://127.0.0.1", "http", null, null, "127.0.0.1", -1, "/" ); - assertUrl( "http://127.0.0.1:8080", "http", null, null, "127.0.0.1", 8080, "/" ); - assertUrl( "http://127.0.0.1/oo/rest/users", "http", null, null, "127.0.0.1", -1, "/oo/rest/users" ); - assertUrl( "http://127.0.0.1:8080/oo/rest/users", "http", null, null, "127.0.0.1", 8080, "/oo/rest/users" ); - - assertUrl( "http://user:password@127.0.0.1", "http", "user", "password", "127.0.0.1", -1, "/" ); - assertUrl( "http://user:password@127.0.0.1:8080", "http", "user", "password", "127.0.0.1", 8080, "/" ); - assertUrl( "http://user:password@127.0.0.1/oo/rest/users", "http", "user", "password", "127.0.0.1", -1, - "/oo/rest/users" ); - assertUrl( "http://user:password@127.0.0.1:8080/oo/rest/users", "http", "user", "password", "127.0.0.1", 8080, - "/oo/rest/users" ); - - assertUrl( "scm:svn:http://user:password@127.0.0.1:8080/oo/rest/users", "scm", "user", "password", "127.0.0.1", - 8080, "/oo/rest/users" ); + public void testIpV4() { + assertUrl("http://127.0.0.1", "http", null, null, "127.0.0.1", -1, "/"); + assertUrl("http://127.0.0.1:8080", "http", null, null, "127.0.0.1", 8080, "/"); + assertUrl("http://127.0.0.1/oo/rest/users", "http", null, null, "127.0.0.1", -1, "/oo/rest/users"); + assertUrl("http://127.0.0.1:8080/oo/rest/users", "http", null, null, "127.0.0.1", 8080, "/oo/rest/users"); + + assertUrl("http://user:password@127.0.0.1", "http", "user", "password", "127.0.0.1", -1, "/"); + assertUrl("http://user:password@127.0.0.1:8080", "http", "user", "password", "127.0.0.1", 8080, "/"); + assertUrl( + "http://user:password@127.0.0.1/oo/rest/users", + "http", + "user", + "password", + "127.0.0.1", + -1, + "/oo/rest/users"); + assertUrl( + "http://user:password@127.0.0.1:8080/oo/rest/users", + "http", + "user", + "password", + "127.0.0.1", + 8080, + "/oo/rest/users"); + + assertUrl( + "scm:svn:http://user:password@127.0.0.1:8080/oo/rest/users", + "scm", + "user", + "password", + "127.0.0.1", + 8080, + "/oo/rest/users"); } - public void testIPv6() - { - assertUrl( "http://user:password@[fff:::1]:7891/oo/rest/users", "http", "user", "password", "fff:::1", 7891, - "/oo/rest/users" ); - assertUrl( "http://[fff:::1]:7891/oo/rest/users", "http", null, null, "fff:::1", 7891, "/oo/rest/users" ); - assertUrl( "http://user:password@[fff:::1]/oo/rest/users", "http", "user", "password", "fff:::1", -1, - "/oo/rest/users" ); - assertUrl( "http://user:password@[fff:::1]:7891", "http", "user", "password", "fff:::1", 7891, "/" ); - - assertUrl( "http://user:password@[fff:000::222:1111]:7891/oo/rest/users", "http", "user", "password", - "fff:000::222:1111", 7891, "/oo/rest/users" ); - assertUrl( "http://[fff:000::222:1111]:7891/oo/rest/users", "http", null, null, "fff:000::222:1111", 7891, - "/oo/rest/users" ); - assertUrl( "http://user:password@[fff:000::222:1111]/oo/rest/users", "http", "user", "password", - "fff:000::222:1111", -1, "/oo/rest/users" ); - assertUrl( "http://user:password@[fff:000::222:1111]:7891", "http", "user", "password", "fff:000::222:1111", - 7891, "/" ); - - assertUrl( "http://user:password@16.60.56.58:7891/oo/rest/users", "http", "user", "password", "16.60.56.58", - 7891, "/oo/rest/users" ); - assertUrl( "http://16.60.56.58:7891/oo/rest/users", "http", null, null, "16.60.56.58", 7891, "/oo/rest/users" ); - assertUrl( "http://user:password@16.60.56.58/oo/rest/users", "http", "user", "password", "16.60.56.58", -1, - "/oo/rest/users" ); - assertUrl( "http://user:password@16.60.56.58:7891", "http", "user", "password", "16.60.56.58", 7891, "/" ); - - assertUrl( "http://user:password@16.60.56.58:7891/oo/rest/users", "http", "user", "password", "16.60.56.58", - 7891, "/oo/rest/users" ); - assertUrl( "http://16.60.56.58:7891/oo/rest/users", "http", null, null, "16.60.56.58", 7891, "/oo/rest/users" ); - assertUrl( "http://user:password@16.60.56.58/oo/rest/users", "http", "user", "password", "16.60.56.58", -1, - "/oo/rest/users" ); - assertUrl( "http://user:password@16.60.56.58:7891", "http", "user", "password", "16.60.56.58", 7891, "/" ); + public void testIPv6() { + assertUrl( + "http://user:password@[fff:::1]:7891/oo/rest/users", + "http", + "user", + "password", + "fff:::1", + 7891, + "/oo/rest/users"); + assertUrl("http://[fff:::1]:7891/oo/rest/users", "http", null, null, "fff:::1", 7891, "/oo/rest/users"); + assertUrl( + "http://user:password@[fff:::1]/oo/rest/users", + "http", + "user", + "password", + "fff:::1", + -1, + "/oo/rest/users"); + assertUrl("http://user:password@[fff:::1]:7891", "http", "user", "password", "fff:::1", 7891, "/"); + + assertUrl( + "http://user:password@[fff:000::222:1111]:7891/oo/rest/users", + "http", + "user", + "password", + "fff:000::222:1111", + 7891, + "/oo/rest/users"); + assertUrl( + "http://[fff:000::222:1111]:7891/oo/rest/users", + "http", + null, + null, + "fff:000::222:1111", + 7891, + "/oo/rest/users"); + assertUrl( + "http://user:password@[fff:000::222:1111]/oo/rest/users", + "http", + "user", + "password", + "fff:000::222:1111", + -1, + "/oo/rest/users"); + assertUrl( + "http://user:password@[fff:000::222:1111]:7891", + "http", + "user", + "password", + "fff:000::222:1111", + 7891, + "/"); + + assertUrl( + "http://user:password@16.60.56.58:7891/oo/rest/users", + "http", + "user", + "password", + "16.60.56.58", + 7891, + "/oo/rest/users"); + assertUrl("http://16.60.56.58:7891/oo/rest/users", "http", null, null, "16.60.56.58", 7891, "/oo/rest/users"); + assertUrl( + "http://user:password@16.60.56.58/oo/rest/users", + "http", + "user", + "password", + "16.60.56.58", + -1, + "/oo/rest/users"); + assertUrl("http://user:password@16.60.56.58:7891", "http", "user", "password", "16.60.56.58", 7891, "/"); + + assertUrl( + "http://user:password@16.60.56.58:7891/oo/rest/users", + "http", + "user", + "password", + "16.60.56.58", + 7891, + "/oo/rest/users"); + assertUrl("http://16.60.56.58:7891/oo/rest/users", "http", null, null, "16.60.56.58", 7891, "/oo/rest/users"); + assertUrl( + "http://user:password@16.60.56.58/oo/rest/users", + "http", + "user", + "password", + "16.60.56.58", + -1, + "/oo/rest/users"); + assertUrl("http://user:password@16.60.56.58:7891", "http", "user", "password", "16.60.56.58", 7891, "/"); } - private void assertUrl( String url, String protocol, String user, String password, String host, int port, - String basedir ) - { - assertEquals( protocol, PathUtils.protocol( url ) ); - assertEquals( user, PathUtils.user( url ) ); - assertEquals( password, PathUtils.password( url ) ); - assertEquals( host, PathUtils.host( url ) ); - assertEquals( port, PathUtils.port( url ) ); - assertEquals( basedir, PathUtils.basedir( url ) ); + private void assertUrl( + String url, String protocol, String user, String password, String host, int port, String basedir) { + assertEquals(protocol, PathUtils.protocol(url)); + assertEquals(user, PathUtils.user(url)); + assertEquals(password, PathUtils.password(url)); + assertEquals(host, PathUtils.host(url)); + assertEquals(port, PathUtils.port(url)); + assertEquals(basedir, PathUtils.basedir(url)); } - public void testToRelative() - { - assertEquals( "dir", PathUtils.toRelative( new File( "/home/user" ).getAbsoluteFile(), - new File( "/home/user/dir" ).getAbsolutePath() ) ); - assertEquals( "dir", PathUtils.toRelative( new File( "C:/home/user" ).getAbsoluteFile(), - new File( "C:/home/user/dir" ).getAbsolutePath() ) ); - - assertEquals( "dir/subdir", PathUtils.toRelative( new File( "/home/user" ).getAbsoluteFile(), - new File( "/home/user/dir/subdir" ).getAbsolutePath() ) ); - assertEquals( "dir/subdir", PathUtils.toRelative( new File( "C:/home/user" ).getAbsoluteFile(), - new File( "C:/home/user/dir/subdir" ).getAbsolutePath() ) ); - - assertEquals( ".", PathUtils.toRelative( new File( "/home/user" ).getAbsoluteFile(), - new File( "/home/user" ).getAbsolutePath() ) ); - assertEquals( ".", PathUtils.toRelative( new File( "C:/home/user" ).getAbsoluteFile(), - new File( "C:/home/user" ).getAbsolutePath() ) ); + public void testToRelative() { + assertEquals( + "dir", + PathUtils.toRelative( + new File("/home/user").getAbsoluteFile(), new File("/home/user/dir").getAbsolutePath())); + assertEquals( + "dir", + PathUtils.toRelative( + new File("C:/home/user").getAbsoluteFile(), new File("C:/home/user/dir").getAbsolutePath())); + + assertEquals( + "dir/subdir", + PathUtils.toRelative( + new File("/home/user").getAbsoluteFile(), new File("/home/user/dir/subdir").getAbsolutePath())); + assertEquals( + "dir/subdir", + PathUtils.toRelative( + new File("C:/home/user").getAbsoluteFile(), + new File("C:/home/user/dir/subdir").getAbsolutePath())); + + assertEquals( + ".", + PathUtils.toRelative( + new File("/home/user").getAbsoluteFile(), new File("/home/user").getAbsolutePath())); + assertEquals( + ".", + PathUtils.toRelative( + new File("C:/home/user").getAbsoluteFile(), new File("C:/home/user").getAbsolutePath())); } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/PermissionModeUtilsTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/PermissionModeUtilsTest.java index 2dbc36fb9..f5314d1a2 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/PermissionModeUtilsTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/PermissionModeUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import junit.framework.TestCase; @@ -28,15 +27,11 @@ * @see PermissionModeUtils * @since Sep 3, 2005 */ -public class PermissionModeUtilsTest - extends TestCase -{ +public class PermissionModeUtilsTest extends TestCase { /** * @throws Exception on error */ - public void testNumeric() - throws Exception - { + public void testNumeric() throws Exception { final String[][] tests = { {"0", "777"}, {"0000", "777"}, @@ -48,23 +43,18 @@ public void testNumeric() {"ug+rwX,o-rwX", "ug+rwX,o-rwX"}, {"1770", "7"}, {"14770", "7"}, - }; - for ( String[] test : tests ) - { + for (String[] test : tests) { String umask = null; - try - { - umask = PermissionModeUtils.getUserMaskFor( test[ 0 ] ); - } - catch ( IllegalArgumentException e ) - { + try { + umask = PermissionModeUtils.getUserMaskFor(test[0]); + } catch (IllegalArgumentException e) { // nothing to do } - assertEquals( test[ 1 ], umask ); + assertEquals(test[1], umask); } } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/ResourceDoesNotExistExceptionTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/ResourceDoesNotExistExceptionTest.java index 512311371..ef33f1e14 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/ResourceDoesNotExistExceptionTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/ResourceDoesNotExistExceptionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import junit.framework.TestCase; @@ -25,19 +24,16 @@ * @author Jason van Zyl * */ -public class ResourceDoesNotExistExceptionTest - extends TestCase -{ - public void testResourceDoesNotExistExceptionTest() - { - ResourceDoesNotExistException ae = new ResourceDoesNotExistException( "message" ); +public class ResourceDoesNotExistExceptionTest extends TestCase { + public void testResourceDoesNotExistExceptionTest() { + ResourceDoesNotExistException ae = new ResourceDoesNotExistException("message"); - assertEquals( "message", ae.getMessage() ); + assertEquals("message", ae.getMessage()); - ae = new ResourceDoesNotExistException( "full-message", new Throwable( "cause" ) ); + ae = new ResourceDoesNotExistException("full-message", new Throwable("cause")); - assertEquals( "full-message", ae.getMessage() ); + assertEquals("full-message", ae.getMessage()); - assertEquals( "cause", ae.getCause().getMessage() ); + assertEquals("cause", ae.getCause().getMessage()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/StreamWagonTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/StreamWagonTest.java index 5904cbd61..b4b735727 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/StreamWagonTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/StreamWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import junit.framework.TestCase; - import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authorization.AuthorizationException; import org.apache.maven.wagon.events.TransferEvent; @@ -37,507 +35,378 @@ import static org.easymock.EasyMock.*; -public class StreamWagonTest - extends TestCase -{ - private static class TestWagon - extends StreamWagon - { - public void closeConnection() - throws ConnectionException - { - } +public class StreamWagonTest extends TestCase { + private static class TestWagon extends StreamWagon { + public void closeConnection() throws ConnectionException {} - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - } + public void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {} - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - } + public void fillOutputData(OutputData outputData) throws TransferFailedException {} - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { - } + protected void openConnectionInternal() throws ConnectionException, AuthenticationException {} } - private Repository repository = new Repository( "id", "url" ); + private Repository repository = new Repository("id", "url"); - public void testNullInputStream() - throws Exception - { - StreamingWagon wagon = new TestWagon() - { - public void fillInputData( InputData inputData ) - { - inputData.setInputStream( null ); + public void testNullInputStream() throws Exception { + StreamingWagon wagon = new TestWagon() { + public void fillInputData(InputData inputData) { + inputData.setInputStream(null); } }; - TransferListener listener = createMock( TransferListener.class ); - listener.transferInitiated( anyObject( TransferEvent.class ) ); - TransferEvent transferEvent = - new TransferEvent( wagon, new Resource( "resource" ), new TransferFailedException( "" ), - TransferEvent.REQUEST_GET ); - listener.transferError( transferEvent ); - replay( listener ); - - wagon.connect( repository ); - wagon.addTransferListener( listener ); - try - { - wagon.getToStream( "resource", new StringOutputStream() ); + TransferListener listener = createMock(TransferListener.class); + listener.transferInitiated(anyObject(TransferEvent.class)); + TransferEvent transferEvent = new TransferEvent( + wagon, new Resource("resource"), new TransferFailedException(""), TransferEvent.REQUEST_GET); + listener.transferError(transferEvent); + replay(listener); + + wagon.connect(repository); + wagon.addTransferListener(listener); + try { + wagon.getToStream("resource", new StringOutputStream()); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); - } - finally - { + } catch (TransferFailedException e) { + assertTrue(true); + } finally { wagon.disconnect(); } - verify( listener ); + verify(listener); } - public void testNullOutputStream() - throws Exception - { - StreamingWagon wagon = new TestWagon() - { - public void fillOutputData( OutputData inputData ) - { - inputData.setOutputStream( null ); + public void testNullOutputStream() throws Exception { + StreamingWagon wagon = new TestWagon() { + public void fillOutputData(OutputData inputData) { + inputData.setOutputStream(null); } }; - TransferListener listener = createMock( TransferListener.class ); - listener.transferInitiated( anyObject( TransferEvent.class ) ); - TransferEvent transferEvent = - new TransferEvent( wagon, new Resource( "resource" ), new TransferFailedException( "" ), - TransferEvent.REQUEST_PUT ); - listener.transferError( transferEvent ); - replay( listener ); - - wagon.connect( repository ); - wagon.addTransferListener( listener ); - try - { - wagon.putFromStream( new StringInputStream( "" ), "resource" ); + TransferListener listener = createMock(TransferListener.class); + listener.transferInitiated(anyObject(TransferEvent.class)); + TransferEvent transferEvent = new TransferEvent( + wagon, new Resource("resource"), new TransferFailedException(""), TransferEvent.REQUEST_PUT); + listener.transferError(transferEvent); + replay(listener); + + wagon.connect(repository); + wagon.addTransferListener(listener); + try { + wagon.putFromStream(new StringInputStream(""), "resource"); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); - } - finally - { + } catch (TransferFailedException e) { + assertTrue(true); + } finally { wagon.disconnect(); } - verify( listener ); + verify(listener); } - public void testTransferFailedExceptionOnInput() - throws Exception - { - try - { - runTestTransferError( new TransferFailedException( "" ) ); + public void testTransferFailedExceptionOnInput() throws Exception { + try { + runTestTransferError(new TransferFailedException("")); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } } - public void testTransferFailedExceptionOnOutput() - throws Exception - { - StreamingWagon wagon = new TestWagon() - { - public void fillOutputData( OutputData inputData ) - throws TransferFailedException - { - throw (TransferFailedException) new TransferFailedException( "" ); + public void testTransferFailedExceptionOnOutput() throws Exception { + StreamingWagon wagon = new TestWagon() { + public void fillOutputData(OutputData inputData) throws TransferFailedException { + throw (TransferFailedException) new TransferFailedException(""); } }; - TransferListener listener = createMock( TransferListener.class ); - listener.transferInitiated( anyObject( TransferEvent.class ) ); - TransferEvent transferEvent = - new TransferEvent( wagon, new Resource( "resource" ), new TransferFailedException( "" ), - TransferEvent.REQUEST_PUT ); - listener.transferError( transferEvent ); - replay( listener ); - - wagon.connect( repository ); - wagon.addTransferListener( listener ); - try - { - wagon.putFromStream( new StringInputStream( "" ), "resource" ); + TransferListener listener = createMock(TransferListener.class); + listener.transferInitiated(anyObject(TransferEvent.class)); + TransferEvent transferEvent = new TransferEvent( + wagon, new Resource("resource"), new TransferFailedException(""), TransferEvent.REQUEST_PUT); + listener.transferError(transferEvent); + replay(listener); + + wagon.connect(repository); + wagon.addTransferListener(listener); + try { + wagon.putFromStream(new StringInputStream(""), "resource"); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); - } - finally - { + } catch (TransferFailedException e) { + assertTrue(true); + } finally { wagon.disconnect(); - verify( listener ); + verify(listener); } } - public void testResourceDoesNotExistException() - throws Exception - { - try - { - runTestTransferError( new ResourceDoesNotExistException( "" ) ); + public void testResourceDoesNotExistException() throws Exception { + try { + runTestTransferError(new ResourceDoesNotExistException("")); fail(); - } - catch ( ResourceDoesNotExistException e ) - { - assertTrue( true ); + } catch (ResourceDoesNotExistException e) { + assertTrue(true); } } - public void testAuthorizationException() - throws Exception - { - try - { - runTestTransferError( new AuthorizationException( "" ) ); + public void testAuthorizationException() throws Exception { + try { + runTestTransferError(new AuthorizationException("")); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - private void runTestTransferError( final WagonException exception ) - throws ConnectionException, AuthenticationException, ResourceDoesNotExistException, AuthorizationException, - TransferFailedException - { - StreamingWagon wagon = new TestWagon() - { - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( exception instanceof TransferFailedException ) - { + private void runTestTransferError(final WagonException exception) + throws ConnectionException, AuthenticationException, ResourceDoesNotExistException, AuthorizationException, + TransferFailedException { + StreamingWagon wagon = new TestWagon() { + public void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (exception instanceof TransferFailedException) { throw (TransferFailedException) exception; } - if ( exception instanceof ResourceDoesNotExistException ) - { + if (exception instanceof ResourceDoesNotExistException) { throw (ResourceDoesNotExistException) exception; } - if ( exception instanceof AuthorizationException ) - { + if (exception instanceof AuthorizationException) { throw (AuthorizationException) exception; } } }; - TransferListener listener = createMock( TransferListener.class ); - listener.transferInitiated( anyObject( TransferEvent.class ) ); + TransferListener listener = createMock(TransferListener.class); + listener.transferInitiated(anyObject(TransferEvent.class)); TransferEvent transferEvent = - new TransferEvent( wagon, new Resource( "resource" ), exception, TransferEvent.REQUEST_GET ); - listener.transferError( transferEvent ); - replay( listener ); - - wagon.connect( repository ); - wagon.addTransferListener( listener ); - try - { - wagon.getToStream( "resource", new StringOutputStream() ); + new TransferEvent(wagon, new Resource("resource"), exception, TransferEvent.REQUEST_GET); + listener.transferError(transferEvent); + replay(listener); + + wagon.connect(repository); + wagon.addTransferListener(listener); + try { + wagon.getToStream("resource", new StringOutputStream()); fail(); - } - finally - { + } finally { wagon.disconnect(); - verify( listener ); + verify(listener); } } - public void testGetIfNewerWithNewerResource() - throws Exception - { + public void testGetIfNewerWithNewerResource() throws Exception { long resourceTime = System.currentTimeMillis(); - long comparisonTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - assertTrue( runTestGetIfNewer( resourceTime, comparisonTime ) ); + long comparisonTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + assertTrue(runTestGetIfNewer(resourceTime, comparisonTime)); } - public void testGetIfNewerWithOlderResource() - throws Exception - { + public void testGetIfNewerWithOlderResource() throws Exception { long comparisonTime = System.currentTimeMillis(); - long resourceTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - assertFalse( runTestGetIfNewer( resourceTime, comparisonTime ) ); + long resourceTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + assertFalse(runTestGetIfNewer(resourceTime, comparisonTime)); } - public void testGetIfNewerWithSameTimeResource() - throws Exception - { - long resourceTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - assertFalse( runTestGetIfNewer( resourceTime, resourceTime ) ); + public void testGetIfNewerWithSameTimeResource() throws Exception { + long resourceTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + assertFalse(runTestGetIfNewer(resourceTime, resourceTime)); } - private boolean runTestGetIfNewer( final long resourceTime, long comparisonTime ) - throws IOException, ConnectionException, AuthenticationException, TransferFailedException, - ResourceDoesNotExistException, AuthorizationException - { - StreamingWagon wagon = new TestWagon() - { - public void fillInputData( InputData inputData ) - { - inputData.setInputStream( new StringInputStream( "" ) ); - inputData.getResource().setLastModified( resourceTime ); + private boolean runTestGetIfNewer(final long resourceTime, long comparisonTime) + throws IOException, ConnectionException, AuthenticationException, TransferFailedException, + ResourceDoesNotExistException, AuthorizationException { + StreamingWagon wagon = new TestWagon() { + public void fillInputData(InputData inputData) { + inputData.setInputStream(new StringInputStream("")); + inputData.getResource().setLastModified(resourceTime); } }; - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); - wagon.connect( repository ); - try - { - return wagon.getIfNewer( "resource", tempFile, comparisonTime ); - } - finally - { + wagon.connect(repository); + try { + return wagon.getIfNewer("resource", tempFile, comparisonTime); + } finally { wagon.disconnect(); tempFile.delete(); } } - public void testGetToStream() - throws Exception - { + public void testGetToStream() throws Exception { final String content = "the content to return"; - final long comparisonTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - StreamingWagon wagon = new TestWagon() - { - public void fillInputData( InputData inputData ) - { - inputData.setInputStream( new StringInputStream( content ) ); - inputData.getResource().setLastModified( comparisonTime ); + final long comparisonTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + StreamingWagon wagon = new TestWagon() { + public void fillInputData(InputData inputData) { + inputData.setInputStream(new StringInputStream(content)); + inputData.getResource().setLastModified(comparisonTime); } }; - wagon.connect( repository ); - try - { + wagon.connect(repository); + try { StringOutputStream out = new StringOutputStream(); - wagon.getToStream( "resource", out ); - assertEquals( content, out.toString() ); - } - finally - { + wagon.getToStream("resource", out); + assertEquals(content, out.toString()); + } finally { wagon.disconnect(); } } - public void testGet() - throws Exception - { + public void testGet() throws Exception { final String content = "the content to return"; - final long comparisonTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - StreamingWagon wagon = new TestWagon() - { - public void fillInputData( InputData inputData ) - { - inputData.setInputStream( new StringInputStream( content ) ); - inputData.getResource().setLastModified( comparisonTime ); + final long comparisonTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + StreamingWagon wagon = new TestWagon() { + public void fillInputData(InputData inputData) { + inputData.setInputStream(new StringInputStream(content)); + inputData.getResource().setLastModified(comparisonTime); } }; - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); - wagon.connect( repository ); - try - { - wagon.get( "resource", tempFile ); - assertEquals( content, FileUtils.fileRead( tempFile ) ); - } - finally - { + wagon.connect(repository); + try { + wagon.get("resource", tempFile); + assertEquals(content, FileUtils.fileRead(tempFile)); + } finally { wagon.disconnect(); tempFile.delete(); } } - public void testGetIfNewerToStreamWithNewerResource() - throws Exception - { + public void testGetIfNewerToStreamWithNewerResource() throws Exception { long resourceTime = System.currentTimeMillis(); - long comparisonTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - assertTrue( runTestGetIfNewerToStream( resourceTime, comparisonTime ) ); + long comparisonTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + assertTrue(runTestGetIfNewerToStream(resourceTime, comparisonTime)); } - public void testGetIfNewerToStreamWithOlderResource() - throws Exception - { + public void testGetIfNewerToStreamWithOlderResource() throws Exception { long comparisonTime = System.currentTimeMillis(); - long resourceTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - assertFalse( runTestGetIfNewerToStream( resourceTime, comparisonTime ) ); + long resourceTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + assertFalse(runTestGetIfNewerToStream(resourceTime, comparisonTime)); } - public void testGetIfNewerToStreamWithSameTimeResource() - throws Exception - { - long resourceTime = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2008-01-01" ).getTime(); - assertFalse( runTestGetIfNewerToStream( resourceTime, resourceTime ) ); + public void testGetIfNewerToStreamWithSameTimeResource() throws Exception { + long resourceTime = + new SimpleDateFormat("yyyy-MM-dd").parse("2008-01-01").getTime(); + assertFalse(runTestGetIfNewerToStream(resourceTime, resourceTime)); } - private boolean runTestGetIfNewerToStream( final long resourceTime, long comparisonTime ) - throws IOException, ConnectionException, AuthenticationException, TransferFailedException, - ResourceDoesNotExistException, AuthorizationException - { - StreamingWagon wagon = new TestWagon() - { - public void fillInputData( InputData inputData ) - { - inputData.setInputStream( new StringInputStream( "" ) ); - inputData.getResource().setLastModified( resourceTime ); + private boolean runTestGetIfNewerToStream(final long resourceTime, long comparisonTime) + throws IOException, ConnectionException, AuthenticationException, TransferFailedException, + ResourceDoesNotExistException, AuthorizationException { + StreamingWagon wagon = new TestWagon() { + public void fillInputData(InputData inputData) { + inputData.setInputStream(new StringInputStream("")); + inputData.getResource().setLastModified(resourceTime); } }; - wagon.connect( repository ); - try - { - return wagon.getIfNewerToStream( "resource", new StringOutputStream(), comparisonTime ); - } - finally - { + wagon.connect(repository); + try { + return wagon.getIfNewerToStream("resource", new StringOutputStream(), comparisonTime); + } finally { wagon.disconnect(); } } - public void testPutFromStream() - throws Exception - { + public void testPutFromStream() throws Exception { final String content = "the content to return"; final StringOutputStream out = new StringOutputStream(); - StreamingWagon wagon = new TestWagon() - { - public void fillOutputData( OutputData outputData ) - { - assertEquals( "resource", outputData.getResource().getName() ); - assertEquals( -1, outputData.getResource().getContentLength() ); - assertEquals( 0, outputData.getResource().getLastModified() ); - outputData.setOutputStream( out ); + StreamingWagon wagon = new TestWagon() { + public void fillOutputData(OutputData outputData) { + assertEquals("resource", outputData.getResource().getName()); + assertEquals(-1, outputData.getResource().getContentLength()); + assertEquals(0, outputData.getResource().getLastModified()); + outputData.setOutputStream(out); } }; - wagon.connect( repository ); - try - { - wagon.putFromStream( new StringInputStream( content ), "resource" ); - assertEquals( content, out.toString() ); - } - finally - { + wagon.connect(repository); + try { + wagon.putFromStream(new StringInputStream(content), "resource"); + assertEquals(content, out.toString()); + } finally { wagon.disconnect(); } } - public void testPutFromStreamWithResourceInformation() - throws Exception - { + public void testPutFromStreamWithResourceInformation() throws Exception { final String content = "the content to return"; final long lastModified = System.currentTimeMillis(); final StringOutputStream out = new StringOutputStream(); - StreamingWagon wagon = new TestWagon() - { - public void fillOutputData( OutputData outputData ) - { - assertEquals( "resource", outputData.getResource().getName() ); - assertEquals( content.length(), outputData.getResource().getContentLength() ); - assertEquals( lastModified, outputData.getResource().getLastModified() ); - outputData.setOutputStream( out ); + StreamingWagon wagon = new TestWagon() { + public void fillOutputData(OutputData outputData) { + assertEquals("resource", outputData.getResource().getName()); + assertEquals(content.length(), outputData.getResource().getContentLength()); + assertEquals(lastModified, outputData.getResource().getLastModified()); + outputData.setOutputStream(out); } }; - wagon.connect( repository ); - try - { - wagon.putFromStream( new StringInputStream( content ), "resource", content.length(), lastModified ); - assertEquals( content, out.toString() ); - } - finally - { + wagon.connect(repository); + try { + wagon.putFromStream(new StringInputStream(content), "resource", content.length(), lastModified); + assertEquals(content, out.toString()); + } finally { wagon.disconnect(); } } - public void testPut() - throws Exception - { + public void testPut() throws Exception { final String content = "the content to return"; - final File tempFile = File.createTempFile( "wagon", "tmp" ); - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); + final File tempFile = File.createTempFile("wagon", "tmp"); + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); tempFile.deleteOnExit(); final StringOutputStream out = new StringOutputStream(); - Wagon wagon = new TestWagon() - { - public void fillOutputData( OutputData outputData ) - { - assertEquals( "resource", outputData.getResource().getName() ); - assertEquals( content.length(), outputData.getResource().getContentLength() ); - assertEquals( tempFile.lastModified(), outputData.getResource().getLastModified() ); - outputData.setOutputStream( out ); + Wagon wagon = new TestWagon() { + public void fillOutputData(OutputData outputData) { + assertEquals("resource", outputData.getResource().getName()); + assertEquals(content.length(), outputData.getResource().getContentLength()); + assertEquals(tempFile.lastModified(), outputData.getResource().getLastModified()); + outputData.setOutputStream(out); } }; - wagon.connect( repository ); - try - { - wagon.put( tempFile, "resource" ); - assertEquals( content, out.toString() ); - } - finally - { + wagon.connect(repository); + try { + wagon.put(tempFile, "resource"); + assertEquals(content, out.toString()); + } finally { wagon.disconnect(); tempFile.delete(); } } - public void testPutFileDoesntExist() - throws Exception - { - final File tempFile = File.createTempFile( "wagon", "tmp" ); + public void testPutFileDoesntExist() throws Exception { + final File tempFile = File.createTempFile("wagon", "tmp"); tempFile.delete(); - assertFalse( tempFile.exists() ); + assertFalse(tempFile.exists()); Wagon wagon = new TestWagon(); - wagon.connect( repository ); - try - { - wagon.put( tempFile, "resource" ); + wagon.connect(repository); + try { + wagon.put(tempFile, "resource"); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); - } - finally - { + } catch (TransferFailedException e) { + assertTrue(true); + } finally { wagon.disconnect(); } } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/TransferFailedExceptionTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/TransferFailedExceptionTest.java index dd1221878..b3b3d5d0f 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/TransferFailedExceptionTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/TransferFailedExceptionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import junit.framework.TestCase; @@ -25,19 +24,16 @@ * @author Jason van Zyl * */ -public class TransferFailedExceptionTest - extends TestCase -{ - public void testTransferFailedExceptionTest() - { - TransferFailedException ae = new TransferFailedException( "message" ); +public class TransferFailedExceptionTest extends TestCase { + public void testTransferFailedExceptionTest() { + TransferFailedException ae = new TransferFailedException("message"); - assertEquals( "message", ae.getMessage() ); + assertEquals("message", ae.getMessage()); - ae = new TransferFailedException( "full-message", new Throwable( "cause" ) ); + ae = new TransferFailedException("full-message", new Throwable("cause")); - assertEquals( "full-message", ae.getMessage() ); + assertEquals("full-message", ae.getMessage()); - assertEquals( "cause", ae.getCause().getMessage() ); + assertEquals("cause", ae.getCause().getMessage()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/WagonMock.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/WagonMock.java index 311b21a1b..626bf9195 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/WagonMock.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/WagonMock.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -32,99 +31,71 @@ * @author Jason van Zyl * */ -public class WagonMock - extends StreamWagon -{ +public class WagonMock extends StreamWagon { private boolean errorInputStream; private int timeout = 0; - public WagonMock() - { - } + public WagonMock() {} - public WagonMock( boolean errorInputStream ) - { + public WagonMock(boolean errorInputStream) { this.errorInputStream = errorInputStream; } - - public void fillInputData( InputData inputData ) - throws TransferFailedException - { + public void fillInputData(InputData inputData) throws TransferFailedException { InputStream is; - if ( errorInputStream ) - { + if (errorInputStream) { InputStreamMock mockInputStream = new InputStreamMock(); - mockInputStream.setForcedError( true ); + mockInputStream.setForcedError(true); is = mockInputStream; - } - else - { + } else { byte[] buffer = new byte[1024 * 4 * 5]; - is = new ByteArrayInputStream( buffer ); + is = new ByteArrayInputStream(buffer); } - inputData.setInputStream( is ); - + inputData.setInputStream(is); } - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { + public void fillOutputData(OutputData outputData) throws TransferFailedException { OutputStream os; - if ( errorInputStream ) - { + if (errorInputStream) { OutputStreamMock mockOutputStream = new OutputStreamMock(); - mockOutputStream.setForcedError( true ); + mockOutputStream.setForcedError(true); os = mockOutputStream; - } - else - { + } else { os = new ByteArrayOutputStream(); } - outputData.setOutputStream( os ); - + outputData.setOutputStream(os); } - public void openConnectionInternal() - { - } + public void openConnectionInternal() {} - public void closeConnection() - { - } - - public void setTimeout( int timeoutValue ) - { - timeout = timeoutValue; + public void closeConnection() {} + + public void setTimeout(int timeoutValue) { + timeout = timeoutValue; } - - public int getTimeout() - { - return timeout; + + public int getTimeout() { + return timeout; } - public List getFileList( String destinationDirectory ) - throws TransferFailedException, AuthorizationException - { + public List getFileList(String destinationDirectory) + throws TransferFailedException, AuthorizationException { return Collections.emptyList(); } - public boolean resourceExists( String resourceName ) - throws AuthorizationException - { + public boolean resourceExists(String resourceName) throws AuthorizationException { return false; } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationExceptionTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationExceptionTest.java index a8d7e7341..02defbd95 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationExceptionTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationExceptionTest.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.wagon.authentication; /* @@ -25,19 +43,16 @@ * @author Jason van Zyl * */ -public class AuthenticationExceptionTest - extends TestCase -{ - public void testAuthenticationExceptionTest() - { - AuthenticationException ae = new AuthenticationException( "message" ); +public class AuthenticationExceptionTest extends TestCase { + public void testAuthenticationExceptionTest() { + AuthenticationException ae = new AuthenticationException("message"); - assertEquals( "message", ae.getMessage() ); + assertEquals("message", ae.getMessage()); - ae = new AuthenticationException( "full-message", new Throwable( "cause" ) ); + ae = new AuthenticationException("full-message", new Throwable("cause")); - assertEquals( "full-message", ae.getMessage() ); + assertEquals("full-message", ae.getMessage()); - assertEquals( "cause", ae.getCause().getMessage() ); + assertEquals("cause", ae.getCause().getMessage()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationInfoTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationInfoTest.java index d65207de7..ff7765b28 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationInfoTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/authentication/AuthenticationInfoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.authentication; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.authentication; import junit.framework.TestCase; @@ -26,44 +25,36 @@ * * @todo test defaults */ -public class AuthenticationInfoTest - extends TestCase -{ - public AuthenticationInfoTest( final String name ) - { - super( name ); +public class AuthenticationInfoTest extends TestCase { + public AuthenticationInfoTest(final String name) { + super(name); } - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); } - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } - public void testAuthenticationInfoProperties() - { + public void testAuthenticationInfoProperties() { final AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setUserName( "username" ); + authenticationInfo.setUserName("username"); - assertEquals( "username", authenticationInfo.getUserName() ); + assertEquals("username", authenticationInfo.getUserName()); - authenticationInfo.setPassword( "password" ); + authenticationInfo.setPassword("password"); - assertEquals( "password", authenticationInfo.getPassword() ); + assertEquals("password", authenticationInfo.getPassword()); - authenticationInfo.setPassphrase( "passphrase" ); + authenticationInfo.setPassphrase("passphrase"); - assertEquals( "passphrase", authenticationInfo.getPassphrase() ); + assertEquals("passphrase", authenticationInfo.getPassphrase()); - authenticationInfo.setPrivateKey( "privatekey" ); + authenticationInfo.setPrivateKey("privatekey"); - assertEquals( "privatekey", authenticationInfo.getPrivateKey() ); + assertEquals("privatekey", authenticationInfo.getPrivateKey()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventSupportTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventSupportTest.java index eca243aad..f554a4669 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventSupportTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventSupportTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import junit.framework.TestCase; - import org.apache.maven.wagon.Wagon; import static org.easymock.EasyMock.*; @@ -29,9 +27,7 @@ * @author Michal Maczka * */ -public class SessionEventSupportTest - extends TestCase -{ +public class SessionEventSupportTest extends TestCase { private SessionEventSupport eventSupport; @@ -40,218 +36,206 @@ public class SessionEventSupportTest /** * @see junit.framework.TestCase#setUp() */ - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); eventSupport = new SessionEventSupport(); - + // TODO: actually test it gets called? - wagon = createNiceMock( Wagon.class ); + wagon = createNiceMock(Wagon.class); } - public void testSessionListenerRegistration() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testSessionListenerRegistration() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - assertTrue( eventSupport.hasSessionListener( mock1 ) ); + assertTrue(eventSupport.hasSessionListener(mock1)); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - assertFalse( eventSupport.hasSessionListener( mock2 ) ); + assertFalse(eventSupport.hasSessionListener(mock2)); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - assertTrue( eventSupport.hasSessionListener( mock1 ) ); + assertTrue(eventSupport.hasSessionListener(mock1)); - assertTrue( eventSupport.hasSessionListener( mock2 ) ); + assertTrue(eventSupport.hasSessionListener(mock2)); - eventSupport.removeSessionListener( mock2 ); + eventSupport.removeSessionListener(mock2); - assertTrue( eventSupport.hasSessionListener( mock1 ) ); + assertTrue(eventSupport.hasSessionListener(mock1)); - assertFalse( eventSupport.hasSessionListener( mock2 ) ); + assertFalse(eventSupport.hasSessionListener(mock2)); - eventSupport.removeSessionListener( mock1 ); + eventSupport.removeSessionListener(mock1); - assertFalse( eventSupport.hasSessionListener( mock1 ) ); + assertFalse(eventSupport.hasSessionListener(mock1)); } - public void testFireSessionDisconnected() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireSessionDisconnected() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - final SessionEvent event = new SessionEvent( wagon, 1 ); + final SessionEvent event = new SessionEvent(wagon, 1); - mock1.sessionDisconnected( event ); - mock2.sessionDisconnected( event ); + mock1.sessionDisconnected(event); + mock2.sessionDisconnected(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireSessionDisconnected( event ); + eventSupport.fireSessionDisconnected(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireSessionDisconneting() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireSessionDisconneting() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - final SessionEvent event = new SessionEvent( wagon, 1 ); + final SessionEvent event = new SessionEvent(wagon, 1); - mock1.sessionDisconnecting( event ); - mock2.sessionDisconnecting( event ); + mock1.sessionDisconnecting(event); + mock2.sessionDisconnecting(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireSessionDisconnecting( event ); + eventSupport.fireSessionDisconnecting(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireSessionLoggedIn() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireSessionLoggedIn() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - final SessionEvent event = new SessionEvent( wagon, 1 ); + final SessionEvent event = new SessionEvent(wagon, 1); - mock1.sessionLoggedIn( event ); - mock2.sessionLoggedIn( event ); + mock1.sessionLoggedIn(event); + mock2.sessionLoggedIn(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireSessionLoggedIn( event ); + eventSupport.fireSessionLoggedIn(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireSessionLoggedOff() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireSessionLoggedOff() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - final SessionEvent event = new SessionEvent( wagon, 1 ); + final SessionEvent event = new SessionEvent(wagon, 1); - mock1.sessionLoggedOff( event ); - mock2.sessionLoggedOff( event ); + mock1.sessionLoggedOff(event); + mock2.sessionLoggedOff(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireSessionLoggedOff( event ); + eventSupport.fireSessionLoggedOff(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireSessionOpened() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireSessionOpened() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - final SessionEvent event = new SessionEvent( wagon, 1 ); + final SessionEvent event = new SessionEvent(wagon, 1); - mock1.sessionOpened( event ); - mock2.sessionOpened( event ); + mock1.sessionOpened(event); + mock2.sessionOpened(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireSessionOpened( event ); + eventSupport.fireSessionOpened(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireSessionOpenning() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireSessionOpenning() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - final SessionEvent event = new SessionEvent( wagon, 1 ); + final SessionEvent event = new SessionEvent(wagon, 1); - mock1.sessionOpening( event ); - mock2.sessionOpening( event ); + mock1.sessionOpening(event); + mock2.sessionOpening(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireSessionOpening( event ); + eventSupport.fireSessionOpening(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireSessionRefused() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireSessionRefused() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - final SessionEvent event = new SessionEvent( wagon, 1 ); + final SessionEvent event = new SessionEvent(wagon, 1); - mock1.sessionConnectionRefused( event ); - mock2.sessionConnectionRefused( event ); + mock1.sessionConnectionRefused(event); + mock2.sessionConnectionRefused(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireSessionConnectionRefused( event ); + eventSupport.fireSessionConnectionRefused(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireDebug() - { - SessionListener mock1 = createMock( SessionListener.class ); + public void testFireDebug() { + SessionListener mock1 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock1 ); + eventSupport.addSessionListener(mock1); - SessionListener mock2 = createMock( SessionListener.class ); + SessionListener mock2 = createMock(SessionListener.class); - eventSupport.addSessionListener( mock2 ); + eventSupport.addSessionListener(mock2); - mock1.debug( "mm" ); - mock2.debug( "mm" ); + mock1.debug("mm"); + mock2.debug("mm"); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireDebug( "mm" ); + eventSupport.fireDebug("mm"); - verify( mock1, mock2 ); + verify(mock1, mock2); } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventTest.java index 88155879a..16c95bcf9 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/SessionEventTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import junit.framework.TestCase; import org.apache.maven.wagon.ConnectionException; @@ -30,103 +29,92 @@ * @author Michal Maczka * */ -public class SessionEventTest - extends TestCase -{ +public class SessionEventTest extends TestCase { /* - * Class to test for void SESSIONEvent(Wagon, Repository, String, int, - * int) - */ - public void testSessionEventProperties() - throws ConnectionException, AuthenticationException - { - - final Wagon wagon = EasyMock.createMock( Wagon.class ); + * Class to test for void SESSIONEvent(Wagon, Repository, String, int, + * int) + */ + public void testSessionEventProperties() throws ConnectionException, AuthenticationException { + + final Wagon wagon = EasyMock.createMock(Wagon.class); final Repository repo = new Repository(); - wagon.connect( repo ); + wagon.connect(repo); final long timestamp = System.currentTimeMillis(); - final Exception exception = new AuthenticationException( "dummy" ); + final Exception exception = new AuthenticationException("dummy"); - SessionEvent event = new SessionEvent( wagon, SessionEvent.SESSION_CLOSED ); + SessionEvent event = new SessionEvent(wagon, SessionEvent.SESSION_CLOSED); - assertEquals( wagon, event.getWagon() ); + assertEquals(wagon, event.getWagon()); - assertEquals( SessionEvent.SESSION_CLOSED, event.getEventType() ); + assertEquals(SessionEvent.SESSION_CLOSED, event.getEventType()); - event = new SessionEvent( wagon, exception ); + event = new SessionEvent(wagon, exception); - assertEquals( wagon, event.getWagon() ); - assertEquals( SessionEvent.SESSION_ERROR_OCCURRED, event.getEventType() ); - assertEquals( exception, event.getException() ); + assertEquals(wagon, event.getWagon()); + assertEquals(SessionEvent.SESSION_ERROR_OCCURRED, event.getEventType()); + assertEquals(exception, event.getException()); - event.setException( null ); - assertEquals( null, event.getException() ); + event.setException(null); + assertEquals(null, event.getException()); - event.setException( exception ); - assertEquals( exception, event.getException() ); + event.setException(exception); + assertEquals(exception, event.getException()); - event.setTimestamp( timestamp ); - assertEquals( timestamp, event.getTimestamp() ); + event.setTimestamp(timestamp); + assertEquals(timestamp, event.getTimestamp()); - event.setEventType( SessionEvent.SESSION_CLOSED ); - assertEquals( SessionEvent.SESSION_CLOSED, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_CLOSED); + assertEquals(SessionEvent.SESSION_CLOSED, event.getEventType()); - event.setEventType( SessionEvent.SESSION_DISCONNECTED ); - assertEquals( SessionEvent.SESSION_DISCONNECTED, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_DISCONNECTED); + assertEquals(SessionEvent.SESSION_DISCONNECTED, event.getEventType()); - event.setEventType( SessionEvent.SESSION_DISCONNECTING ); - assertEquals( SessionEvent.SESSION_DISCONNECTING, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_DISCONNECTING); + assertEquals(SessionEvent.SESSION_DISCONNECTING, event.getEventType()); - event.setEventType( SessionEvent.SESSION_ERROR_OCCURRED ); - assertEquals( SessionEvent.SESSION_ERROR_OCCURRED, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_ERROR_OCCURRED); + assertEquals(SessionEvent.SESSION_ERROR_OCCURRED, event.getEventType()); - event.setEventType( SessionEvent.SESSION_LOGGED_IN ); - assertEquals( SessionEvent.SESSION_LOGGED_IN, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_LOGGED_IN); + assertEquals(SessionEvent.SESSION_LOGGED_IN, event.getEventType()); - event.setEventType( SessionEvent.SESSION_LOGGED_OFF ); - assertEquals( SessionEvent.SESSION_LOGGED_OFF, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_LOGGED_OFF); + assertEquals(SessionEvent.SESSION_LOGGED_OFF, event.getEventType()); - event.setEventType( SessionEvent.SESSION_OPENED ); - assertEquals( SessionEvent.SESSION_OPENED, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_OPENED); + assertEquals(SessionEvent.SESSION_OPENED, event.getEventType()); - event.setEventType( SessionEvent.SESSION_OPENING ); - assertEquals( SessionEvent.SESSION_OPENING, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_OPENING); + assertEquals(SessionEvent.SESSION_OPENING, event.getEventType()); - event.setEventType( SessionEvent.SESSION_CONNECTION_REFUSED ); - assertEquals( SessionEvent.SESSION_CONNECTION_REFUSED, event.getEventType() ); + event.setEventType(SessionEvent.SESSION_CONNECTION_REFUSED); + assertEquals(SessionEvent.SESSION_CONNECTION_REFUSED, event.getEventType()); - try - { - event.setEventType( -1 ); - fail( "Exception expected" ); + try { + event.setEventType(-1); + fail("Exception expected"); + } catch (IllegalArgumentException e) { + assertTrue(true); } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); - } - } - public void testConstantValueConflict() - { - final int[] values = {SessionEvent.SESSION_CLOSED, SessionEvent.SESSION_DISCONNECTED, - SessionEvent.SESSION_DISCONNECTING, SessionEvent.SESSION_ERROR_OCCURRED, - SessionEvent.SESSION_LOGGED_IN, SessionEvent.SESSION_LOGGED_OFF, - SessionEvent.SESSION_OPENED, SessionEvent.SESSION_OPENING, - SessionEvent.SESSION_CONNECTION_REFUSED}; + public void testConstantValueConflict() { + final int[] values = { + SessionEvent.SESSION_CLOSED, SessionEvent.SESSION_DISCONNECTED, + SessionEvent.SESSION_DISCONNECTING, SessionEvent.SESSION_ERROR_OCCURRED, + SessionEvent.SESSION_LOGGED_IN, SessionEvent.SESSION_LOGGED_OFF, + SessionEvent.SESSION_OPENED, SessionEvent.SESSION_OPENING, + SessionEvent.SESSION_CONNECTION_REFUSED + }; - for ( int i = 0; i < values.length; i++ ) - { - for ( int j = i + 1; j < values.length; j++ ) - { + for (int i = 0; i < values.length; i++) { + for (int j = i + 1; j < values.length; j++) { final String msg = "Value confict at [i,j]=[" + i + "," + j + "]"; - assertTrue( msg, values[i] != values[j] ); + assertTrue(msg, values[i] != values[j]); } } - } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventSupportTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventSupportTest.java index 79f83fa6c..147aadf7f 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventSupportTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventSupportTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import junit.framework.TestCase; import org.apache.maven.wagon.Wagon; @@ -29,9 +28,7 @@ /** * @author Michal Maczka */ -public class TransferEventSupportTest - extends TestCase -{ +public class TransferEventSupportTest extends TestCase { private TransferEventSupport eventSupport; private Wagon wagon; @@ -39,152 +36,141 @@ public class TransferEventSupportTest /** * @see junit.framework.TestCase#setUp() */ - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - + eventSupport = new TransferEventSupport(); - + // TODO: actually test it gets called? - wagon = EasyMock.createNiceMock( Wagon.class ); + wagon = EasyMock.createNiceMock(Wagon.class); } - public void testTransferListenerRegistration() - { - TransferListener mock1 = createMock( TransferListener.class ); - eventSupport.addTransferListener( mock1 ); + public void testTransferListenerRegistration() { + TransferListener mock1 = createMock(TransferListener.class); + eventSupport.addTransferListener(mock1); - assertTrue( eventSupport.hasTransferListener( mock1 ) ); - TransferListener mock2 = createMock( TransferListener.class ); + assertTrue(eventSupport.hasTransferListener(mock1)); + TransferListener mock2 = createMock(TransferListener.class); - assertFalse( eventSupport.hasTransferListener( mock2 ) ); + assertFalse(eventSupport.hasTransferListener(mock2)); - eventSupport.addTransferListener( mock2 ); + eventSupport.addTransferListener(mock2); - assertTrue( eventSupport.hasTransferListener( mock1 ) ); - assertTrue( eventSupport.hasTransferListener( mock2 ) ); + assertTrue(eventSupport.hasTransferListener(mock1)); + assertTrue(eventSupport.hasTransferListener(mock2)); - eventSupport.removeTransferListener( mock2 ); + eventSupport.removeTransferListener(mock2); - assertTrue( eventSupport.hasTransferListener( mock1 ) ); - assertFalse( eventSupport.hasTransferListener( mock2 ) ); + assertTrue(eventSupport.hasTransferListener(mock1)); + assertFalse(eventSupport.hasTransferListener(mock2)); - eventSupport.removeTransferListener( mock1 ); - assertFalse( eventSupport.hasTransferListener( mock1 ) ); + eventSupport.removeTransferListener(mock1); + assertFalse(eventSupport.hasTransferListener(mock1)); } - public void testFireTransferStarted() - { - TransferListener mock1 = createMock( TransferListener.class ); - eventSupport.addTransferListener( mock1 ); + public void testFireTransferStarted() { + TransferListener mock1 = createMock(TransferListener.class); + eventSupport.addTransferListener(mock1); - TransferListener mock2 = createMock( TransferListener.class ); - eventSupport.addTransferListener( mock2 ); + TransferListener mock2 = createMock(TransferListener.class); + eventSupport.addTransferListener(mock2); - final TransferEvent event = getEvent( wagon ); + final TransferEvent event = getEvent(wagon); - mock1.transferStarted( event ); - mock2.transferStarted( event ); + mock1.transferStarted(event); + mock2.transferStarted(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireTransferStarted( event ); + eventSupport.fireTransferStarted(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireTransferProgress() - { - TransferListener mock1 = createMock( TransferListener.class ); + public void testFireTransferProgress() { + TransferListener mock1 = createMock(TransferListener.class); - eventSupport.addTransferListener( mock1 ); + eventSupport.addTransferListener(mock1); - TransferListener mock2 = createMock( TransferListener.class ); + TransferListener mock2 = createMock(TransferListener.class); - eventSupport.addTransferListener( mock2 ); + eventSupport.addTransferListener(mock2); - final TransferEvent event = getEvent( wagon ); + final TransferEvent event = getEvent(wagon); final byte[] buffer = "content".getBytes(); - mock1.transferProgress( event, buffer, 0 ); - mock2.transferProgress( event, buffer, 0 ); + mock1.transferProgress(event, buffer, 0); + mock2.transferProgress(event, buffer, 0); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireTransferProgress( event, buffer , 0 ); + eventSupport.fireTransferProgress(event, buffer, 0); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireTransferCompleted() - { - TransferListener mock1 = createMock( TransferListener.class ); + public void testFireTransferCompleted() { + TransferListener mock1 = createMock(TransferListener.class); - eventSupport.addTransferListener( mock1 ); + eventSupport.addTransferListener(mock1); - TransferListener mock2 = createMock( TransferListener.class ); + TransferListener mock2 = createMock(TransferListener.class); - eventSupport.addTransferListener( mock2 ); + eventSupport.addTransferListener(mock2); - final TransferEvent event = getEvent( wagon ); + final TransferEvent event = getEvent(wagon); - mock1.transferCompleted( event ); - mock2.transferCompleted( event ); + mock1.transferCompleted(event); + mock2.transferCompleted(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireTransferCompleted( event ); + eventSupport.fireTransferCompleted(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireTransferError() - { - TransferListener mock1 = createMock( TransferListener.class ); + public void testFireTransferError() { + TransferListener mock1 = createMock(TransferListener.class); + + eventSupport.addTransferListener(mock1); - eventSupport.addTransferListener( mock1 ); + TransferListener mock2 = createMock(TransferListener.class); - TransferListener mock2 = createMock( TransferListener.class ); + eventSupport.addTransferListener(mock2); - eventSupport.addTransferListener( mock2 ); + final TransferEvent event = getEvent(wagon); - final TransferEvent event = getEvent( wagon ); - - mock1.transferError( event ); - mock2.transferError( event ); + mock1.transferError(event); + mock2.transferError(event); - replay( mock1, mock2 ); + replay(mock1, mock2); - eventSupport.fireTransferError( event ); + eventSupport.fireTransferError(event); - verify( mock1, mock2 ); + verify(mock1, mock2); } - public void testFireDebug() - { - TransferListener mock1 = createMock( TransferListener.class ); + public void testFireDebug() { + TransferListener mock1 = createMock(TransferListener.class); - eventSupport.addTransferListener( mock1 ); + eventSupport.addTransferListener(mock1); - TransferListener mock2 = createMock( TransferListener.class ); + TransferListener mock2 = createMock(TransferListener.class); - eventSupport.addTransferListener( mock2 ); + eventSupport.addTransferListener(mock2); - mock1.debug( "mm" ); - mock2.debug( "mm" ); + mock1.debug("mm"); + mock2.debug("mm"); - replay( mock1, mock2 ); - - eventSupport.fireDebug( "mm" ); + replay(mock1, mock2); - verify( mock1, mock2 ); - } + eventSupport.fireDebug("mm"); - private TransferEvent getEvent( final Wagon wagon ) - { - return new TransferEvent( wagon, new Resource(), TransferEvent.TRANSFER_COMPLETED, - TransferEvent.REQUEST_GET ); + verify(mock1, mock2); } + private TransferEvent getEvent(final Wagon wagon) { + return new TransferEvent(wagon, new Resource(), TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET); + } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventTest.java index 5df120b7d..e53cfc534 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/events/TransferEventTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.events; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.events; import junit.framework.TestCase; import org.apache.maven.wagon.ConnectionException; @@ -31,136 +30,122 @@ * @author Michal Maczka * */ -public class TransferEventTest - extends TestCase -{ +public class TransferEventTest extends TestCase { /* * Class to test for void TransferEvent(Wagon, Repository, String, int, * int) - */ - public void testTransferEventProperties() - throws ConnectionException, AuthenticationException - { - final Wagon wagon = EasyMock.createMock( Wagon.class ); + */ + public void testTransferEventProperties() throws ConnectionException, AuthenticationException { + final Wagon wagon = EasyMock.createMock(Wagon.class); final Repository repo = new Repository(); - wagon.connect( repo ); + wagon.connect(repo); final long timestamp = System.currentTimeMillis(); - final Exception exception = new AuthenticationException( "dummy" ); + final Exception exception = new AuthenticationException("dummy"); Resource resource = new Resource(); - resource.setName( "mm" ); + resource.setName("mm"); - TransferEvent event = new TransferEvent( wagon, resource, TransferEvent.TRANSFER_COMPLETED, - TransferEvent.REQUEST_GET ); + TransferEvent event = + new TransferEvent(wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET); - assertEquals( wagon, event.getWagon() ); + assertEquals(wagon, event.getWagon()); - assertEquals( "mm", event.getResource().getName() ); + assertEquals("mm", event.getResource().getName()); - assertEquals( TransferEvent.TRANSFER_COMPLETED, event.getEventType() ); + assertEquals(TransferEvent.TRANSFER_COMPLETED, event.getEventType()); - assertEquals( TransferEvent.REQUEST_GET, event.getRequestType() ); + assertEquals(TransferEvent.REQUEST_GET, event.getRequestType()); Resource res = new Resource(); - res.setName( "mm" ); + res.setName("mm"); - event = new TransferEvent( wagon, res, exception, TransferEvent.REQUEST_GET ); + event = new TransferEvent(wagon, res, exception, TransferEvent.REQUEST_GET); - assertEquals( wagon, event.getWagon() ); + assertEquals(wagon, event.getWagon()); - assertEquals( "mm", event.getResource().getName() ); + assertEquals("mm", event.getResource().getName()); - assertEquals( TransferEvent.TRANSFER_ERROR, event.getEventType() ); + assertEquals(TransferEvent.TRANSFER_ERROR, event.getEventType()); - assertEquals( TransferEvent.REQUEST_GET, event.getRequestType() ); + assertEquals(TransferEvent.REQUEST_GET, event.getRequestType()); - assertEquals( exception, event.getException() ); + assertEquals(exception, event.getException()); - event.setResource( null ); + event.setResource(null); - assertEquals( null, event.getResource() ); + assertEquals(null, event.getResource()); - res.setName( "/foo/baa" ); + res.setName("/foo/baa"); - event.setResource( res ); + event.setResource(res); - assertEquals( "/foo/baa", event.getResource().getName() ); + assertEquals("/foo/baa", event.getResource().getName()); - event.setTimestamp( timestamp ); + event.setTimestamp(timestamp); - assertEquals( timestamp, event.getTimestamp() ); + assertEquals(timestamp, event.getTimestamp()); - event.setRequestType( TransferEvent.REQUEST_PUT ); + event.setRequestType(TransferEvent.REQUEST_PUT); - assertEquals( TransferEvent.REQUEST_PUT, event.getRequestType() ); + assertEquals(TransferEvent.REQUEST_PUT, event.getRequestType()); - event.setRequestType( TransferEvent.REQUEST_GET ); + event.setRequestType(TransferEvent.REQUEST_GET); - assertEquals( TransferEvent.REQUEST_GET, event.getRequestType() ); + assertEquals(TransferEvent.REQUEST_GET, event.getRequestType()); - try - { - event.setRequestType( -1 ); + try { + event.setRequestType(-1); - fail( "Exception expected" ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); + fail("Exception expected"); + } catch (IllegalArgumentException e) { + assertTrue(true); } - event.setEventType( TransferEvent.TRANSFER_COMPLETED ); + event.setEventType(TransferEvent.TRANSFER_COMPLETED); - assertEquals( TransferEvent.TRANSFER_COMPLETED, event.getEventType() ); + assertEquals(TransferEvent.TRANSFER_COMPLETED, event.getEventType()); - event.setEventType( TransferEvent.TRANSFER_ERROR ); + event.setEventType(TransferEvent.TRANSFER_ERROR); - assertEquals( TransferEvent.TRANSFER_ERROR, event.getEventType() ); + assertEquals(TransferEvent.TRANSFER_ERROR, event.getEventType()); - event.setEventType( TransferEvent.TRANSFER_STARTED ); + event.setEventType(TransferEvent.TRANSFER_STARTED); - assertEquals( TransferEvent.TRANSFER_STARTED, event.getEventType() ); + assertEquals(TransferEvent.TRANSFER_STARTED, event.getEventType()); - event.setEventType( TransferEvent.TRANSFER_PROGRESS ); + event.setEventType(TransferEvent.TRANSFER_PROGRESS); - assertEquals( TransferEvent.TRANSFER_PROGRESS, event.getEventType() ); + assertEquals(TransferEvent.TRANSFER_PROGRESS, event.getEventType()); - try - { - event.setEventType( -1 ); + try { + event.setEventType(-1); - fail( "Exception expected" ); + fail("Exception expected"); + } catch (IllegalArgumentException e) { + assertTrue(true); } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); - } - } - public void testConstantValueConflict() - { - final int[] values = {TransferEvent.TRANSFER_COMPLETED, TransferEvent.TRANSFER_ERROR, - TransferEvent.TRANSFER_STARTED, TransferEvent.TRANSFER_PROGRESS, - TransferEvent.REQUEST_GET, TransferEvent.REQUEST_PUT}; + public void testConstantValueConflict() { + final int[] values = { + TransferEvent.TRANSFER_COMPLETED, TransferEvent.TRANSFER_ERROR, + TransferEvent.TRANSFER_STARTED, TransferEvent.TRANSFER_PROGRESS, + TransferEvent.REQUEST_GET, TransferEvent.REQUEST_PUT + }; - for ( int i = 0; i < values.length; i++ ) - { - for ( int j = i + 1; j < values.length; j++ ) - { + for (int i = 0; i < values.length; i++) { + for (int j = i + 1; j < values.length; j++) { final String msg = "Value confict at [i,j]=[" + i + "," + j + "]"; - assertTrue( msg, values[i] != values[j] ); + assertTrue(msg, values[i] != values[j]); } } - } - } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/observers/ChecksumObserverTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/observers/ChecksumObserverTest.java index d2c17db6e..911ad1c3a 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/observers/ChecksumObserverTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/observers/ChecksumObserverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.observers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.observers; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import junit.framework.TestCase; - -import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.TransferFailedException; import org.apache.maven.wagon.Wagon; @@ -36,88 +33,72 @@ import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; -public class ChecksumObserverTest - extends TestCase -{ +public class ChecksumObserverTest extends TestCase { private Wagon wagon; - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - wagon = new WagonMock( true ); + wagon = new WagonMock(true); Repository repository = new Repository(); - wagon.connect( repository ); + wagon.connect(repository); } - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { wagon.disconnect(); super.tearDown(); } public void testSubsequentTransfersAfterTransferError() - throws NoSuchAlgorithmException, ResourceDoesNotExistException, AuthorizationException, IOException - { + throws NoSuchAlgorithmException, ResourceDoesNotExistException, AuthorizationException, IOException { TransferListener listener = new ChecksumObserver(); - wagon.addTransferListener( listener ); + wagon.addTransferListener(listener); - File testFile = File.createTempFile( "wagon", "tmp" ); + File testFile = File.createTempFile("wagon", "tmp"); testFile.deleteOnExit(); - try - { - wagon.get( "resource", testFile ); + try { + wagon.get("resource", testFile); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } - try - { - wagon.get( "resource", testFile ); + try { + wagon.get("resource", testFile); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } testFile.delete(); } - public void testChecksum() - throws NoSuchAlgorithmException - { - ChecksumObserver listener = new ChecksumObserver( "SHA-1" ); + public void testChecksum() throws NoSuchAlgorithmException { + ChecksumObserver listener = new ChecksumObserver("SHA-1"); - Resource resource = new Resource( "resource" ); + Resource resource = new Resource("resource"); TransferEvent transferEvent = - new TransferEvent( wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET ); + new TransferEvent(wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET); - listener.transferInitiated( transferEvent ); + listener.transferInitiated(transferEvent); - transferEvent = new TransferEvent( wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_GET ); + transferEvent = new TransferEvent(wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_GET); - listener.transferStarted( transferEvent ); + listener.transferStarted(transferEvent); - transferEvent = new TransferEvent( wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_GET ); + transferEvent = new TransferEvent(wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_GET); - listener.transferProgress( transferEvent, "checksum\n".getBytes(), 9 ); + listener.transferProgress(transferEvent, "checksum\n".getBytes(), 9); - transferEvent = - new TransferEvent( wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET ); + transferEvent = new TransferEvent(wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET); - listener.transferCompleted( transferEvent ); + listener.transferCompleted(transferEvent); - assertEquals( "2e5daf0201ddeb068a62d5e08da18657ab2c6be9", listener.getActualChecksum() ); + assertEquals("2e5daf0201ddeb068a62d5e08da18657ab2c6be9", listener.getActualChecksum()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoTest.java index fbece3803..4ea306d18 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.proxy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.proxy; import junit.framework.TestCase; @@ -25,49 +24,41 @@ * @author Jason van Zyl * */ -public class ProxyInfoTest - extends TestCase -{ - public ProxyInfoTest( final String name ) - { - super( name ); +public class ProxyInfoTest extends TestCase { + public ProxyInfoTest(final String name) { + super(name); } - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); } - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } - public void testProxyInfoProperties() + public void testProxyInfoProperties() { - { final ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setUserName( "username" ); + proxyInfo.setUserName("username"); - assertEquals( "username", proxyInfo.getUserName() ); + assertEquals("username", proxyInfo.getUserName()); - proxyInfo.setPassword( "password" ); + proxyInfo.setPassword("password"); - assertEquals( "password", proxyInfo.getPassword() ); + assertEquals("password", proxyInfo.getPassword()); - proxyInfo.setHost( "http://www.ibiblio.org" ); + proxyInfo.setHost("http://www.ibiblio.org"); - assertEquals( "http://www.ibiblio.org", proxyInfo.getHost() ); + assertEquals("http://www.ibiblio.org", proxyInfo.getHost()); - proxyInfo.setPort( 0 ); + proxyInfo.setPort(0); - assertEquals( 0, proxyInfo.getPort() ); + assertEquals(0, proxyInfo.getPort()); - proxyInfo.setType( "SOCKSv4" ); + proxyInfo.setType("SOCKSv4"); - assertEquals( "SOCKSv4", proxyInfo.getType() ); + assertEquals("SOCKSv4", proxyInfo.getType()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoUtilsTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoUtilsTest.java index e506999a3..717f22eba 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoUtilsTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/proxy/ProxyInfoUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.proxy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,75 +16,66 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.proxy; import junit.framework.TestCase; /** * @author Thomas Champagne */ -public class ProxyInfoUtilsTest - extends TestCase -{ - public ProxyInfoUtilsTest( final String name ) - { - super( name ); +public class ProxyInfoUtilsTest extends TestCase { + public ProxyInfoUtilsTest(final String name) { + super(name); } - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); } - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } - public void testValidateNonProxyHostsWithNullProxy() - { - assertFalse( "www.ibiblio.org", ProxyUtils.validateNonProxyHosts( null, "maven.apache.org" ) ); + public void testValidateNonProxyHostsWithNullProxy() { + assertFalse("www.ibiblio.org", ProxyUtils.validateNonProxyHosts(null, "maven.apache.org")); } - public void testValidateNonProxyHostsWithUniqueHost() + public void testValidateNonProxyHostsWithUniqueHost() { - { final ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setUserName( "username" ); - proxyInfo.setPassword( "password" ); - proxyInfo.setHost( "http://www.ibiblio.org" ); - proxyInfo.setPort( 0 ); - proxyInfo.setType( "SOCKSv4" ); - proxyInfo.setNonProxyHosts( "*.apache.org" ); + proxyInfo.setUserName("username"); + proxyInfo.setPassword("password"); + proxyInfo.setHost("http://www.ibiblio.org"); + proxyInfo.setPort(0); + proxyInfo.setType("SOCKSv4"); + proxyInfo.setNonProxyHosts("*.apache.org"); - assertTrue( "maven.apache.org", ProxyUtils.validateNonProxyHosts( proxyInfo, "maven.apache.org" ) ); + assertTrue("maven.apache.org", ProxyUtils.validateNonProxyHosts(proxyInfo, "maven.apache.org")); - assertFalse( "www.ibiblio.org", ProxyUtils.validateNonProxyHosts( proxyInfo, "www.ibiblio.org" ) ); + assertFalse("www.ibiblio.org", ProxyUtils.validateNonProxyHosts(proxyInfo, "www.ibiblio.org")); - assertFalse( "null", ProxyUtils.validateNonProxyHosts( proxyInfo, null ) ); + assertFalse("null", ProxyUtils.validateNonProxyHosts(proxyInfo, null)); - proxyInfo.setNonProxyHosts( null ); - assertFalse( "NonProxyHosts = null", ProxyUtils.validateNonProxyHosts( proxyInfo, "maven.apache.org" ) ); + proxyInfo.setNonProxyHosts(null); + assertFalse("NonProxyHosts = null", ProxyUtils.validateNonProxyHosts(proxyInfo, "maven.apache.org")); - proxyInfo.setNonProxyHosts( "" ); - assertFalse( "NonProxyHosts = \"\"", ProxyUtils.validateNonProxyHosts( proxyInfo, "maven.apache.org" ) ); + proxyInfo.setNonProxyHosts(""); + assertFalse("NonProxyHosts = \"\"", ProxyUtils.validateNonProxyHosts(proxyInfo, "maven.apache.org")); } - public void testValidateNonProxyHostsWithMultipleHost() + public void testValidateNonProxyHostsWithMultipleHost() { - { final ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setUserName( "username" ); - proxyInfo.setPassword( "password" ); - proxyInfo.setHost( "http://www.ibiblio.org" ); - proxyInfo.setPort( 0 ); - proxyInfo.setType( "SOCKSv4" ); - proxyInfo.setNonProxyHosts( "*.apache.org|*.codehaus.org" ); + proxyInfo.setUserName("username"); + proxyInfo.setPassword("password"); + proxyInfo.setHost("http://www.ibiblio.org"); + proxyInfo.setPort(0); + proxyInfo.setType("SOCKSv4"); + proxyInfo.setNonProxyHosts("*.apache.org|*.codehaus.org"); - assertTrue( "maven.apache.org", ProxyUtils.validateNonProxyHosts( proxyInfo, "maven.apache.org" ) ); - assertTrue( "wiki.codehaus.org", ProxyUtils.validateNonProxyHosts( proxyInfo, "wiki.codehaus.org" ) ); + assertTrue("maven.apache.org", ProxyUtils.validateNonProxyHosts(proxyInfo, "maven.apache.org")); + assertTrue("wiki.codehaus.org", ProxyUtils.validateNonProxyHosts(proxyInfo, "wiki.codehaus.org")); - assertFalse( "www.ibiblio.org", ProxyUtils.validateNonProxyHosts( proxyInfo, "www.ibiblio.org" ) ); + assertFalse("www.ibiblio.org", ProxyUtils.validateNonProxyHosts(proxyInfo, "www.ibiblio.org")); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryPermissionsTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryPermissionsTest.java index 36d8ced79..b63563664 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryPermissionsTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryPermissionsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.repository; import junit.framework.TestCase; @@ -26,41 +25,32 @@ * * @todo test defaults */ -public class RepositoryPermissionsTest - extends TestCase -{ - public RepositoryPermissionsTest( final String name ) - { - super( name ); +public class RepositoryPermissionsTest extends TestCase { + public RepositoryPermissionsTest(final String name) { + super(name); } - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); } - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } - public void testAuthenticationInfoProperties() - { + public void testAuthenticationInfoProperties() { final RepositoryPermissions repositoryPermissions = new RepositoryPermissions(); - repositoryPermissions.setDirectoryMode( "directoryMode" ); - - assertEquals( "directoryMode", repositoryPermissions.getDirectoryMode() ); + repositoryPermissions.setDirectoryMode("directoryMode"); - repositoryPermissions.setFileMode( "fileMode" ); + assertEquals("directoryMode", repositoryPermissions.getDirectoryMode()); - assertEquals( "fileMode", repositoryPermissions.getFileMode() ); + repositoryPermissions.setFileMode("fileMode"); - repositoryPermissions.setGroup( "group" ); + assertEquals("fileMode", repositoryPermissions.getFileMode()); - assertEquals( "group", repositoryPermissions.getGroup() ); + repositoryPermissions.setGroup("group"); + assertEquals("group", repositoryPermissions.getGroup()); } } diff --git a/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryTest.java b/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryTest.java index bb85df0c6..4f6beba3e 100644 --- a/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryTest.java +++ b/wagon-provider-api/src/test/java/org/apache/maven/wagon/repository/RepositoryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,147 +16,226 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.repository; import junit.framework.TestCase; - import org.apache.maven.wagon.WagonConstants; /** * @author Jason van Zyl * */ -public class RepositoryTest - extends TestCase -{ - public RepositoryTest( final String name ) - { - super( name ); +public class RepositoryTest extends TestCase { + public RepositoryTest(final String name) { + super(name); } - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); } - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } - public void testRepositoryProperties() - throws Exception - { + public void testRepositoryProperties() throws Exception { Repository repository = new Repository(); - repository.setBasedir( "directory" ); - - assertEquals( "directory", repository.getBasedir() ); + repository.setBasedir("directory"); - repository.setName( "name" ); + assertEquals("directory", repository.getBasedir()); - assertEquals( "name", repository.getName() ); + repository.setName("name"); - repository.setPort( 0 ); + assertEquals("name", repository.getName()); - assertEquals( 0, repository.getPort() ); + repository.setPort(0); - assertEquals( "localhost", repository.getHost() ); + assertEquals(0, repository.getPort()); - repository.setUrl( "http://www.ibiblio.org" ); + assertEquals("localhost", repository.getHost()); - assertEquals( "http://www.ibiblio.org", repository.getUrl() ); + repository.setUrl("http://www.ibiblio.org"); - assertEquals( "http", repository.getProtocol() ); + assertEquals("http://www.ibiblio.org", repository.getUrl()); - assertEquals( "www.ibiblio.org", repository.getHost() ); + assertEquals("http", repository.getProtocol()); - assertEquals( "/", repository.getBasedir() ); + assertEquals("www.ibiblio.org", repository.getHost()); - assertEquals( WagonConstants.UNKNOWN_PORT, repository.getPort() ); + assertEquals("/", repository.getBasedir()); - repository.setUrl( "https://www.ibiblio.org:100/maven" ); + assertEquals(WagonConstants.UNKNOWN_PORT, repository.getPort()); - assertEquals( "https://www.ibiblio.org:100/maven", repository.getUrl() ); + repository.setUrl("https://www.ibiblio.org:100/maven"); - assertEquals( "https", repository.getProtocol() ); + assertEquals("https://www.ibiblio.org:100/maven", repository.getUrl()); - assertEquals( "www.ibiblio.org", repository.getHost() ); + assertEquals("https", repository.getProtocol()); - assertEquals( "/maven", repository.getBasedir() ); + assertEquals("www.ibiblio.org", repository.getHost()); - assertEquals( 100, repository.getPort() ); + assertEquals("/maven", repository.getBasedir()); - assertEquals( "www.ibiblio.org", repository.getHost() ); + assertEquals(100, repository.getPort()); - repository.setBasedir( "basedir" ); + assertEquals("www.ibiblio.org", repository.getHost()); - assertEquals( "basedir", repository.getBasedir() ); + repository.setBasedir("basedir"); - repository.setUrl( "http://brett:porter@www.ibiblio.org" ); + assertEquals("basedir", repository.getBasedir()); - assertEquals( "http://www.ibiblio.org", repository.getUrl() ); + repository.setUrl("http://brett:porter@www.ibiblio.org"); - repository.setUrl( "http://brett@www.ibiblio.org" ); + assertEquals("http://www.ibiblio.org", repository.getUrl()); - assertEquals( "http://www.ibiblio.org", repository.getUrl() ); + repository.setUrl("http://brett@www.ibiblio.org"); + assertEquals("http://www.ibiblio.org", repository.getUrl()); } - public void testIPv6() - { - assertRepository( "http://user:password@[fff:::1]:7891/oo/rest/users", "http://[fff:::1]:7891/oo/rest/users", - "/oo/rest/users", "user", "password", "fff:::1", 7891 ); - assertRepository( "http://[fff:::1]:7891/oo/rest/users", "http://[fff:::1]:7891/oo/rest/users", - "/oo/rest/users", null, null, "fff:::1", 7891 ); - assertRepository( "http://user:password@[fff:::1]/oo/rest/users", "http://[fff:::1]/oo/rest/users", - "/oo/rest/users", "user", "password", "fff:::1", -1 ); - assertRepository( "http://user:password@[fff:::1]:7891", "http://[fff:::1]:7891", "/", "user", "password", - "fff:::1", 7891 ); - - assertRepository( "http://user:password@[fff:000::222:1111]:7891/oo/rest/users", - "http://[fff:000::222:1111]:7891/oo/rest/users", "/oo/rest/users", "user", "password", - "fff:000::222:1111", 7891 ); - assertRepository( "http://[fff:000::222:1111]:7891/oo/rest/users", - "http://[fff:000::222:1111]:7891/oo/rest/users", "/oo/rest/users", null, null, - "fff:000::222:1111", 7891 ); - assertRepository( "http://user:password@[fff:000::222:1111]/oo/rest/users", - "http://[fff:000::222:1111]/oo/rest/users", "/oo/rest/users", "user", "password", - "fff:000::222:1111", -1 ); - assertRepository( "http://user:password@[fff:000::222:1111]:7891", "http://[fff:000::222:1111]:7891", "/", - "user", "password", "fff:000::222:1111", 7891 ); - - assertRepository( "http://user:password@16.60.56.58:7891/oo/rest/users", - "http://16.60.56.58:7891/oo/rest/users", "/oo/rest/users", "user", "password", "16.60.56.58", - 7891 ); - assertRepository( "http://16.60.56.58:7891/oo/rest/users", "http://16.60.56.58:7891/oo/rest/users", - "/oo/rest/users", null, null, "16.60.56.58", 7891 ); - assertRepository( "http://user:password@16.60.56.58/oo/rest/users", "http://16.60.56.58/oo/rest/users", - "/oo/rest/users", "user", "password", "16.60.56.58", -1 ); - assertRepository( "http://user:password@16.60.56.58:7891", "http://16.60.56.58:7891", "/", "user", "password", - "16.60.56.58", 7891 ); - - assertRepository( "http://user:password@16.60.56.58:7891/oo/rest/users", - "http://16.60.56.58:7891/oo/rest/users", "/oo/rest/users", "user", "password", "16.60.56.58", - 7891 ); - assertRepository( "http://16.60.56.58:7891/oo/rest/users", "http://16.60.56.58:7891/oo/rest/users", - "/oo/rest/users", null, null, "16.60.56.58", 7891 ); - assertRepository( "http://user:password@16.60.56.58/oo/rest/users", "http://16.60.56.58/oo/rest/users", - "/oo/rest/users", "user", "password", "16.60.56.58", -1 ); - assertRepository( "http://user:password@16.60.56.58:7891", "http://16.60.56.58:7891", "/", "user", "password", - "16.60.56.58", 7891 ); + public void testIPv6() { + assertRepository( + "http://user:password@[fff:::1]:7891/oo/rest/users", + "http://[fff:::1]:7891/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "fff:::1", + 7891); + assertRepository( + "http://[fff:::1]:7891/oo/rest/users", + "http://[fff:::1]:7891/oo/rest/users", + "/oo/rest/users", + null, + null, + "fff:::1", + 7891); + assertRepository( + "http://user:password@[fff:::1]/oo/rest/users", + "http://[fff:::1]/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "fff:::1", + -1); + assertRepository( + "http://user:password@[fff:::1]:7891", + "http://[fff:::1]:7891", + "/", + "user", + "password", + "fff:::1", + 7891); + + assertRepository( + "http://user:password@[fff:000::222:1111]:7891/oo/rest/users", + "http://[fff:000::222:1111]:7891/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "fff:000::222:1111", + 7891); + assertRepository( + "http://[fff:000::222:1111]:7891/oo/rest/users", + "http://[fff:000::222:1111]:7891/oo/rest/users", + "/oo/rest/users", + null, + null, + "fff:000::222:1111", + 7891); + assertRepository( + "http://user:password@[fff:000::222:1111]/oo/rest/users", + "http://[fff:000::222:1111]/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "fff:000::222:1111", + -1); + assertRepository( + "http://user:password@[fff:000::222:1111]:7891", + "http://[fff:000::222:1111]:7891", + "/", + "user", + "password", + "fff:000::222:1111", + 7891); + + assertRepository( + "http://user:password@16.60.56.58:7891/oo/rest/users", + "http://16.60.56.58:7891/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "16.60.56.58", + 7891); + assertRepository( + "http://16.60.56.58:7891/oo/rest/users", + "http://16.60.56.58:7891/oo/rest/users", + "/oo/rest/users", + null, + null, + "16.60.56.58", + 7891); + assertRepository( + "http://user:password@16.60.56.58/oo/rest/users", + "http://16.60.56.58/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "16.60.56.58", + -1); + assertRepository( + "http://user:password@16.60.56.58:7891", + "http://16.60.56.58:7891", + "/", + "user", + "password", + "16.60.56.58", + 7891); + + assertRepository( + "http://user:password@16.60.56.58:7891/oo/rest/users", + "http://16.60.56.58:7891/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "16.60.56.58", + 7891); + assertRepository( + "http://16.60.56.58:7891/oo/rest/users", + "http://16.60.56.58:7891/oo/rest/users", + "/oo/rest/users", + null, + null, + "16.60.56.58", + 7891); + assertRepository( + "http://user:password@16.60.56.58/oo/rest/users", + "http://16.60.56.58/oo/rest/users", + "/oo/rest/users", + "user", + "password", + "16.60.56.58", + -1); + assertRepository( + "http://user:password@16.60.56.58:7891", + "http://16.60.56.58:7891", + "/", + "user", + "password", + "16.60.56.58", + 7891); } - private void assertRepository( String url, String repoUrl, String baseDir, String user, String password, - String host, int port ) - { - Repository repo = new Repository( String.valueOf( System.currentTimeMillis() ), url ); - assertEquals( repoUrl, repo.getUrl() ); - assertEquals( baseDir, repo.getBasedir() ); - assertEquals( host, repo.getHost() ); - assertEquals( user, repo.getUsername() ); - assertEquals( password, repo.getPassword() ); - assertEquals( port, repo.getPort() ); + private void assertRepository( + String url, String repoUrl, String baseDir, String user, String password, String host, int port) { + Repository repo = new Repository(String.valueOf(System.currentTimeMillis()), url); + assertEquals(repoUrl, repo.getUrl()); + assertEquals(baseDir, repo.getBasedir()); + assertEquals(host, repo.getHost()); + assertEquals(user, repo.getUsername()); + assertEquals(password, repo.getPassword()); + assertEquals(port, repo.getPort()); } } diff --git a/wagon-provider-test/src/main/java/org/apache/maven/wagon/CommandExecutorTestCase.java b/wagon-provider-test/src/main/java/org/apache/maven/wagon/CommandExecutorTestCase.java index fd3b401f7..5c9210d89 100644 --- a/wagon-provider-test/src/main/java/org/apache/maven/wagon/CommandExecutorTestCase.java +++ b/wagon-provider-test/src/main/java/org/apache/maven/wagon/CommandExecutorTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; -import org.codehaus.plexus.PlexusTestCase; -import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.authentication.AuthenticationInfo; +import org.apache.maven.wagon.repository.Repository; +import org.codehaus.plexus.PlexusTestCase; /** * Base class for command executor tests. @@ -29,78 +28,59 @@ * @author Brett Porter * */ -public abstract class CommandExecutorTestCase - extends PlexusTestCase -{ - public void testErrorInCommandExecuted() - throws Exception - { - CommandExecutor exec = (CommandExecutor) lookup( CommandExecutor.ROLE ); +public abstract class CommandExecutorTestCase extends PlexusTestCase { + public void testErrorInCommandExecuted() throws Exception { + CommandExecutor exec = (CommandExecutor) lookup(CommandExecutor.ROLE); Repository repository = getTestRepository(); AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setUserName( System.getProperty( "user.name" ) ); + authenticationInfo.setUserName(System.getProperty("user.name")); - exec.connect( repository, authenticationInfo ); + exec.connect(repository, authenticationInfo); - try - { - exec.executeCommand( "fail" ); - fail( "Command should have failed" ); - } - catch ( CommandExecutionException e ) - { - assertTrue( e.getMessage().trim().endsWith( "fail: command not found" ) ); - } - finally - { + try { + exec.executeCommand("fail"); + fail("Command should have failed"); + } catch (CommandExecutionException e) { + assertTrue(e.getMessage().trim().endsWith("fail: command not found")); + } finally { exec.disconnect(); } } - public void testIgnoreFailuresInCommandExecuted() - throws Exception - { - CommandExecutor exec = (CommandExecutor) lookup( CommandExecutor.ROLE ); + public void testIgnoreFailuresInCommandExecuted() throws Exception { + CommandExecutor exec = (CommandExecutor) lookup(CommandExecutor.ROLE); Repository repository = getTestRepository(); AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setUserName( System.getProperty( "user.name" ) ); + authenticationInfo.setUserName(System.getProperty("user.name")); - exec.connect( repository, authenticationInfo ); + exec.connect(repository, authenticationInfo); - try - { - Streams streams = exec.executeCommand( "fail", true ); - //expect no exception, and stderr has something. - assertTrue( streams.getErr().length() > 0 ); - } - finally - { + try { + Streams streams = exec.executeCommand("fail", true); + // expect no exception, and stderr has something. + assertTrue(streams.getErr().length() > 0); + } finally { exec.disconnect(); } } - public void testExecuteSuccessfulCommand() - throws Exception - { - CommandExecutor exec = (CommandExecutor) lookup( CommandExecutor.ROLE ); + public void testExecuteSuccessfulCommand() throws Exception { + CommandExecutor exec = (CommandExecutor) lookup(CommandExecutor.ROLE); Repository repository = getTestRepository(); AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setUserName( System.getProperty( "user.name" ) ); + authenticationInfo.setUserName(System.getProperty("user.name")); - exec.connect( repository, authenticationInfo ); + exec.connect(repository, authenticationInfo); - try - { - exec.executeCommand( "ls" ); - } - finally - { + try { + exec.executeCommand("ls"); + } finally { exec.disconnect(); } } diff --git a/wagon-provider-test/src/main/java/org/apache/maven/wagon/FileTestUtils.java b/wagon-provider-test/src/main/java/org/apache/maven/wagon/FileTestUtils.java index 75aa3f0ea..80bcc69c4 100644 --- a/wagon-provider-test/src/main/java/org/apache/maven/wagon/FileTestUtils.java +++ b/wagon-provider-test/src/main/java/org/apache/maven/wagon/FileTestUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,101 +16,83 @@ * specific language governing permissions and limitations * under the License. */ - -import org.codehaus.plexus.util.FileUtils; +package org.apache.maven.wagon; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; +import org.codehaus.plexus.util.FileUtils; + /** * @author Brett Porter */ -public abstract class StreamingWagonTestCase - extends WagonTestCase -{ - public void testStreamingWagon() - throws Exception - { - if ( supportsGetIfNewer() ) - { +public abstract class StreamingWagonTestCase extends WagonTestCase { + public void testStreamingWagon() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); @@ -52,266 +46,221 @@ public void testStreamingWagon() } } - public void testFailedGetToStream() - throws Exception - { + public void testFailedGetToStream() throws Exception { setupWagonTestingFixtures(); setupRepositories(); - message( "Getting test artifact from test repository " + testRepository ); + message("Getting test artifact from test repository " + testRepository); StreamingWagon wagon = (StreamingWagon) getWagon(); - wagon.addTransferListener( checksumObserver ); + wagon.addTransferListener(checksumObserver); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); OutputStream stream = null; - try - { - stream = new FileOutputStream( destFile ); - wagon.getToStream( "fubar.txt", stream ); - fail( "File was found when it shouldn't have been" ); + try { + stream = new FileOutputStream(destFile); + wagon.getToStream("fubar.txt", stream); + fail("File was found when it shouldn't have been"); stream.close(); stream = null; - } - catch ( ResourceDoesNotExistException e ) - { + } catch (ResourceDoesNotExistException e) { // expected - assertTrue( true ); - } - finally - { - wagon.removeTransferListener( checksumObserver ); + assertTrue(true); + } finally { + wagon.removeTransferListener(checksumObserver); wagon.disconnect(); - IOUtil.close( stream ); + IOUtil.close(stream); tearDownWagonTestingFixtures(); } } - public void testWagonGetIfNewerToStreamIsNewer() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testWagonGetIfNewerToStreamIsNewer() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); int expectedSize = putFile(); // CHECKSTYLE_OFF: MagicNumber - getIfNewerToStream( getExpectedLastModifiedOnGet( testRepository, new Resource( resource ) ) + 30000, false, - expectedSize ); + getIfNewerToStream( + getExpectedLastModifiedOnGet(testRepository, new Resource(resource)) + 30000, false, expectedSize); // CHECKSTYLE_ON: MagicNumber } } - public void testWagonGetIfNewerToStreamIsOlder() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testWagonGetIfNewerToStreamIsOlder() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); int expectedSize = putFile(); - getIfNewerToStream( new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2006-01-01" ).getTime(), true, - expectedSize ); + getIfNewerToStream( + new SimpleDateFormat("yyyy-MM-dd").parse("2006-01-01").getTime(), true, expectedSize); } } - public void testWagonGetIfNewerToStreamIsSame() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testWagonGetIfNewerToStreamIsSame() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); int expectedSize = putFile(); - getIfNewerToStream( getExpectedLastModifiedOnGet( testRepository, new Resource( resource ) ), false, - expectedSize ); + getIfNewerToStream( + getExpectedLastModifiedOnGet(testRepository, new Resource(resource)), false, expectedSize); } } - private void getIfNewerToStream( long timestamp, boolean expectedResult, int expectedSize ) - throws Exception - { + private void getIfNewerToStream(long timestamp, boolean expectedResult, int expectedSize) throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); - ProgressAnswer progressAnswer = setupGetIfNewerTest( wagon, expectedResult, expectedSize ); + ProgressAnswer progressAnswer = setupGetIfNewerTest(wagon, expectedResult, expectedSize); - connectWagon( wagon ); + connectWagon(wagon); - OutputStream stream = new LazyFileOutputStream( destFile ); + OutputStream stream = new LazyFileOutputStream(destFile); - try - { - boolean result = wagon.getIfNewerToStream( this.resource, stream, timestamp ); - assertEquals( expectedResult, result ); - } - finally - { + try { + boolean result = wagon.getIfNewerToStream(this.resource, stream, timestamp); + assertEquals(expectedResult, result); + } finally { stream.close(); } - disconnectWagon( wagon ); + disconnectWagon(wagon); - assertGetIfNewerTest( progressAnswer, expectedResult, expectedSize ); + assertGetIfNewerTest(progressAnswer, expectedResult, expectedSize); tearDownWagonTestingFixtures(); } - public void testFailedGetIfNewerToStream() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testFailedGetIfNewerToStream() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); - message( "Getting test artifact from test repository " + testRepository ); + message("Getting test artifact from test repository " + testRepository); StreamingWagon wagon = (StreamingWagon) getWagon(); - wagon.addTransferListener( checksumObserver ); - wagon.connect( testRepository, getAuthInfo() ); - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + wagon.addTransferListener(checksumObserver); + wagon.connect(testRepository, getAuthInfo()); + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); OutputStream stream = null; - try - { - stream = new FileOutputStream( destFile ); - wagon.getIfNewerToStream( "fubar.txt", stream, 0 ); - fail( "File was found when it shouldn't have been" ); + try { + stream = new FileOutputStream(destFile); + wagon.getIfNewerToStream("fubar.txt", stream, 0); + fail("File was found when it shouldn't have been"); stream.close(); stream = null; - } - catch ( ResourceDoesNotExistException e ) - { + } catch (ResourceDoesNotExistException e) { // expected - assertTrue( true ); - } - finally - { - wagon.removeTransferListener( checksumObserver ); + assertTrue(true); + } finally { + wagon.removeTransferListener(checksumObserver); wagon.disconnect(); - IOUtil.close( stream ); + IOUtil.close(stream); tearDownWagonTestingFixtures(); } } } - protected void streamRoundTripTesting() - throws Exception - { - message( "Stream round trip testing ..." ); + protected void streamRoundTripTesting() throws Exception { + message("Stream round trip testing ..."); int expectedSize = putStream(); - assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() ); + assertNotNull("check checksum is not null", checksumObserver.getActualChecksum()); - assertEquals( "compare checksums", "6b144b7285ffd6b0bc8300da162120b9", checksumObserver.getActualChecksum() ); + assertEquals("compare checksums", "6b144b7285ffd6b0bc8300da162120b9", checksumObserver.getActualChecksum()); checksumObserver = new ChecksumObserver(); - getStream( expectedSize ); + getStream(expectedSize); - assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() ); + assertNotNull("check checksum is not null", checksumObserver.getActualChecksum()); - assertEquals( "compare checksums", "6b144b7285ffd6b0bc8300da162120b9", checksumObserver.getActualChecksum() ); + assertEquals("compare checksums", "6b144b7285ffd6b0bc8300da162120b9", checksumObserver.getActualChecksum()); // Now compare the conents of the artifact that was placed in // the repository with the contents of the artifact that was // retrieved from the repository. - String sourceContent = FileUtils.fileRead( sourceFile ); + String sourceContent = FileUtils.fileRead(sourceFile); - String destContent = FileUtils.fileRead( destFile ); + String destContent = FileUtils.fileRead(destFile); - assertEquals( sourceContent, destContent ); + assertEquals(sourceContent, destContent); } - private int putStream() - throws Exception - { + private int putStream() throws Exception { String content = "test-resource.txt\n"; - sourceFile = new File( FileTestUtils.getTestOutputDir(), "test-resource" ); + sourceFile = new File(FileTestUtils.getTestOutputDir(), "test-resource"); sourceFile.getParentFile().mkdirs(); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), content ); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), content); StreamingWagon wagon = (StreamingWagon) getWagon(); - ProgressAnswer progressAnswer = replayMockForPut( resource, content, wagon ); + ProgressAnswer progressAnswer = replayMockForPut(resource, content, wagon); - message( "Putting test artifact: " + resource + " into test repository " + testRepository ); + message("Putting test artifact: " + resource + " into test repository " + testRepository); - connectWagon( wagon ); + connectWagon(wagon); InputStream stream = null; - try - { - stream = new FileInputStream( sourceFile ); - wagon.putFromStream( stream, resource, sourceFile.length(), sourceFile.lastModified() ); + try { + stream = new FileInputStream(sourceFile); + wagon.putFromStream(stream, resource, sourceFile.length(), sourceFile.lastModified()); stream.close(); stream = null; - } - catch ( Exception e ) - { - logger.error( "error while putting resources to the FTP Server", e ); - } - finally - { - IOUtil.close( stream ); + } catch (Exception e) { + logger.error("error while putting resources to the FTP Server", e); + } finally { + IOUtil.close(stream); } - disconnectWagon( wagon ); + disconnectWagon(wagon); - verifyMock( progressAnswer, content.length() ); + verifyMock(progressAnswer, content.length()); return content.length(); } - private void getStream( int expectedSize ) - throws Exception - { - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + private void getStream(int expectedSize) throws Exception { + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); StreamingWagon wagon = (StreamingWagon) getWagon(); - ProgressAnswer progressAnswer = replaceMockForGet( wagon, expectedSize ); + ProgressAnswer progressAnswer = replaceMockForGet(wagon, expectedSize); - message( "Getting test artifact from test repository " + testRepository ); + message("Getting test artifact from test repository " + testRepository); - connectWagon( wagon ); + connectWagon(wagon); OutputStream stream = null; - try - { - stream = new FileOutputStream( destFile ); - wagon.getToStream( this.resource, stream ); + try { + stream = new FileOutputStream(destFile); + wagon.getToStream(this.resource, stream); stream.close(); stream = null; - } - catch ( Exception e ) - { - logger.error( "error while reading resources from the FTP Server", e ); - } - finally - { - IOUtil.close( stream ); + } catch (Exception e) { + logger.error("error while reading resources from the FTP Server", e); + } finally { + IOUtil.close(stream); } - disconnectWagon( wagon ); + disconnectWagon(wagon); - verifyMock( progressAnswer, expectedSize ); + verifyMock(progressAnswer, expectedSize); } } diff --git a/wagon-provider-test/src/main/java/org/apache/maven/wagon/WagonTestCase.java b/wagon-provider-test/src/main/java/org/apache/maven/wagon/WagonTestCase.java index e4c370caa..b0953cc55 100644 --- a/wagon-provider-test/src/main/java/org/apache/maven/wagon/WagonTestCase.java +++ b/wagon-provider-test/src/main/java/org/apache/maven/wagon/WagonTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.NoSuchAlgorithmException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authentication.AuthenticationInfo; @@ -33,52 +41,34 @@ import org.codehaus.plexus.util.FileUtils; import org.easymock.IAnswer; import org.junit.Assume; - -// CHECKSTYLE_OFF: AvoidStarImport -import static org.easymock.EasyMock.*; -//CHECKSTYLE_ON: AvoidStarImport - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import static org.easymock.EasyMock.*; /** * @author Jason van Zyl */ -public abstract class WagonTestCase - extends PlexusTestCase -{ - protected static Logger logger = LoggerFactory.getLogger( WagonTestCase.class ); +public abstract class WagonTestCase extends PlexusTestCase { + protected static Logger logger = LoggerFactory.getLogger(WagonTestCase.class); - - static final class ProgressAnswer implements IAnswer - { + static final class ProgressAnswer implements IAnswer { private int size; - public Object answer() throws Throwable - { + public Object answer() throws Throwable { int length = (Integer) getCurrentArguments()[2]; size += length; return null; } - public int getSize() - { + public int getSize() { return size; } } protected static final String TEST_CONTENT = "test-resource.txt\n"; - protected static final String TEST_CKSUM = cksum( TEST_CONTENT ); + protected static final String TEST_CKSUM = cksum(TEST_CONTENT); protected static final String POM = "pom.xml"; @@ -108,12 +98,10 @@ public int getSize() // Constructors // ---------------------------------------------------------------------- - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { checksumObserver = new ChecksumObserver(); - mockTransferListener = createMock( TransferListener.class ); + mockTransferListener = createMock(TransferListener.class); super.setUp(); } @@ -126,8 +114,7 @@ protected void setUp() * URL of the repository. For a complete test it should point to a non existing folder so we also check for the * creation of new folders in the remote site.

return the URL of the repository as specified by Wagon syntax */ - protected abstract String getTestRepositoryUrl() - throws IOException; + protected abstract String getTestRepositoryUrl() throws IOException; /** * Protocol id of the Wagon to use, eg. scp, ftp @@ -145,9 +132,7 @@ protected abstract String getTestRepositoryUrl() // repository url of file://${basedir}/target/file-repository. // ---------------------------------------------------------------------- - protected void setupRepositories() - throws Exception - { + protected void setupRepositories() throws Exception { resource = "test-resource"; // ---------------------------------------------------------------------- @@ -156,69 +141,56 @@ protected void setupRepositories() testRepository = new Repository(); - testRepository.setUrl( getTestRepositoryUrl() ); + testRepository.setUrl(getTestRepositoryUrl()); - testRepository.setPermissions( getPermissions() ); + testRepository.setPermissions(getPermissions()); // ---------------------------------------------------------------------- // Create a test local repository. // ---------------------------------------------------------------------- - File file = FileTestUtils.createDir( "local-repository" ); + File file = FileTestUtils.createDir("local-repository"); localRepositoryPath = file.getPath(); - localRepository = createFileRepository( file.toPath().toUri().toASCIIString() ); + localRepository = createFileRepository(file.toPath().toUri().toASCIIString()); - message( "Local repository: " + localRepository ); + message("Local repository: " + localRepository); - File f = new File( localRepositoryPath ); + File f = new File(localRepositoryPath); - if ( !f.exists() ) - { + if (!f.exists()) { f.mkdirs(); } } - protected void customizeContext() - throws Exception - { - getContainer().addContextValue( "test.repository", localRepositoryPath ); + protected void customizeContext() throws Exception { + getContainer().addContextValue("test.repository", localRepositoryPath); } - protected void setupWagonTestingFixtures() - throws Exception - { - } + protected void setupWagonTestingFixtures() throws Exception {} - protected void tearDownWagonTestingFixtures() - throws Exception - { - } + protected void tearDownWagonTestingFixtures() throws Exception {} // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { return new AuthenticationInfo(); } - protected RepositoryPermissions getPermissions() - { + protected RepositoryPermissions getPermissions() { return new RepositoryPermissions(); } - protected Wagon getWagon() - throws Exception - { - Wagon wagon = (Wagon) lookup( Wagon.ROLE, getProtocol() ); + protected Wagon getWagon() throws Exception { + Wagon wagon = (Wagon) lookup(Wagon.ROLE, getProtocol()); Debug debug = new Debug(); - wagon.addSessionListener( debug ); + wagon.addSessionListener(debug); - wagon.addTransferListener( debug ); + wagon.addTransferListener(debug); return wagon; } @@ -227,32 +199,25 @@ protected Wagon getWagon() * @param cmd the executable to run, not null. * @return true */ - public static boolean isSystemCmd( String cmd ) - { - try - { - Runtime.getRuntime().exec( cmd ); + public static boolean isSystemCmd(String cmd) { + try { + Runtime.getRuntime().exec(cmd); return true; - } - catch ( IOException e ) - { + } catch (IOException e) { return false; } } - protected void message( String message ) - { - logger.info( message ); + protected void message(String message) { + logger.info(message); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - public void testWagon() - throws Exception - { + public void testWagon() throws Exception { setupWagonTestingFixtures(); setupRepositories(); @@ -262,189 +227,157 @@ public void testWagon() tearDownWagonTestingFixtures(); } - public void testWagonGetIfNewerIsNewer() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testWagonGetIfNewerIsNewer() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); int expectedSize = putFile(); // CHECKSTYLE_OFF: MagicNumber - getIfNewer( getExpectedLastModifiedOnGet( testRepository, new Resource( resource ) ) + 30000, false, - expectedSize ); + getIfNewer( + getExpectedLastModifiedOnGet(testRepository, new Resource(resource)) + 30000, false, expectedSize); // CHECKSTYLE_ON: MagicNumber } } @Override - protected void runTest() - throws Throwable - { - if ( !testSkipped ) - { + protected void runTest() throws Throwable { + if (!testSkipped) { super.runTest(); } } - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return true; } - - public void testWagonGetIfNewerIsSame() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testWagonGetIfNewerIsSame() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); int expectedSize = putFile(); - getIfNewer( getExpectedLastModifiedOnGet( testRepository, new Resource( resource ) ), false, expectedSize ); + getIfNewer(getExpectedLastModifiedOnGet(testRepository, new Resource(resource)), false, expectedSize); } } - public void testWagonGetIfNewerIsOlder() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testWagonGetIfNewerIsOlder() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); int expectedSize = putFile(); - getIfNewer( new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2006-01-01" ).getTime(), true, expectedSize ); + getIfNewer(new SimpleDateFormat("yyyy-MM-dd").parse("2006-01-01").getTime(), true, expectedSize); } } - private void getIfNewer( long timestamp, boolean expectedResult, int expectedSize ) - throws Exception - { + private void getIfNewer(long timestamp, boolean expectedResult, int expectedSize) throws Exception { Wagon wagon = getWagon(); - ProgressAnswer progressAnswer = setupGetIfNewerTest( wagon, expectedResult, expectedSize ); + ProgressAnswer progressAnswer = setupGetIfNewerTest(wagon, expectedResult, expectedSize); - connectWagon( wagon ); + connectWagon(wagon); - boolean result = wagon.getIfNewer( this.resource, destFile, timestamp ); - assertEquals( expectedResult, result ); + boolean result = wagon.getIfNewer(this.resource, destFile, timestamp); + assertEquals(expectedResult, result); - disconnectWagon( wagon ); + disconnectWagon(wagon); - assertGetIfNewerTest( progressAnswer, expectedResult, expectedSize ); + assertGetIfNewerTest(progressAnswer, expectedResult, expectedSize); tearDownWagonTestingFixtures(); } - protected ProgressAnswer setupGetIfNewerTest( Wagon wagon, boolean expectedResult, int expectedSize ) - throws NoSuchAlgorithmException, IOException - { + protected ProgressAnswer setupGetIfNewerTest(Wagon wagon, boolean expectedResult, int expectedSize) + throws NoSuchAlgorithmException, IOException { checksumObserver = new ChecksumObserver(); - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.delete(); - assertFalse( destFile.exists() ); + assertFalse(destFile.exists()); destFile.deleteOnExit(); ProgressAnswer progressAnswer = null; - if ( expectedResult ) - { - progressAnswer = replaceMockForGet( wagon, expectedSize ); - } - else - { - replaceMockForSkippedGetIfNewer( wagon, expectedSize ); + if (expectedResult) { + progressAnswer = replaceMockForGet(wagon, expectedSize); + } else { + replaceMockForSkippedGetIfNewer(wagon, expectedSize); } return progressAnswer; } - protected void assertGetIfNewerTest( ProgressAnswer progressAnswer, boolean expectedResult, - int expectedSize ) - throws IOException - { - if ( expectedResult ) - { - verifyMock( progressAnswer, expectedSize ); + protected void assertGetIfNewerTest(ProgressAnswer progressAnswer, boolean expectedResult, int expectedSize) + throws IOException { + if (expectedResult) { + verifyMock(progressAnswer, expectedSize); - assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() ); + assertNotNull("check checksum is not null", checksumObserver.getActualChecksum()); - assertEquals( "compare checksums", TEST_CKSUM, - checksumObserver.getActualChecksum() ); + assertEquals("compare checksums", TEST_CKSUM, checksumObserver.getActualChecksum()); // Now compare the contents of the artifact that was placed in // the repository with the contents of the artifact that was // retrieved from the repository. - String sourceContent = FileUtils.fileRead( sourceFile ); - String destContent = FileUtils.fileRead( destFile ); - assertEquals( sourceContent, destContent ); - } - else - { - verify( mockTransferListener ); + String sourceContent = FileUtils.fileRead(sourceFile); + String destContent = FileUtils.fileRead(destFile); + assertEquals(sourceContent, destContent); + } else { + verify(mockTransferListener); - reset( mockTransferListener ); + reset(mockTransferListener); - assertNull( "check checksum is null", checksumObserver.getActualChecksum() ); + assertNull("check checksum is null", checksumObserver.getActualChecksum()); - assertFalse( destFile.exists() ); + assertFalse(destFile.exists()); } } - - private void replaceMockForSkippedGetIfNewer( Wagon wagon, int expectedSize ) - { - Resource resource = new Resource( this.resource ); - mockTransferListener.transferInitiated( - createTransferEvent( wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET, - destFile ) ); - resource = new Resource( this.resource ); - resource.setContentLength( getExpectedContentLengthOnGet( expectedSize ) ); - resource.setLastModified( getExpectedLastModifiedOnGet( testRepository, resource ) ); + private void replaceMockForSkippedGetIfNewer(Wagon wagon, int expectedSize) { + Resource resource = new Resource(this.resource); + mockTransferListener.transferInitiated(createTransferEvent( + wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET, destFile)); + resource = new Resource(this.resource); + resource.setContentLength(getExpectedContentLengthOnGet(expectedSize)); + resource.setLastModified(getExpectedLastModifiedOnGet(testRepository, resource)); // TODO: transfer skipped event? // mockTransferListener.transferSkipped( createTransferEvent( wagon, resource, TransferEvent.TRANSFER_STARTED, // TransferEvent.REQUEST_GET, destFile ) ); - mockTransferListener.debug( anyString() ); + mockTransferListener.debug(anyString()); expectLastCall().anyTimes(); - replay( mockTransferListener ); + replay(mockTransferListener); } - public void testWagonPutDirectory() - throws Exception - { + public void testWagonPutDirectory() throws Exception { setupWagonTestingFixtures(); setupRepositories(); Wagon wagon = getWagon(); - if ( wagon.supportsDirectoryCopy() ) - { - sourceFile = new File( FileTestUtils.getTestOutputDir(), "directory-copy" ); + if (wagon.supportsDirectoryCopy()) { + sourceFile = new File(FileTestUtils.getTestOutputDir(), "directory-copy"); - FileUtils.deleteDirectory( sourceFile ); + FileUtils.deleteDirectory(sourceFile); - writeTestFile( "test-resource-1.txt" ); - writeTestFile( "a/test-resource-2.txt" ); - writeTestFile( "a/b/test-resource-3.txt" ); - writeTestFile( "c/test-resource-4.txt" ); - writeTestFile( "d/e/f/test-resource-5.txt" ); + writeTestFile("test-resource-1.txt"); + writeTestFile("a/test-resource-2.txt"); + writeTestFile("a/b/test-resource-3.txt"); + writeTestFile("c/test-resource-4.txt"); + writeTestFile("d/e/f/test-resource-5.txt"); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - wagon.putDirectory( sourceFile, "directory-copy" ); + wagon.putDirectory(sourceFile, "directory-copy"); - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "directory-copy/test-resource-1.txt", destFile ); - wagon.get( "directory-copy/a/test-resource-2.txt", destFile ); - wagon.get( "directory-copy/a/b/test-resource-3.txt", destFile ); - wagon.get( "directory-copy/c/test-resource-4.txt", destFile ); - wagon.get( "directory-copy/d/e/f/test-resource-5.txt", destFile ); + wagon.get("directory-copy/test-resource-1.txt", destFile); + wagon.get("directory-copy/a/test-resource-2.txt", destFile); + wagon.get("directory-copy/a/b/test-resource-3.txt", destFile); + wagon.get("directory-copy/c/test-resource-4.txt", destFile); + wagon.get("directory-copy/d/e/f/test-resource-5.txt", destFile); wagon.disconnect(); } @@ -459,40 +392,37 @@ public void testWagonPutDirectory() * @throws Exception * @since 1.0-beta-2 */ - public void testWagonPutDirectoryDeepDestination() - throws Exception - { + public void testWagonPutDirectoryDeepDestination() throws Exception { setupWagonTestingFixtures(); setupRepositories(); Wagon wagon = getWagon(); - if ( wagon.supportsDirectoryCopy() ) - { - sourceFile = new File( FileTestUtils.getTestOutputDir(), "deep0/deep1/deep2" ); + if (wagon.supportsDirectoryCopy()) { + sourceFile = new File(FileTestUtils.getTestOutputDir(), "deep0/deep1/deep2"); - FileUtils.deleteDirectory( sourceFile ); + FileUtils.deleteDirectory(sourceFile); - writeTestFile( "test-resource-1.txt" ); - writeTestFile( "a/test-resource-2.txt" ); - writeTestFile( "a/b/test-resource-3.txt" ); - writeTestFile( "c/test-resource-4.txt" ); - writeTestFile( "d/e/f/test-resource-5.txt" ); + writeTestFile("test-resource-1.txt"); + writeTestFile("a/test-resource-2.txt"); + writeTestFile("a/b/test-resource-3.txt"); + writeTestFile("c/test-resource-4.txt"); + writeTestFile("d/e/f/test-resource-5.txt"); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - wagon.putDirectory( sourceFile, "deep0/deep1/deep2" ); + wagon.putDirectory(sourceFile, "deep0/deep1/deep2"); - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "deep0/deep1/deep2/test-resource-1.txt", destFile ); - wagon.get( "deep0/deep1/deep2/a/test-resource-2.txt", destFile ); - wagon.get( "deep0/deep1/deep2/a/b/test-resource-3.txt", destFile ); - wagon.get( "deep0/deep1/deep2/c/test-resource-4.txt", destFile ); - wagon.get( "deep0/deep1/deep2/d/e/f/test-resource-5.txt", destFile ); + wagon.get("deep0/deep1/deep2/test-resource-1.txt", destFile); + wagon.get("deep0/deep1/deep2/a/test-resource-2.txt", destFile); + wagon.get("deep0/deep1/deep2/a/b/test-resource-3.txt", destFile); + wagon.get("deep0/deep1/deep2/c/test-resource-4.txt", destFile); + wagon.get("deep0/deep1/deep2/d/e/f/test-resource-5.txt", destFile); wagon.disconnect(); } @@ -506,15 +436,13 @@ public void testWagonPutDirectoryDeepDestination() * @throws Exception * @since 1.0-beta-1 */ - public void testWagonPutDirectoryWhenDirectoryAlreadyExists() - throws Exception - { + public void testWagonPutDirectoryWhenDirectoryAlreadyExists() throws Exception { final String dirName = "directory-copy-existing"; final String resourceToCreate = "test-resource-1.txt"; - final String[] resources = { "a/test-resource-2.txt", "a/b/test-resource-3.txt", "c/test-resource-4.txt" }; + final String[] resources = {"a/test-resource-2.txt", "a/b/test-resource-3.txt", "c/test-resource-4.txt"}; setupWagonTestingFixtures(); @@ -522,32 +450,29 @@ public void testWagonPutDirectoryWhenDirectoryAlreadyExists() Wagon wagon = getWagon(); - if ( wagon.supportsDirectoryCopy() ) - { - sourceFile = new File( FileTestUtils.getTestOutputDir(), dirName ); + if (wagon.supportsDirectoryCopy()) { + sourceFile = new File(FileTestUtils.getTestOutputDir(), dirName); - FileUtils.deleteDirectory( sourceFile ); + FileUtils.deleteDirectory(sourceFile); - createDirectory( wagon, resourceToCreate, dirName ); + createDirectory(wagon, resourceToCreate, dirName); - for ( String resource : resources ) - { - writeTestFile( resource ); + for (String resource : resources) { + writeTestFile(resource); } - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - wagon.putDirectory( sourceFile, dirName ); + wagon.putDirectory(sourceFile, dirName); - List resourceNames = new ArrayList<>( resources.length + 1 ); + List resourceNames = new ArrayList<>(resources.length + 1); - resourceNames.add( dirName + "/" + resourceToCreate ); - for ( String resource : resources ) - { - resourceNames.add( dirName + "/" + resource ); + resourceNames.add(dirName + "/" + resourceToCreate); + for (String resource : resources) { + resourceNames.add(dirName + "/" + resource); } - assertResourcesAreInRemoteSide( wagon, resourceNames ); + assertResourcesAreInRemoteSide(wagon, resourceNames); wagon.disconnect(); } @@ -561,12 +486,10 @@ public void testWagonPutDirectoryWhenDirectoryAlreadyExists() * @throws Exception * @since 1.0-beta-1 */ - public void testWagonPutDirectoryForDot() - throws Exception - { + public void testWagonPutDirectoryForDot() throws Exception { final String resourceToCreate = "test-resource-1.txt"; - final String[] resources = { "a/test-resource-2.txt", "a/b/test-resource-3.txt", "c/test-resource-4.txt" }; + final String[] resources = {"a/test-resource-2.txt", "a/b/test-resource-3.txt", "c/test-resource-4.txt"}; setupWagonTestingFixtures(); @@ -574,29 +497,27 @@ public void testWagonPutDirectoryForDot() Wagon wagon = getWagon(); - if ( wagon.supportsDirectoryCopy() ) - { - sourceFile = new File( FileTestUtils.getTestOutputDir(), "dot-repo" ); + if (wagon.supportsDirectoryCopy()) { + sourceFile = new File(FileTestUtils.getTestOutputDir(), "dot-repo"); - FileUtils.deleteDirectory( sourceFile ); + FileUtils.deleteDirectory(sourceFile); - createDirectory( wagon, resourceToCreate, "." ); + createDirectory(wagon, resourceToCreate, "."); - for ( String resource : resources ) - { - writeTestFile( resource ); + for (String resource : resources) { + writeTestFile(resource); } - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - wagon.putDirectory( sourceFile, "." ); + wagon.putDirectory(sourceFile, "."); - List resourceNames = new ArrayList<>( resources.length + 1 ); + List resourceNames = new ArrayList<>(resources.length + 1); - resourceNames.add( resourceToCreate ); - Collections.addAll( resourceNames, resources ); + resourceNames.add(resourceToCreate); + Collections.addAll(resourceNames, resources); - assertResourcesAreInRemoteSide( wagon, resourceNames ); + assertResourcesAreInRemoteSide(wagon, resourceNames); wagon.disconnect(); } @@ -612,22 +533,18 @@ public void testWagonPutDirectoryForDot() * @param dirName directory name to create * @throws Exception */ - protected void createDirectory( Wagon wagon, String resourceToCreate, String dirName ) - throws Exception - { - writeTestFile( resourceToCreate ); + protected void createDirectory(Wagon wagon, String resourceToCreate, String dirName) throws Exception { + writeTestFile(resourceToCreate); } - protected void assertResourcesAreInRemoteSide( Wagon wagon, List resourceNames ) - throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - for ( String resourceName : resourceNames ) - { - File destFile = FileTestUtils.createUniqueFile( getName(), resourceName ); + protected void assertResourcesAreInRemoteSide(Wagon wagon, List resourceNames) + throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + for (String resourceName : resourceNames) { + File destFile = FileTestUtils.createUniqueFile(getName(), resourceName); destFile.deleteOnExit(); - wagon.get( resourceName, destFile ); + wagon.get(resourceName, destFile); } } @@ -641,65 +558,50 @@ protected void assertResourcesAreInRemoteSide( Wagon wagon, List resourc * @throws TransferFailedException * @since 1.0-beta-1 */ - protected void assertNotExists( Wagon wagon, String resourceName ) - throws IOException, TransferFailedException, AuthorizationException - { - File tmpFile = File.createTempFile( "wagon", null ); - try - { - wagon.get( resourceName, tmpFile ); - fail( "Resource exists: " + resourceName ); - } - catch ( ResourceDoesNotExistException e ) - { + protected void assertNotExists(Wagon wagon, String resourceName) + throws IOException, TransferFailedException, AuthorizationException { + File tmpFile = File.createTempFile("wagon", null); + try { + wagon.get(resourceName, tmpFile); + fail("Resource exists: " + resourceName); + } catch (ResourceDoesNotExistException e) { // ok - } - finally - { + } finally { tmpFile.delete(); } } - private void writeTestFile( String child ) - throws IOException - { - File dir = new File( sourceFile, child ); + private void writeTestFile(String child) throws IOException { + File dir = new File(sourceFile, child); dir.getParentFile().mkdirs(); - FileUtils.fileWrite( dir.getAbsolutePath(), child ); + FileUtils.fileWrite(dir.getAbsolutePath(), child); } - public void testFailedGet() - throws Exception - { + public void testFailedGet() throws Exception { setupWagonTestingFixtures(); setupRepositories(); - message( "Getting test artifact from test repository " + testRepository ); + message("Getting test artifact from test repository " + testRepository); Wagon wagon = getWagon(); - wagon.addTransferListener( checksumObserver ); + wagon.addTransferListener(checksumObserver); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - try - { - wagon.get( "fubar.txt", destFile ); - fail( "File was found when it shouldn't have been" ); - } - catch ( ResourceDoesNotExistException e ) - { + try { + wagon.get("fubar.txt", destFile); + fail("File was found when it shouldn't have been"); + } catch (ResourceDoesNotExistException e) { // expected - assertTrue( true ); - } - finally - { - wagon.removeTransferListener( checksumObserver ); + assertTrue(true); + } finally { + wagon.removeTransferListener(checksumObserver); wagon.disconnect(); @@ -707,32 +609,24 @@ public void testFailedGet() } } - public void testFailedGetIfNewer() - throws Exception - { - if ( supportsGetIfNewer() ) - { + public void testFailedGetIfNewer() throws Exception { + if (supportsGetIfNewer()) { setupWagonTestingFixtures(); setupRepositories(); - message( "Getting test artifact from test repository " + testRepository ); + message("Getting test artifact from test repository " + testRepository); Wagon wagon = getWagon(); - wagon.addTransferListener( checksumObserver ); - wagon.connect( testRepository, getAuthInfo() ); - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + wagon.addTransferListener(checksumObserver); + wagon.connect(testRepository, getAuthInfo()); + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - try - { - wagon.getIfNewer( "fubar.txt", destFile, 0 ); - fail( "File was found when it shouldn't have been" ); - } - catch ( ResourceDoesNotExistException e ) - { + try { + wagon.getIfNewer("fubar.txt", destFile, 0); + fail("File was found when it shouldn't have been"); + } catch (ResourceDoesNotExistException e) { // expected - assertTrue( true ); - } - finally - { - wagon.removeTransferListener( checksumObserver ); + assertTrue(true); + } finally { + wagon.removeTransferListener(checksumObserver); wagon.disconnect(); @@ -747,58 +641,50 @@ public void testFailedGetIfNewer() * @throws Exception * @since 1.0-beta-2 */ - public void testWagonGetFileList() - throws Exception - { + public void testWagonGetFileList() throws Exception { setupWagonTestingFixtures(); setupRepositories(); String dirName = "file-list"; - String filenames[] = - new String[]{ "test-resource.txt", "test-resource.pom", "test-resource b.txt", "more-resources.dat", - ".index.txt" }; + String filenames[] = new String[] { + "test-resource.txt", "test-resource.pom", "test-resource b.txt", "more-resources.dat", ".index.txt" + }; - for ( String filename : filenames ) - { - putFile( dirName + "/" + filename, dirName + "/" + filename, filename + "\n" ); + for (String filename : filenames) { + putFile(dirName + "/" + filename, dirName + "/" + filename, filename + "\n"); } Wagon wagon = getWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - try - { - List list = wagon.getFileList( dirName ); - assertNotNull( "file list should not be null.", list ); - assertTrue( "file list should contain more items (actually contains '" + list + "').", - list.size() >= filenames.length ); + try { + List list = wagon.getFileList(dirName); + assertNotNull("file list should not be null.", list); + assertTrue( + "file list should contain more items (actually contains '" + list + "').", + list.size() >= filenames.length); - for ( String filename : filenames ) - { - assertTrue( "Filename '" + filename + "' should be in list.", list.contains( filename ) ); + for (String filename : filenames) { + assertTrue("Filename '" + filename + "' should be in list.", list.contains(filename)); } // WAGON-250 - list = wagon.getFileList( "" ); - assertNotNull( "file list should not be null.", list ); - assertTrue( "file list should contain items (actually contains '" + list + "').", !list.isEmpty() ); - assertTrue( list.contains( "file-list/" ) ); - assertFalse( list.contains( "file-list" ) ); - assertFalse( list.contains( "." ) ); - assertFalse( list.contains( ".." ) ); - assertFalse( list.contains( "./" ) ); - assertFalse( list.contains( "../" ) ); - } - catch ( UnsupportedOperationException e ) - { + list = wagon.getFileList(""); + assertNotNull("file list should not be null.", list); + assertTrue("file list should contain items (actually contains '" + list + "').", !list.isEmpty()); + assertTrue(list.contains("file-list/")); + assertFalse(list.contains("file-list")); + assertFalse(list.contains(".")); + assertFalse(list.contains("..")); + assertFalse(list.contains("./")); + assertFalse(list.contains("../")); + } catch (UnsupportedOperationException e) { // Some providers don't support this - Assume.assumeFalse( false ); - } - finally - { + Assume.assumeFalse(false); + } finally { wagon.disconnect(); tearDownWagonTestingFixtures(); @@ -811,9 +697,7 @@ public void testWagonGetFileList() * @throws Exception * @since 1.0-beta-2 */ - public void testWagonGetFileListWhenDirectoryDoesNotExist() - throws Exception - { + public void testWagonGetFileListWhenDirectoryDoesNotExist() throws Exception { setupWagonTestingFixtures(); setupRepositories(); @@ -822,24 +706,17 @@ public void testWagonGetFileListWhenDirectoryDoesNotExist() Wagon wagon = getWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - try - { - wagon.getFileList( dirName ); - fail( "getFileList on unexisting directory must throw ResourceDoesNotExistException" ); - } - catch ( ResourceDoesNotExistException e ) - { + try { + wagon.getFileList(dirName); + fail("getFileList on unexisting directory must throw ResourceDoesNotExistException"); + } catch (ResourceDoesNotExistException e) { // expected - } - catch ( UnsupportedOperationException e ) - { + } catch (UnsupportedOperationException e) { // Some providers don't support this - Assume.assumeFalse( false ); - } - finally - { + Assume.assumeFalse(false); + } finally { wagon.disconnect(); tearDownWagonTestingFixtures(); @@ -852,9 +729,7 @@ public void testWagonGetFileListWhenDirectoryDoesNotExist() * @throws Exception * @since 1.0-beta-2 */ - public void testWagonResourceExists() - throws Exception - { + public void testWagonResourceExists() throws Exception { setupWagonTestingFixtures(); setupRepositories(); @@ -863,9 +738,9 @@ public void testWagonResourceExists() putFile(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - assertTrue( sourceFile.getName() + " does not exist", wagon.resourceExists( sourceFile.getName() ) ); + assertTrue(sourceFile.getName() + " does not exist", wagon.resourceExists(sourceFile.getName())); wagon.disconnect(); @@ -878,18 +753,16 @@ public void testWagonResourceExists() * @throws Exception * @since 1.0-beta-2 */ - public void testWagonResourceNotExists() - throws Exception - { + public void testWagonResourceNotExists() throws Exception { setupWagonTestingFixtures(); setupRepositories(); Wagon wagon = getWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - assertFalse( wagon.resourceExists( "a/bad/resource/name/that/should/not/exist.txt" ) ); + assertFalse(wagon.resourceExists("a/bad/resource/name/that/should/not/exist.txt")); wagon.disconnect(); @@ -903,122 +776,107 @@ public void testWagonResourceNotExists() // test repository that we have setup. // ---------------------------------------------------------------------- - protected void putFile( String resourceName, String testFileName, String content ) - throws Exception - { - sourceFile = new File( FileTestUtils.getTestOutputDir(), testFileName ); + protected void putFile(String resourceName, String testFileName, String content) throws Exception { + sourceFile = new File(FileTestUtils.getTestOutputDir(), testFileName); sourceFile.getParentFile().mkdirs(); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), content ); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), content); Wagon wagon = getWagon(); - ProgressAnswer progressAnswer = replayMockForPut( resourceName, content, wagon ); + ProgressAnswer progressAnswer = replayMockForPut(resourceName, content, wagon); - message( "Putting test artifact: " + resourceName + " into test repository " + testRepository ); + message("Putting test artifact: " + resourceName + " into test repository " + testRepository); - connectWagon( wagon ); + connectWagon(wagon); - wagon.put( sourceFile, resourceName ); + wagon.put(sourceFile, resourceName); - disconnectWagon( wagon ); + disconnectWagon(wagon); - verifyMock( progressAnswer, content.length() ); + verifyMock(progressAnswer, content.length()); } - protected ProgressAnswer replayMockForPut( String resourceName, String content, Wagon wagon ) - { - Resource resource = new Resource( resourceName ); - mockTransferListener.transferInitiated( - createTransferEvent( wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_PUT, - sourceFile ) ); - resource = new Resource( resourceName ); - resource.setContentLength( content.length() ); - resource.setLastModified( sourceFile.lastModified() ); - mockTransferListener.transferStarted( - createTransferEvent( wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_PUT, - sourceFile ) ); + protected ProgressAnswer replayMockForPut(String resourceName, String content, Wagon wagon) { + Resource resource = new Resource(resourceName); + mockTransferListener.transferInitiated(createTransferEvent( + wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_PUT, sourceFile)); + resource = new Resource(resourceName); + resource.setContentLength(content.length()); + resource.setLastModified(sourceFile.lastModified()); + mockTransferListener.transferStarted(createTransferEvent( + wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_PUT, sourceFile)); mockTransferListener.transferProgress( - eq( createTransferEvent( wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_PUT, - sourceFile ) ), anyObject( byte[].class ), anyInt() ); + eq(createTransferEvent( + wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_PUT, sourceFile)), + anyObject(byte[].class), + anyInt()); ProgressAnswer progressAnswer = new ProgressAnswer(); - expectLastCall().andStubAnswer( progressAnswer ); + expectLastCall().andStubAnswer(progressAnswer); - mockTransferListener.debug( anyString() ); + mockTransferListener.debug(anyString()); expectLastCall().anyTimes(); - mockTransferListener.transferCompleted( - createTransferEvent( wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_PUT, - sourceFile ) ); + mockTransferListener.transferCompleted(createTransferEvent( + wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_PUT, sourceFile)); - replay( mockTransferListener ); + replay(mockTransferListener); return progressAnswer; } - protected TransferEvent createTransferEvent( Wagon wagon, Resource resource, int eventType, int requestType, - File file ) - { - TransferEvent transferEvent = new TransferEvent( wagon, resource, eventType, requestType ); - transferEvent.setLocalFile( file ); + protected TransferEvent createTransferEvent( + Wagon wagon, Resource resource, int eventType, int requestType, File file) { + TransferEvent transferEvent = new TransferEvent(wagon, resource, eventType, requestType); + transferEvent.setLocalFile(file); return transferEvent; } - protected int putFile() - throws Exception - { + protected int putFile() throws Exception { String content = TEST_CONTENT; - putFile( resource, "test-resource", content ); + putFile(resource, "test-resource", content); return content.length(); } - protected void getFile( int expectedSize ) - throws Exception - { - destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + protected void getFile(int expectedSize) throws Exception { + destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); Wagon wagon = getWagon(); - ProgressAnswer progressAnswer = replaceMockForGet( wagon, expectedSize ); + ProgressAnswer progressAnswer = replaceMockForGet(wagon, expectedSize); - message( "Getting test artifact from test repository " + testRepository ); + message("Getting test artifact from test repository " + testRepository); - connectWagon( wagon ); + connectWagon(wagon); - wagon.get( this.resource, destFile ); + wagon.get(this.resource, destFile); - disconnectWagon( wagon ); + disconnectWagon(wagon); - verifyMock( progressAnswer, expectedSize ); + verifyMock(progressAnswer, expectedSize); } + protected void verifyMock(ProgressAnswer progressAnswer, int length) { + verify(mockTransferListener); - protected void verifyMock( ProgressAnswer progressAnswer, int length ) - { - verify( mockTransferListener ); - - assertEquals( length, progressAnswer.getSize() ); + assertEquals(length, progressAnswer.getSize()); - reset( mockTransferListener ); + reset(mockTransferListener); } - protected void disconnectWagon( Wagon wagon ) - throws ConnectionException - { - wagon.removeTransferListener( mockTransferListener ); + protected void disconnectWagon(Wagon wagon) throws ConnectionException { + wagon.removeTransferListener(mockTransferListener); - wagon.removeTransferListener( checksumObserver ); + wagon.removeTransferListener(checksumObserver); wagon.disconnect(); } - protected void connectWagon( Wagon wagon ) - throws ConnectionException, AuthenticationException - { - wagon.addTransferListener( checksumObserver ); + protected void connectWagon(Wagon wagon) throws ConnectionException, AuthenticationException { + wagon.addTransferListener(checksumObserver); - wagon.addTransferListener( mockTransferListener ); + wagon.addTransferListener(mockTransferListener); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); } /** @@ -1026,125 +884,109 @@ protected void connectWagon( Wagon wagon ) * some test (mock on transfertprogress call) relies on the fact that InputStream #read(byte[] b, int off, int len) * read all bytes. But javadoc says: "" */ - protected boolean assertOnTransferProgress() - { + protected boolean assertOnTransferProgress() { return false; } - protected ProgressAnswer replaceMockForGet( Wagon wagon, int expectedSize ) - { - Resource resource = new Resource( this.resource ); - mockTransferListener.transferInitiated( - createTransferEvent( wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET, - destFile ) ); - resource = new Resource( this.resource ); - resource.setContentLength( getExpectedContentLengthOnGet( expectedSize ) ); - resource.setLastModified( getExpectedLastModifiedOnGet( testRepository, resource ) ); + protected ProgressAnswer replaceMockForGet(Wagon wagon, int expectedSize) { + Resource resource = new Resource(this.resource); + mockTransferListener.transferInitiated(createTransferEvent( + wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET, destFile)); + resource = new Resource(this.resource); + resource.setContentLength(getExpectedContentLengthOnGet(expectedSize)); + resource.setLastModified(getExpectedLastModifiedOnGet(testRepository, resource)); TransferEvent te = - createTransferEvent( wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_GET, null ); - mockTransferListener.transferStarted( te ); + createTransferEvent(wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_GET, null); + mockTransferListener.transferStarted(te); mockTransferListener.transferProgress( - eq( new TransferEvent( wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_GET ) ), - anyObject( byte[].class ), anyInt() ); + eq(new TransferEvent(wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_GET)), + anyObject(byte[].class), + anyInt()); ProgressAnswer progressAnswer = new ProgressAnswer(); - if ( assertOnTransferProgress() ) - { - expectLastCall().andAnswer( progressAnswer ); - } - else - { - expectLastCall().andAnswer( progressAnswer ); + if (assertOnTransferProgress()) { + expectLastCall().andAnswer(progressAnswer); + } else { + expectLastCall().andAnswer(progressAnswer); expectLastCall().anyTimes(); } - mockTransferListener.debug( anyString() ); + mockTransferListener.debug(anyString()); expectLastCall().anyTimes(); - mockTransferListener.transferCompleted( - createTransferEvent( wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET, - destFile ) ); + mockTransferListener.transferCompleted(createTransferEvent( + wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET, destFile)); - replay( mockTransferListener ); + replay(mockTransferListener); return progressAnswer; } - protected int getExpectedContentLengthOnGet( int expectedSize ) - { + protected int getExpectedContentLengthOnGet(int expectedSize) { return expectedSize; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { // default implementation - prone to failing if the time between test file creation and completion of putFile() // cross the "second" boundary, causing the "remote" and local files to have different times. return sourceFile.lastModified(); } - protected void fileRoundTripTesting() - throws Exception - { - message( "File round trip testing ..." ); + protected void fileRoundTripTesting() throws Exception { + message("File round trip testing ..."); int expectedSize = putFile(); - assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() ); + assertNotNull("check checksum is not null", checksumObserver.getActualChecksum()); - assertEquals( "compare checksums", TEST_CKSUM, checksumObserver.getActualChecksum() ); + assertEquals("compare checksums", TEST_CKSUM, checksumObserver.getActualChecksum()); checksumObserver = new ChecksumObserver(); - getFile( expectedSize ); + getFile(expectedSize); - assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() ); + assertNotNull("check checksum is not null", checksumObserver.getActualChecksum()); - assertEquals( "compare checksums", TEST_CKSUM, checksumObserver.getActualChecksum() ); + assertEquals("compare checksums", TEST_CKSUM, checksumObserver.getActualChecksum()); // Now compare the conents of the artifact that was placed in // the repository with the contents of the artifact that was // retrieved from the repository. - String sourceContent = FileUtils.fileRead( sourceFile ); + String sourceContent = FileUtils.fileRead(sourceFile); - String destContent = FileUtils.fileRead( destFile ); + String destContent = FileUtils.fileRead(destFile); - assertEquals( sourceContent, destContent ); + assertEquals(sourceContent, destContent); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - protected Repository createFileRepository( String url ) - { - File path = new File( url.substring( 7 ) ); + protected Repository createFileRepository(String url) { + File path = new File(url.substring(7)); path.mkdirs(); Repository repository = new Repository(); - repository.setUrl( url ); + repository.setUrl(url); return repository; } - protected static String cksum( String content ) - { + protected static String cksum(String content) { String checkSum; - try - { + try { ChecksumObserver obs = new ChecksumObserver(); - byte[] buf = content.getBytes( StandardCharsets.ISO_8859_1 ); - obs.transferProgress( null, buf, buf.length ); - obs.transferCompleted( null ); + byte[] buf = content.getBytes(StandardCharsets.ISO_8859_1); + obs.transferProgress(null, buf, buf.length); + obs.transferCompleted(null); checkSum = obs.getActualChecksum(); - } - catch ( Exception e ) - { + } catch (Exception e) { checkSum = null; } return checkSum; } - } diff --git a/wagon-provider-test/src/main/java/org/apache/maven/wagon/http/HttpWagonTestCase.java b/wagon-provider-test/src/main/java/org/apache/maven/wagon/http/HttpWagonTestCase.java index dbabd8ecf..937d210e6 100644 --- a/wagon-provider-test/src/main/java/org/apache/maven/wagon/http/HttpWagonTestCase.java +++ b/wagon-provider-test/src/main/java/org/apache/maven/wagon/http/HttpWagonTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,31 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.http; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Method; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.GZIPOutputStream; import org.apache.maven.wagon.FileTestUtils; import org.apache.maven.wagon.ResourceDoesNotExistException; @@ -56,474 +79,364 @@ import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Password; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Method; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.GZIPOutputStream; - /** * */ -public abstract class HttpWagonTestCase - extends StreamingWagonTestCase -{ +public abstract class HttpWagonTestCase extends StreamingWagonTestCase { public static final int SC_TOO_MANY_REQUESTS = 429; private Server server; private ServerConnector connector; - protected int getLocalPort( Server server ) - { + protected int getLocalPort(Server server) { Connector connector = server.getConnectors()[0]; - return ( ( ServerConnector ) connector ).getLocalPort(); + return ((ServerConnector) connector).getLocalPort(); } - protected void setupWagonTestingFixtures() - throws Exception - { + protected void setupWagonTestingFixtures() throws Exception { // File round trip testing - File file = FileTestUtils.createUniqueFile( "local-repository", "test-resource" ); + File file = FileTestUtils.createUniqueFile("local-repository", "test-resource"); file.delete(); file.getParentFile().mkdirs(); File repositoryDirectory = getRepositoryDirectory(); - FileUtils.deleteDirectory( repositoryDirectory ); + FileUtils.deleteDirectory(repositoryDirectory); repositoryDirectory.mkdirs(); - server = new Server( ); - //connector = new ServerConnector( server, new HttpConnectionFactory( new HttpConfiguration() ) ); - //server.addConnector( connector ); - connector = addConnector( server ); + server = new Server(); + // connector = new ServerConnector( server, new HttpConnectionFactory( new HttpConfiguration() ) ); + // server.addConnector( connector ); + connector = addConnector(server); - PutHandler putHandler = new PutHandler( repositoryDirectory ); + PutHandler putHandler = new PutHandler(repositoryDirectory); - ServletContextHandler context = createContext( server, repositoryDirectory ); + ServletContextHandler context = createContext(server, repositoryDirectory); HandlerCollection handlers = new HandlerCollection(); - handlers.addHandler( putHandler ); - handlers.addHandler( context ); - server.setHandler( handlers ); + handlers.addHandler(putHandler); + handlers.addHandler(context); + server.setHandler(handlers); server.start(); } - protected final int getTestRepositoryPort() - { - if ( server == null ) - { + protected final int getTestRepositoryPort() { + if (server == null) { return 0; } return connector.getLocalPort(); } - protected ServletContextHandler createContext( Server server, File repositoryDirectory ) - throws IOException - { - ServletContextHandler root = new ServletContextHandler( ServletContextHandler.SESSIONS ); - root.setResourceBase( repositoryDirectory.getAbsolutePath() ); - ServletHolder servletHolder = new ServletHolder( new DefaultServlet() ); - root.addServlet( servletHolder, "/*" ); + protected ServletContextHandler createContext(Server server, File repositoryDirectory) throws IOException { + ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS); + root.setResourceBase(repositoryDirectory.getAbsolutePath()); + ServletHolder servletHolder = new ServletHolder(new DefaultServlet()); + root.addServlet(servletHolder, "/*"); return root; } - protected void tearDownWagonTestingFixtures() - throws Exception - { + protected void tearDownWagonTestingFixtures() throws Exception { server.stop(); } - public void testHttpHeaders() - throws Exception - { + public void testHttpHeaders() throws Exception { Properties headers = new Properties(); - headers.setProperty( "User-Agent", "Maven-Wagon/1.0" ); + headers.setProperty("User-Agent", "Maven-Wagon/1.0"); StreamingWagon wagon = (StreamingWagon) getWagon(); - setHttpConfiguration( wagon, headers, new Properties() ); + setHttpConfiguration(wagon, headers, new Properties()); - Server server = new Server( ); + Server server = new Server(); TestHeaderHandler handler = new TestHeaderHandler(); - server.setHandler( handler ); - ServerConnector serverConnector = addConnector( server ); + server.setHandler(handler); + ServerConnector serverConnector = addConnector(server); server.start(); - wagon.connect( - new Repository( "id", getProtocol() + "://localhost:" + serverConnector.getLocalPort() ) ); + wagon.connect(new Repository("id", getProtocol() + "://localhost:" + serverConnector.getLocalPort())); - wagon.getToStream( "resource", new ByteArrayOutputStream() ); + wagon.getToStream("resource", new ByteArrayOutputStream()); wagon.disconnect(); server.stop(); - assertEquals( "Maven-Wagon/1.0", handler.headers.get( "User-Agent" ) ); + assertEquals("Maven-Wagon/1.0", handler.headers.get("User-Agent")); } /** * test set of User-Agent as it's done by aether wagon connector with using setHttpHeaders */ - public void testHttpHeadersWithCommonMethods() - throws Exception - { + public void testHttpHeadersWithCommonMethods() throws Exception { Properties properties = new Properties(); - properties.setProperty( "User-Agent", "Maven-Wagon/1.0" ); + properties.setProperty("User-Agent", "Maven-Wagon/1.0"); StreamingWagon wagon = (StreamingWagon) getWagon(); - Method setHttpHeaders = wagon.getClass().getMethod( "setHttpHeaders", Properties.class ); - setHttpHeaders.invoke( wagon, properties ); + Method setHttpHeaders = wagon.getClass().getMethod("setHttpHeaders", Properties.class); + setHttpHeaders.invoke(wagon, properties); - Server server = new Server( ); - ServerConnector serverConnector = addConnector( server ); + Server server = new Server(); + ServerConnector serverConnector = addConnector(server); TestHeaderHandler handler = new TestHeaderHandler(); - server.setHandler( handler ); - addConnector( server ); + server.setHandler(handler); + addConnector(server); server.start(); - wagon.connect( - new Repository( "id", getProtocol() + "://localhost:" + serverConnector.getLocalPort() ) ); + wagon.connect(new Repository("id", getProtocol() + "://localhost:" + serverConnector.getLocalPort())); - wagon.getToStream( "resource", new ByteArrayOutputStream() ); + wagon.getToStream("resource", new ByteArrayOutputStream()); wagon.disconnect(); server.stop(); - assertEquals( "Maven-Wagon/1.0", handler.headers.get( "User-Agent" ) ); + assertEquals("Maven-Wagon/1.0", handler.headers.get("User-Agent")); } - public void testUserAgentHeaderIsPresentByDefault() - throws Exception - { + public void testUserAgentHeaderIsPresentByDefault() throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); - Server server = new Server( ); + Server server = new Server(); TestHeaderHandler handler = new TestHeaderHandler(); - server.setHandler( handler ); - addConnector( server ); + server.setHandler(handler); + addConnector(server); server.start(); - wagon.connect( new Repository( "id", getProtocol() + "://localhost:" + getLocalPort( server ) ) ); - wagon.getToStream( "resource", new ByteArrayOutputStream() ); + wagon.connect(new Repository("id", getProtocol() + "://localhost:" + getLocalPort(server))); + wagon.getToStream("resource", new ByteArrayOutputStream()); wagon.disconnect(); server.stop(); - assertNotNull( "default User-Agent header of wagon provider should be present", - handler.headers.get( "User-Agent" ) ); + assertNotNull( + "default User-Agent header of wagon provider should be present", handler.headers.get("User-Agent")); } - public void testUserAgentHeaderIsPresentOnlyOnceIfSetMultipleTimes() - throws Exception - { + public void testUserAgentHeaderIsPresentOnlyOnceIfSetMultipleTimes() throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); // 1. set User-Agent header via HttpConfiguration Properties headers1 = new Properties(); - headers1.setProperty( "User-Agent", "test-user-agent" ); - setHttpConfiguration( wagon, headers1, new Properties() ); + headers1.setProperty("User-Agent", "test-user-agent"); + setHttpConfiguration(wagon, headers1, new Properties()); // 2. redundantly set User-Agent header via setHttpHeaders() Properties headers2 = new Properties(); - headers2.setProperty( "User-Agent", "test-user-agent" ); - Method setHttpHeaders = wagon.getClass().getMethod( "setHttpHeaders", Properties.class ); - setHttpHeaders.invoke( wagon, headers2 ); + headers2.setProperty("User-Agent", "test-user-agent"); + Method setHttpHeaders = wagon.getClass().getMethod("setHttpHeaders", Properties.class); + setHttpHeaders.invoke(wagon, headers2); - Server server = new Server( ); + Server server = new Server(); TestHeaderHandler handler = new TestHeaderHandler(); - server.setHandler( handler ); - addConnector( server ); + server.setHandler(handler); + addConnector(server); server.start(); - wagon.connect( new Repository( "id", getProtocol() + "://localhost:" + getLocalPort( server ) ) ); - wagon.getToStream( "resource", new ByteArrayOutputStream() ); + wagon.connect(new Repository("id", getProtocol() + "://localhost:" + getLocalPort(server))); + wagon.getToStream("resource", new ByteArrayOutputStream()); wagon.disconnect(); server.stop(); - assertEquals( "test-user-agent", handler.headers.get( "User-Agent" ) ); - + assertEquals("test-user-agent", handler.headers.get("User-Agent")); } - protected abstract void setHttpConfiguration( StreamingWagon wagon, Properties headers, Properties params ); + protected abstract void setHttpConfiguration(StreamingWagon wagon, Properties headers, Properties params); - protected ServerConnector addConnector( Server server ) - { + protected ServerConnector addConnector(Server server) { ServerConnector serverConnector = - new ServerConnector( server, new HttpConnectionFactory( new HttpConfiguration() ) ); - server.addConnector( serverConnector ); + new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration())); + server.addConnector(serverConnector); return serverConnector; } - protected String getRepositoryUrl( Server server ) - { - int localPort = getLocalPort( server ); + protected String getRepositoryUrl(Server server) { + int localPort = getLocalPort(server); return getProtocol() + "://localhost:" + localPort; } - public void testGetForbidden() - throws Exception - { - try - { - runTestGet( HttpServletResponse.SC_FORBIDDEN ); + public void testGetForbidden() throws Exception { + try { + runTestGet(HttpServletResponse.SC_FORBIDDEN); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testGet404() - throws Exception - { - try - { - runTestGet( HttpServletResponse.SC_NOT_FOUND ); + public void testGet404() throws Exception { + try { + runTestGet(HttpServletResponse.SC_NOT_FOUND); fail(); - } - catch ( ResourceDoesNotExistException e ) - { - assertTrue( true ); + } catch (ResourceDoesNotExistException e) { + assertTrue(true); } } - public void testGet500() - throws Exception - { - try - { - runTestGet( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + public void testGet500() throws Exception { + try { + runTestGet(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } } - private void runTestGet( int status ) - throws Exception - { + private void runTestGet(int status) throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); - Server server = createStatusServer( status ); + Server server = createStatusServer(status); server.start(); - String baseUrl = getRepositoryUrl( server ); + String baseUrl = getRepositoryUrl(server); String resourceName = "resource"; - String serverReasonPhrase = HttpStatus.getCode( status ).getMessage(); + String serverReasonPhrase = HttpStatus.getCode(status).getMessage(); - wagon.connect( new Repository( "id", baseUrl ) ); + wagon.connect(new Repository("id", baseUrl)); - try - { - wagon.getToStream( "resource", new ByteArrayOutputStream() ); + try { + wagon.getToStream("resource", new ByteArrayOutputStream()); fail(); - } - catch ( Exception e ) - { - verifyWagonExceptionMessage( e, status, baseUrl + "/" + resourceName, serverReasonPhrase ); + } catch (Exception e) { + verifyWagonExceptionMessage(e, status, baseUrl + "/" + resourceName, serverReasonPhrase); throw e; - } - finally - { + } finally { wagon.disconnect(); server.stop(); } } - public void testResourceExistsForbidden() - throws Exception - { - try - { - runTestResourceExists( HttpServletResponse.SC_FORBIDDEN ); + public void testResourceExistsForbidden() throws Exception { + try { + runTestResourceExists(HttpServletResponse.SC_FORBIDDEN); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testResourceExists404() - throws Exception - { - try - { - assertFalse( runTestResourceExists( HttpServletResponse.SC_NOT_FOUND ) ); - } - catch ( ResourceDoesNotExistException e ) - { - assertTrue( true ); + public void testResourceExists404() throws Exception { + try { + assertFalse(runTestResourceExists(HttpServletResponse.SC_NOT_FOUND)); + } catch (ResourceDoesNotExistException e) { + assertTrue(true); } } - public void testResourceExists500() - throws Exception - { - try - { - runTestResourceExists( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + public void testResourceExists500() throws Exception { + try { + runTestResourceExists(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } } - public void testResourceExists429() - throws Exception - { - try - { + public void testResourceExists429() throws Exception { + try { final AtomicBoolean called = new AtomicBoolean(); - AbstractHandler handler = new AbstractHandler() - { - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { - if ( called.get() ) - { - response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - baseRequest.setHandled( true ); - } - else - { - called.set( true ); - response.setStatus( SC_TOO_MANY_REQUESTS ); - baseRequest.setHandled( true ); + AbstractHandler handler = new AbstractHandler() { + public void handle( + String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + if (called.get()) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + baseRequest.setHandled(true); + } else { + called.set(true); + response.setStatus(SC_TOO_MANY_REQUESTS); + baseRequest.setHandled(true); } } }; StreamingWagon wagon = (StreamingWagon) getWagon(); - Server server = new Server( ); - server.setHandler( handler ); - addConnector( server ); + Server server = new Server(); + server.setHandler(handler); + addConnector(server); server.start(); - wagon.connect( new Repository( "id", getRepositoryUrl( server ) ) ); + wagon.connect(new Repository("id", getRepositoryUrl(server))); - try - { - wagon.resourceExists( "resource" ); - } - finally - { + try { + wagon.resourceExists("resource"); + } finally { wagon.disconnect(); server.stop(); } fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } } - - private boolean runTestResourceExists( int status ) - throws Exception - { + private boolean runTestResourceExists(int status) throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); - Server server = createStatusServer( status ); + Server server = createStatusServer(status); server.start(); - wagon.connect( new Repository( "id", getRepositoryUrl( server ) ) ); + wagon.connect(new Repository("id", getRepositoryUrl(server))); - try - { - return wagon.resourceExists( "resource" ); - } - finally - { + try { + return wagon.resourceExists("resource"); + } finally { wagon.disconnect(); server.stop(); } } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - File file = new File( getRepositoryDirectory(), resource.getName() ); - return ( file.lastModified() / 1000 ) * 1000; + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + File file = new File(getRepositoryDirectory(), resource.getName()); + return (file.lastModified() / 1000) * 1000; } - protected File getRepositoryDirectory() - { - return getTestFile( "target/test-output/http-repository" ); + protected File getRepositoryDirectory() { + return getTestFile("target/test-output/http-repository"); } - public void testGzipGet() - throws Exception - { - Server server = new Server( ); + public void testGzipGet() throws Exception { + Server server = new Server(); String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - ServletContextHandler root = new ServletContextHandler( ServletContextHandler.SESSIONS ); - root.setResourceBase( localRepositoryPath ); - ServletHolder servletHolder = new ServletHolder( new DefaultServlet() ); - servletHolder.setInitParameter( "gzip", "true" ); - root.addServlet( servletHolder, "/*" ); - addConnector( server ); - server.setHandler( root ); + ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS); + root.setResourceBase(localRepositoryPath); + ServletHolder servletHolder = new ServletHolder(new DefaultServlet()); + servletHolder.setInitParameter("gzip", "true"); + root.addServlet(servletHolder, "/*"); + addConnector(server); + server.setHandler(root); server.start(); - try - { + try { Wagon wagon = getWagon(); - Repository testRepository = new Repository( "id", getRepositoryUrl( server ) ); + Repository testRepository = new Repository("id", getRepositoryUrl(server)); - File sourceFile = new File( localRepositoryPath + "/gzip" ); + File sourceFile = new File(localRepositoryPath + "/gzip"); sourceFile.deleteOnExit(); String resName = "gzip-res.txt"; - String sourceContent = writeTestFile( sourceFile, resName, "gzip" ); + String sourceContent = writeTestFile(sourceFile, resName, "gzip"); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + File destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "gzip/" + resName, destFile ); + wagon.get("gzip/" + resName, destFile); wagon.disconnect(); - String destContent = FileUtils.fileRead( destFile ); + String destContent = FileUtils.fileRead(destFile); - assertEquals( sourceContent, destContent ); - } - finally - { + assertEquals(sourceContent, destContent); + } finally { server.stop(); } } @@ -578,127 +491,106 @@ public void testDeflateGet() } }*/ - public void testProxiedRequest() - throws Exception - { + public void testProxiedRequest() throws Exception { ProxyInfo proxyInfo = createProxyInfo(); TestHeaderHandler handler = new TestHeaderHandler(); - runTestProxiedRequest( proxyInfo, handler ); + runTestProxiedRequest(proxyInfo, handler); } - public void testProxiedRequestWithAuthentication() - throws Exception - { + public void testProxiedRequestWithAuthentication() throws Exception { ProxyInfo proxyInfo = createProxyInfo(); - proxyInfo.setUserName( "user" ); - proxyInfo.setPassword( "secret" ); + proxyInfo.setUserName("user"); + proxyInfo.setPassword("secret"); AuthorizingProxyHandler handler = new AuthorizingProxyHandler(); - runTestProxiedRequest( proxyInfo, handler ); + runTestProxiedRequest(proxyInfo, handler); - assertTrue( handler.headers.containsKey( "Proxy-Authorization" ) ); + assertTrue(handler.headers.containsKey("Proxy-Authorization")); - if ( supportProxyPreemptiveAuthentication() ) - { - assertEquals( HttpServletResponse.SC_OK, handler.handlerRequestResponses.get( 0 ).responseCode ); - } - else - { - assertEquals( HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, - handler.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( HttpServletResponse.SC_OK, handler.handlerRequestResponses.get( 1 ).responseCode ); + if (supportProxyPreemptiveAuthentication()) { + assertEquals(HttpServletResponse.SC_OK, handler.handlerRequestResponses.get(0).responseCode); + } else { + assertEquals( + HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, + handler.handlerRequestResponses.get(0).responseCode); + assertEquals(HttpServletResponse.SC_OK, handler.handlerRequestResponses.get(1).responseCode); } - } - public void testProxiedRequestWithAuthenticationWithProvider() - throws Exception - { + public void testProxiedRequestWithAuthenticationWithProvider() throws Exception { final ProxyInfo proxyInfo = createProxyInfo(); - proxyInfo.setUserName( "user" ); - proxyInfo.setPassword( "secret" ); + proxyInfo.setUserName("user"); + proxyInfo.setPassword("secret"); AuthorizingProxyHandler handler = new AuthorizingProxyHandler(); - ProxyInfoProvider proxyInfoProvider = new ProxyInfoProvider() - { - public ProxyInfo getProxyInfo( String protocol ) - { + ProxyInfoProvider proxyInfoProvider = new ProxyInfoProvider() { + public ProxyInfo getProxyInfo(String protocol) { return proxyInfo; } }; - runTestProxiedRequestWithProvider( proxyInfoProvider, handler ); + runTestProxiedRequestWithProvider(proxyInfoProvider, handler); - assertTrue( handler.headers.containsKey( "Proxy-Authorization" ) ); + assertTrue(handler.headers.containsKey("Proxy-Authorization")); - if ( supportProxyPreemptiveAuthentication() ) - { - assertEquals( HttpServletResponse.SC_OK, handler.handlerRequestResponses.get( 0 ).responseCode ); - } - else - { - assertEquals( HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, - handler.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( HttpServletResponse.SC_OK, handler.handlerRequestResponses.get( 1 ).responseCode ); + if (supportProxyPreemptiveAuthentication()) { + assertEquals(HttpServletResponse.SC_OK, handler.handlerRequestResponses.get(0).responseCode); + } else { + assertEquals( + HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, + handler.handlerRequestResponses.get(0).responseCode); + assertEquals(HttpServletResponse.SC_OK, handler.handlerRequestResponses.get(1).responseCode); } - } - public void testRedirectGetToStream() - throws Exception - { + public void testRedirectGetToStream() throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); - Server realServer = new Server( ); + Server realServer = new Server(); TestHeaderHandler handler = new TestHeaderHandler(); - realServer.setHandler( handler ); - addConnector( realServer ); + realServer.setHandler(handler); + addConnector(realServer); realServer.start(); - Server redirectServer = new Server( ); + Server redirectServer = new Server(); - addConnector( redirectServer ); + addConnector(redirectServer); String protocol = getProtocol(); // protocol is wagon protocol but in fact dav is http(s) - if ( protocol.equals( "dav" ) ) - { + if (protocol.equals("dav")) { protocol = "http"; } - if ( protocol.equals( "davs" ) ) - { + if (protocol.equals("davs")) { protocol = "https"; } - String redirectUrl = protocol + "://localhost:" + getLocalPort( realServer ); + String redirectUrl = protocol + "://localhost:" + getLocalPort(realServer); RedirectHandler redirectHandler = - new RedirectHandler( "See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, null ); + new RedirectHandler("See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, null); - redirectServer.setHandler( redirectHandler ); + redirectServer.setHandler(redirectHandler); redirectServer.start(); - wagon.connect( new Repository( "id", getRepositoryUrl( redirectServer ) ) ); + wagon.connect(new Repository("id", getRepositoryUrl(redirectServer))); - File tmpResult = File.createTempFile( "foo", "get" ); + File tmpResult = File.createTempFile("foo", "get"); - try ( FileOutputStream fileOutputStream = new FileOutputStream( tmpResult ) ) - { - wagon.getToStream( "resource", fileOutputStream ); + try (FileOutputStream fileOutputStream = new FileOutputStream(tmpResult)) { + wagon.getToStream("resource", fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); - String found = FileUtils.fileRead( tmpResult ); - assertEquals( "found:'" + found + "'", "Hello, World!", found ); + String found = FileUtils.fileRead(tmpResult); + assertEquals("found:'" + found + "'", "Hello, World!", found); - checkHandlerResult( redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER ); - checkHandlerResult( handler.handlerRequestResponses, HttpServletResponse.SC_OK ); - } - finally - { + checkHandlerResult(redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER); + checkHandlerResult(handler.handlerRequestResponses, HttpServletResponse.SC_OK); + } finally { wagon.disconnect(); redirectServer.stop(); @@ -708,59 +600,52 @@ public void testRedirectGetToStream() } } - public void testRedirectGet() - throws Exception - { + public void testRedirectGet() throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); - Server realServer = new Server( ); + Server realServer = new Server(); TestHeaderHandler handler = new TestHeaderHandler(); - realServer.setHandler( handler ); - addConnector( realServer ); + realServer.setHandler(handler); + addConnector(realServer); realServer.start(); - Server redirectServer = new Server( ); + Server redirectServer = new Server(); - addConnector( redirectServer ); + addConnector(redirectServer); String protocol = getProtocol(); // protocol is wagon protocol but in fact dav is http(s) - if ( protocol.equals( "dav" ) ) - { + if (protocol.equals("dav")) { protocol = "http"; } - if ( protocol.equals( "davs" ) ) - { + if (protocol.equals("davs")) { protocol = "https"; } - String redirectUrl = protocol + "://localhost:" + getLocalPort( realServer ); + String redirectUrl = protocol + "://localhost:" + getLocalPort(realServer); RedirectHandler redirectHandler = - new RedirectHandler( "See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, null ); + new RedirectHandler("See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, null); - redirectServer.setHandler( redirectHandler ); + redirectServer.setHandler(redirectHandler); redirectServer.start(); - wagon.connect( new Repository( "id", getRepositoryUrl( redirectServer ) ) ); + wagon.connect(new Repository("id", getRepositoryUrl(redirectServer))); - File tmpResult = File.createTempFile( "foo", "get" ); + File tmpResult = File.createTempFile("foo", "get"); - try - { - wagon.get( "resource", tmpResult ); - String found = FileUtils.fileRead( tmpResult ); - assertEquals( "found:'" + found + "'", "Hello, World!", found ); + try { + wagon.get("resource", tmpResult); + String found = FileUtils.fileRead(tmpResult); + assertEquals("found:'" + found + "'", "Hello, World!", found); - checkHandlerResult( redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER ); - checkHandlerResult( handler.handlerRequestResponses, HttpServletResponse.SC_OK ); - } - finally - { + checkHandlerResult(redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER); + checkHandlerResult(handler.handlerRequestResponses, HttpServletResponse.SC_OK); + } finally { wagon.disconnect(); redirectServer.stop(); @@ -770,400 +655,340 @@ public void testRedirectGet() } } + public void testRedirectPutFromStreamWithFullUrl() throws Exception { + Server realServer = new Server(); - public void testRedirectPutFromStreamWithFullUrl() - throws Exception - { - Server realServer = new Server( ); - - addConnector( realServer ); + addConnector(realServer); File repositoryDirectory = getRepositoryDirectory(); - FileUtils.deleteDirectory( repositoryDirectory ); + FileUtils.deleteDirectory(repositoryDirectory); repositoryDirectory.mkdirs(); - PutHandler putHandler = new PutHandler( repositoryDirectory ); + PutHandler putHandler = new PutHandler(repositoryDirectory); - realServer.setHandler( putHandler ); + realServer.setHandler(putHandler); realServer.start(); - Server redirectServer = new Server( ); + Server redirectServer = new Server(); - addConnector( redirectServer ); + addConnector(redirectServer); String protocol = getProtocol(); // protocol is wagon protocol but in fact dav is http(s) - if ( protocol.equals( "dav" ) ) - { + if (protocol.equals("dav")) { protocol = "http"; } - if ( protocol.equals( "davs" ) ) - { + if (protocol.equals("davs")) { protocol = "https"; } - String redirectUrl = protocol + "://localhost:" + getLocalPort( realServer ); + String redirectUrl = protocol + "://localhost:" + getLocalPort(realServer); RedirectHandler redirectHandler = - new RedirectHandler( "See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, repositoryDirectory ); + new RedirectHandler("See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, repositoryDirectory); - redirectServer.setHandler( redirectHandler ); + redirectServer.setHandler(redirectHandler); redirectServer.start(); - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository repository = new Repository( "foo", getRepositoryUrl( redirectServer ) ); - wagon.connect( repository ); + Repository repository = new Repository("foo", getRepositoryUrl(redirectServer)); + wagon.connect(repository); - File sourceFile = new File( repositoryDirectory, "test-secured-put-resource" ); + File sourceFile = new File(repositoryDirectory, "test-secured-put-resource"); sourceFile.delete(); - assertFalse( sourceFile.exists() ); + assertFalse(sourceFile.exists()); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); String content = "put top secret"; - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); - try ( FileInputStream fileInputStream = new FileInputStream( tempFile ) ) - { - wagon.putFromStream( fileInputStream, "test-secured-put-resource", content.length(), -1 ); - assertEquals( content, FileUtils.fileRead( sourceFile.getAbsolutePath() ) ); + try (FileInputStream fileInputStream = new FileInputStream(tempFile)) { + wagon.putFromStream(fileInputStream, "test-secured-put-resource", content.length(), -1); + assertEquals(content, FileUtils.fileRead(sourceFile.getAbsolutePath())); - checkRequestResponseForRedirectPutWithFullUrl( redirectHandler, putHandler ); - } - finally - { + checkRequestResponseForRedirectPutWithFullUrl(redirectHandler, putHandler); + } finally { wagon.disconnect(); tempFile.delete(); } - } - finally - { + } finally { realServer.stop(); redirectServer.stop(); } } - protected void checkRequestResponseForRedirectPutWithFullUrl( RedirectHandler redirectHandler, - PutHandler putHandler ) - { - checkHandlerResult( redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER ); - checkHandlerResult( putHandler.handlerRequestResponses, HttpServletResponse.SC_CREATED ); + protected void checkRequestResponseForRedirectPutWithFullUrl( + RedirectHandler redirectHandler, PutHandler putHandler) { + checkHandlerResult(redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER); + checkHandlerResult(putHandler.handlerRequestResponses, HttpServletResponse.SC_CREATED); } - public void testRedirectPutFromStreamRelativeUrl() - throws Exception - { - Server realServer = new Server( ); - addConnector( realServer ); + public void testRedirectPutFromStreamRelativeUrl() throws Exception { + Server realServer = new Server(); + addConnector(realServer); File repositoryDirectory = getRepositoryDirectory(); - FileUtils.deleteDirectory( repositoryDirectory ); + FileUtils.deleteDirectory(repositoryDirectory); repositoryDirectory.mkdirs(); - PutHandler putHandler = new PutHandler( repositoryDirectory ); + PutHandler putHandler = new PutHandler(repositoryDirectory); - realServer.setHandler( putHandler ); + realServer.setHandler(putHandler); realServer.start(); - Server redirectServer = new Server( ); + Server redirectServer = new Server(); - addConnector( redirectServer ); + addConnector(redirectServer); - RedirectHandler redirectHandler = - new RedirectHandler( "See Other", HttpServletResponse.SC_SEE_OTHER, "/redirectRequest/foo", - repositoryDirectory ); + RedirectHandler redirectHandler = new RedirectHandler( + "See Other", HttpServletResponse.SC_SEE_OTHER, "/redirectRequest/foo", repositoryDirectory); - redirectServer.setHandler( redirectHandler ); + redirectServer.setHandler(redirectHandler); redirectServer.start(); - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository repository = new Repository( "foo", getRepositoryUrl( redirectServer ) ); - wagon.connect( repository ); + Repository repository = new Repository("foo", getRepositoryUrl(redirectServer)); + wagon.connect(repository); - File sourceFile = new File( repositoryDirectory, "/redirectRequest/foo/test-secured-put-resource" ); + File sourceFile = new File(repositoryDirectory, "/redirectRequest/foo/test-secured-put-resource"); sourceFile.delete(); - assertFalse( sourceFile.exists() ); + assertFalse(sourceFile.exists()); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); String content = "put top secret"; - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); - try ( FileInputStream fileInputStream = new FileInputStream( tempFile ) ) - { - wagon.putFromStream( fileInputStream, "test-secured-put-resource", content.length(), -1 ); - assertEquals( content, FileUtils.fileRead( sourceFile.getAbsolutePath() ) ); + try (FileInputStream fileInputStream = new FileInputStream(tempFile)) { + wagon.putFromStream(fileInputStream, "test-secured-put-resource", content.length(), -1); + assertEquals(content, FileUtils.fileRead(sourceFile.getAbsolutePath())); - checkRequestResponseForRedirectPutWithRelativeUrl( redirectHandler, putHandler ); - } - finally - { + checkRequestResponseForRedirectPutWithRelativeUrl(redirectHandler, putHandler); + } finally { wagon.disconnect(); tempFile.delete(); } - } - finally - { + } finally { realServer.stop(); redirectServer.stop(); } } - protected void checkRequestResponseForRedirectPutWithRelativeUrl( RedirectHandler redirectHandler, - PutHandler putHandler ) - { - checkHandlerResult( redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER, - HttpServletResponse.SC_CREATED ); - checkHandlerResult( putHandler.handlerRequestResponses ); + protected void checkRequestResponseForRedirectPutWithRelativeUrl( + RedirectHandler redirectHandler, PutHandler putHandler) { + checkHandlerResult( + redirectHandler.handlerRequestResponses, + HttpServletResponse.SC_SEE_OTHER, + HttpServletResponse.SC_CREATED); + checkHandlerResult(putHandler.handlerRequestResponses); } - protected void checkHandlerResult( List handlerRequestResponses, - int... expectedResponseCodes ) - { + protected void checkHandlerResult( + List handlerRequestResponses, int... expectedResponseCodes) { boolean success = true; - if ( handlerRequestResponses.size() == expectedResponseCodes.length ) - { - for ( int i = 0; i < expectedResponseCodes.length; i++ ) - { - success &= expectedResponseCodes[i] == handlerRequestResponses.get( i ).responseCode; + if (handlerRequestResponses.size() == expectedResponseCodes.length) { + for (int i = 0; i < expectedResponseCodes.length; i++) { + success &= expectedResponseCodes[i] == handlerRequestResponses.get(i).responseCode; } } - if ( !success ) - { - fail( "expected " + expectedResponseCodes + ", got " + handlerRequestResponses ); + if (!success) { + fail("expected " + expectedResponseCodes + ", got " + handlerRequestResponses); } } - public void testRedirectPutFileWithFullUrl() - throws Exception - { - Server realServer = new Server( ); + public void testRedirectPutFileWithFullUrl() throws Exception { + Server realServer = new Server(); - addConnector( realServer ); + addConnector(realServer); File repositoryDirectory = getRepositoryDirectory(); - FileUtils.deleteDirectory( repositoryDirectory ); + FileUtils.deleteDirectory(repositoryDirectory); repositoryDirectory.mkdirs(); - PutHandler putHandler = new PutHandler( repositoryDirectory ); + PutHandler putHandler = new PutHandler(repositoryDirectory); - realServer.setHandler( putHandler ); + realServer.setHandler(putHandler); realServer.start(); - Server redirectServer = new Server( ); + Server redirectServer = new Server(); - addConnector( redirectServer ); + addConnector(redirectServer); String protocol = getProtocol(); // protocol is wagon protocol but in fact dav is http(s) - if ( protocol.equals( "dav" ) ) - { + if (protocol.equals("dav")) { protocol = "http"; } - if ( protocol.equals( "davs" ) ) - { + if (protocol.equals("davs")) { protocol = "https"; } - String redirectUrl = protocol + "://localhost:" + getLocalPort( realServer ); + String redirectUrl = protocol + "://localhost:" + getLocalPort(realServer); RedirectHandler redirectHandler = - new RedirectHandler( "See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, repositoryDirectory ); + new RedirectHandler("See Other", HttpServletResponse.SC_SEE_OTHER, redirectUrl, repositoryDirectory); - redirectServer.setHandler( redirectHandler ); + redirectServer.setHandler(redirectHandler); redirectServer.start(); - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository repository = new Repository( "foo", getRepositoryUrl( redirectServer ) ); - wagon.connect( repository ); + Repository repository = new Repository("foo", getRepositoryUrl(redirectServer)); + wagon.connect(repository); - File sourceFile = new File( repositoryDirectory, "test-secured-put-resource" ); + File sourceFile = new File(repositoryDirectory, "test-secured-put-resource"); sourceFile.delete(); - assertFalse( sourceFile.exists() ); + assertFalse(sourceFile.exists()); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); String content = "put top secret"; - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); - try - { - wagon.put( tempFile, "test-secured-put-resource" ); - assertEquals( content, FileUtils.fileRead( sourceFile.getAbsolutePath() ) ); + try { + wagon.put(tempFile, "test-secured-put-resource"); + assertEquals(content, FileUtils.fileRead(sourceFile.getAbsolutePath())); - checkRequestResponseForRedirectPutWithFullUrl( redirectHandler, putHandler ); - } - finally - { + checkRequestResponseForRedirectPutWithFullUrl(redirectHandler, putHandler); + } finally { wagon.disconnect(); tempFile.delete(); } - } - finally - { + } finally { realServer.stop(); redirectServer.stop(); } } - - public void testRedirectPutFileRelativeUrl() - throws Exception - { - Server realServer = new Server( ); - addConnector( realServer ); + public void testRedirectPutFileRelativeUrl() throws Exception { + Server realServer = new Server(); + addConnector(realServer); File repositoryDirectory = getRepositoryDirectory(); - FileUtils.deleteDirectory( repositoryDirectory ); + FileUtils.deleteDirectory(repositoryDirectory); repositoryDirectory.mkdirs(); - PutHandler putHandler = new PutHandler( repositoryDirectory ); + PutHandler putHandler = new PutHandler(repositoryDirectory); - realServer.setHandler( putHandler ); + realServer.setHandler(putHandler); realServer.start(); - Server redirectServer = new Server( ); + Server redirectServer = new Server(); - addConnector( redirectServer ); + addConnector(redirectServer); - RedirectHandler redirectHandler = - new RedirectHandler( "See Other", HttpServletResponse.SC_SEE_OTHER, "/redirectRequest/foo", - repositoryDirectory ); + RedirectHandler redirectHandler = new RedirectHandler( + "See Other", HttpServletResponse.SC_SEE_OTHER, "/redirectRequest/foo", repositoryDirectory); - redirectServer.setHandler( redirectHandler ); + redirectServer.setHandler(redirectHandler); redirectServer.start(); - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository repository = new Repository( "foo", getRepositoryUrl( redirectServer ) ); - wagon.connect( repository ); + Repository repository = new Repository("foo", getRepositoryUrl(redirectServer)); + wagon.connect(repository); - File sourceFile = new File( repositoryDirectory, "/redirectRequest/foo/test-secured-put-resource" ); + File sourceFile = new File(repositoryDirectory, "/redirectRequest/foo/test-secured-put-resource"); sourceFile.delete(); - assertFalse( sourceFile.exists() ); + assertFalse(sourceFile.exists()); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); String content = "put top secret"; - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); - try - { - wagon.put( tempFile, "test-secured-put-resource" ); - assertEquals( content, FileUtils.fileRead( sourceFile.getAbsolutePath() ) ); + try { + wagon.put(tempFile, "test-secured-put-resource"); + assertEquals(content, FileUtils.fileRead(sourceFile.getAbsolutePath())); - checkRequestResponseForRedirectPutWithRelativeUrl( redirectHandler, putHandler ); - } - finally - { + checkRequestResponseForRedirectPutWithRelativeUrl(redirectHandler, putHandler); + } finally { wagon.disconnect(); tempFile.delete(); } - } - finally - { + } finally { realServer.stop(); redirectServer.stop(); } } - public void testRedirectPutFailureNonRepeatableStream() - throws Exception - { - File repositoryDirectory = getRepositoryDirectory(); - FileUtils.deleteDirectory( repositoryDirectory ); - repositoryDirectory.mkdirs(); + public void testRedirectPutFailureNonRepeatableStream() throws Exception { + File repositoryDirectory = getRepositoryDirectory(); + FileUtils.deleteDirectory(repositoryDirectory); + repositoryDirectory.mkdirs(); - Server redirectServer = new Server( ); + Server redirectServer = new Server(); - addConnector( redirectServer ); + addConnector(redirectServer); - RedirectHandler redirectHandler = - new RedirectHandler( "See Other", HttpServletResponse.SC_SEE_OTHER, "/redirectRequest/foo", - null ); + RedirectHandler redirectHandler = + new RedirectHandler("See Other", HttpServletResponse.SC_SEE_OTHER, "/redirectRequest/foo", null); - redirectServer.setHandler( redirectHandler ); + redirectServer.setHandler(redirectHandler); - redirectServer.start(); + redirectServer.start(); - try - { - StreamingWagon wagon = (StreamingWagon) getWagon(); + try { + StreamingWagon wagon = (StreamingWagon) getWagon(); - Properties params = new Properties(); - params.put( "http.protocol.expect-continue", "%b,false" ); - setHttpConfiguration( wagon, new Properties(), params ); - Repository repository = new Repository( "foo", getRepositoryUrl( redirectServer ) ); - wagon.connect( repository ); + Properties params = new Properties(); + params.put("http.protocol.expect-continue", "%b,false"); + setHttpConfiguration(wagon, new Properties(), params); + Repository repository = new Repository("foo", getRepositoryUrl(redirectServer)); + wagon.connect(repository); - File sourceFile = new File( repositoryDirectory, "/redirectRequest/foo/test-secured-put-resource" ); - sourceFile.delete(); - assertFalse( sourceFile.exists() ); + File sourceFile = new File(repositoryDirectory, "/redirectRequest/foo/test-secured-put-resource"); + sourceFile.delete(); + assertFalse(sourceFile.exists()); - File tempFile = File.createTempFile( "wagon", "tmp" ); - tempFile.deleteOnExit(); - String content = "put top secret"; - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); - - try ( FileInputStream fileInputStream = new FileInputStream( tempFile ) ) - { - wagon.putFromStream( fileInputStream, "test-secured-put-resource", content.length(), -1 ); - // This does not behave as expected because LightweightWagon does buffering by default - if ( wagon.getClass().getName().contains( "Lightweight" ) ) - { - assertTrue( true ); - } - else - { - fail(); - } - } - catch ( TransferFailedException e ) - { - assertTrue( true ); - } - finally - { - wagon.disconnect(); - tempFile.delete(); + File tempFile = File.createTempFile("wagon", "tmp"); + tempFile.deleteOnExit(); + String content = "put top secret"; + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); + + try (FileInputStream fileInputStream = new FileInputStream(tempFile)) { + wagon.putFromStream(fileInputStream, "test-secured-put-resource", content.length(), -1); + // This does not behave as expected because LightweightWagon does buffering by default + if (wagon.getClass().getName().contains("Lightweight")) { + assertTrue(true); + } else { + fail(); } - - } - finally - { - redirectServer.stop(); + } catch (TransferFailedException e) { + assertTrue(true); + } finally { + wagon.disconnect(); + tempFile.delete(); } + + } finally { + redirectServer.stop(); } + } /** * */ - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static class RedirectHandler - extends AbstractHandler - { + @SuppressWarnings("checkstyle:visibilitymodifier") + public static class RedirectHandler extends AbstractHandler { String reason; int retCode; @@ -1174,243 +999,198 @@ public static class RedirectHandler public List handlerRequestResponses = new ArrayList<>(); - RedirectHandler( String reason, int retCode, String redirectUrl, File repositoryDirectory ) - { + RedirectHandler(String reason, int retCode, String redirectUrl, File repositoryDirectory) { this.reason = reason; this.retCode = retCode; this.redirectUrl = redirectUrl; this.repositoryDirectory = repositoryDirectory; } - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { - if ( request.getRequestURI().contains( "redirectRequest" ) ) - { - PutHandler putHandler = new PutHandler( this.repositoryDirectory ); - putHandler.handle( target, baseRequest, request, response ); + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + if (request.getRequestURI().contains("redirectRequest")) { + PutHandler putHandler = new PutHandler(this.repositoryDirectory); + putHandler.handle(target, baseRequest, request, response); handlerRequestResponses.add( - new HandlerRequestResponse( request.getMethod(), response.getStatus(), - request.getRequestURI() ) ); + new HandlerRequestResponse(request.getMethod(), response.getStatus(), request.getRequestURI())); return; } - response.setStatus( this.retCode ); - response.setHeader( "Location", this.redirectUrl + request.getRequestURI() ); - baseRequest.setHandled( true ); + response.setStatus(this.retCode); + response.setHeader("Location", this.redirectUrl + request.getRequestURI()); + baseRequest.setHandled(true); handlerRequestResponses.add( - new HandlerRequestResponse( request.getMethod(), response.getStatus(), - request.getRequestURI() ) ); + new HandlerRequestResponse(request.getMethod(), response.getStatus(), request.getRequestURI())); } - - } - - private void runTestProxiedRequest( ProxyInfo proxyInfo, TestHeaderHandler handler ) - throws Exception - { + private void runTestProxiedRequest(ProxyInfo proxyInfo, TestHeaderHandler handler) throws Exception { // what an UGLY hack! // but apparently jetty needs some time to free up resources // <5s: broken test :( // CHECKSTYLE_OFF: MagicNumber - Thread.sleep( 5001L ); + Thread.sleep(5001L); // CHECKSTYLE_ON: MagicNumber - Server proxyServer = new Server( ); + Server proxyServer = new Server(); ServerConnector serverConnector = - new ServerConnector( proxyServer, new HttpConnectionFactory( new HttpConfiguration() ) ); - proxyServer.addConnector( serverConnector ); - proxyServer.setHandler( handler ); + new ServerConnector(proxyServer, new HttpConnectionFactory(new HttpConfiguration())); + proxyServer.addConnector(serverConnector); + proxyServer.setHandler(handler); proxyServer.start(); - proxyInfo.setPort( getLocalPort( proxyServer ) ); + proxyInfo.setPort(getLocalPort(proxyServer)); - System.out.println( - "start proxy on host/port " + proxyInfo.getHost() + "/" + proxyInfo.getPort() + " with non proxyHosts " - + proxyInfo.getNonProxyHosts() ); + System.out.println("start proxy on host/port " + proxyInfo.getHost() + "/" + proxyInfo.getPort() + + " with non proxyHosts " + proxyInfo.getNonProxyHosts()); - while ( !proxyServer.isRunning() || !proxyServer.isStarted() ) - { - Thread.sleep( 10 ); + while (!proxyServer.isRunning() || !proxyServer.isStarted()) { + Thread.sleep(10); } - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository testRepository = new Repository( "id", "http://www.example.com/" ); + Repository testRepository = new Repository("id", "http://www.example.com/"); String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - File sourceFile = new File( localRepositoryPath, "test-proxied-resource" ); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), "content" ); + File sourceFile = new File(localRepositoryPath, "test-proxied-resource"); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), "content"); - wagon.connect( testRepository, proxyInfo ); + wagon.connect(testRepository, proxyInfo); - try - { - wagon.getToStream( "test-proxied-resource", new ByteArrayOutputStream() ); + try { + wagon.getToStream("test-proxied-resource", new ByteArrayOutputStream()); - assertTrue( handler.headers.containsKey( "Proxy-Connection" ) ); - } - finally - { - System.setProperty( "http.proxyHost", "" ); - System.setProperty( "http.proxyPort", "" ); + assertTrue(handler.headers.containsKey("Proxy-Connection")); + } finally { + System.setProperty("http.proxyHost", ""); + System.setProperty("http.proxyPort", ""); wagon.disconnect(); } - } - finally - { + } finally { proxyServer.stop(); } } - private void runTestProxiedRequestWithProvider( ProxyInfoProvider proxyInfoProvider, TestHeaderHandler handler ) - throws Exception - { + private void runTestProxiedRequestWithProvider(ProxyInfoProvider proxyInfoProvider, TestHeaderHandler handler) + throws Exception { // what an UGLY hack! // but apparently jetty needs some time to free up resources // <5s: broken test :( // CHECKSTYLE_OFF: MagicNumber - Thread.sleep( 5001L ); + Thread.sleep(5001L); // CHECKSTYLE_ON: MagicNumber - Server proxyServer = new Server( ); + Server proxyServer = new Server(); ServerConnector serverConnector = - new ServerConnector( proxyServer, new HttpConnectionFactory( new HttpConfiguration() ) ); - proxyServer.addConnector( serverConnector ); + new ServerConnector(proxyServer, new HttpConnectionFactory(new HttpConfiguration())); + proxyServer.addConnector(serverConnector); - proxyServer.setHandler( handler ); + proxyServer.setHandler(handler); proxyServer.start(); - proxyInfoProvider.getProxyInfo( null ).setPort( getLocalPort( proxyServer ) ); + proxyInfoProvider.getProxyInfo(null).setPort(getLocalPort(proxyServer)); - System.out.println( "start proxy on host/port " + proxyInfoProvider.getProxyInfo( null ).getHost() + "/" - + proxyInfoProvider.getProxyInfo( null ).getPort() + " with non proxyHosts " - + proxyInfoProvider.getProxyInfo( null ).getNonProxyHosts() ); + System.out.println("start proxy on host/port " + + proxyInfoProvider.getProxyInfo(null).getHost() + "/" + + proxyInfoProvider.getProxyInfo(null).getPort() + " with non proxyHosts " + + proxyInfoProvider.getProxyInfo(null).getNonProxyHosts()); - while ( !proxyServer.isRunning() || !proxyServer.isStarted() ) - { - Thread.sleep( 10 ); + while (!proxyServer.isRunning() || !proxyServer.isStarted()) { + Thread.sleep(10); } - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository testRepository = new Repository( "id", "http://www.example.com/" ); + Repository testRepository = new Repository("id", "http://www.example.com/"); String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - File sourceFile = new File( localRepositoryPath, "test-proxied-resource" ); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), "content" ); + File sourceFile = new File(localRepositoryPath, "test-proxied-resource"); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), "content"); - wagon.connect( testRepository, proxyInfoProvider ); + wagon.connect(testRepository, proxyInfoProvider); - try - { - wagon.getToStream( "test-proxied-resource", new ByteArrayOutputStream() ); + try { + wagon.getToStream("test-proxied-resource", new ByteArrayOutputStream()); - assertTrue( handler.headers.containsKey( "Proxy-Connection" ) ); - } - finally - { - System.setProperty( "http.proxyHost", "" ); - System.setProperty( "http.proxyPort", "" ); + assertTrue(handler.headers.containsKey("Proxy-Connection")); + } finally { + System.setProperty("http.proxyHost", ""); + System.setProperty("http.proxyPort", ""); wagon.disconnect(); } - } - finally - { + } finally { proxyServer.stop(); } } - private ProxyInfo createProxyInfo() - { + private ProxyInfo createProxyInfo() { ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setHost( "localhost" ); - proxyInfo.setNonProxyHosts( null ); - proxyInfo.setType( "http" ); + proxyInfo.setHost("localhost"); + proxyInfo.setNonProxyHosts(null); + proxyInfo.setType("http"); return proxyInfo; } - public void testSecuredGetUnauthorized() - throws Exception - { - try - { - runTestSecuredGet( null ); + public void testSecuredGetUnauthorized() throws Exception { + try { + runTestSecuredGet(null); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testSecuredGetWrongPassword() - throws Exception - { - try - { + public void testSecuredGetWrongPassword() throws Exception { + try { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "admin" ); - runTestSecuredGet( authInfo ); + authInfo.setUserName("user"); + authInfo.setPassword("admin"); + runTestSecuredGet(authInfo); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testSecuredGet() - throws Exception - { + public void testSecuredGet() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "secret" ); - runTestSecuredGet( authInfo ); + authInfo.setUserName("user"); + authInfo.setPassword("secret"); + runTestSecuredGet(authInfo); } - - public void runTestSecuredGet( AuthenticationInfo authInfo ) - throws Exception - { + public void runTestSecuredGet(AuthenticationInfo authInfo) throws Exception { String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - Server server = createSecurityServer( localRepositoryPath ); + Server server = createSecurityServer(localRepositoryPath); server.start(); - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository testRepository = new Repository( "id", getRepositoryUrl( server ) ); + Repository testRepository = new Repository("id", getRepositoryUrl(server)); - File sourceFile = new File( localRepositoryPath, "test-secured-resource" ); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), "top secret" ); + File sourceFile = new File(localRepositoryPath, "test-secured-resource"); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), "top secret"); - wagon.connect( testRepository, authInfo ); + wagon.connect(testRepository, authInfo); - File file = File.createTempFile( "wagon-test", "txt" ); + File file = File.createTempFile("wagon-test", "txt"); - try - { - wagon.get( "test-secured-resource", file ); - } - finally - { + try { + wagon.get("test-secured-resource", file); + } finally { wagon.disconnect(); } - FileInputStream in = new FileInputStream( file ); + FileInputStream in = new FileInputStream(file); - assertEquals( "top secret", IOUtil.toString( in ) ); + assertEquals("top secret", IOUtil.toString(in)); /* * We need to wait a bit for all Jetty workers/threads to complete their work. Otherwise @@ -1419,59 +1199,48 @@ public void runTestSecuredGet( AuthenticationInfo authInfo ) * a test failure. */ // CHECKSTYLE_OFF: MagicNumber - Thread.sleep ( 2000L ); + Thread.sleep(2000L); // CHECKSTYLE_ON: MagicNumber - TestSecurityHandler securityHandler = server.getChildHandlerByClass( TestSecurityHandler.class ); - testPreemptiveAuthenticationGet( securityHandler, supportPreemptiveAuthenticationGet() ); + TestSecurityHandler securityHandler = server.getChildHandlerByClass(TestSecurityHandler.class); + testPreemptiveAuthenticationGet(securityHandler, supportPreemptiveAuthenticationGet()); - } - finally - { + } finally { server.stop(); } } - - public void testSecuredGetToStream() - throws Exception - { + public void testSecuredGetToStream() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "secret" ); - runTestSecuredGetToStream( authInfo ); + authInfo.setUserName("user"); + authInfo.setPassword("secret"); + runTestSecuredGetToStream(authInfo); } - public void runTestSecuredGetToStream( AuthenticationInfo authInfo ) - throws Exception - { + public void runTestSecuredGetToStream(AuthenticationInfo authInfo) throws Exception { String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - Server server = createSecurityServer( localRepositoryPath ); + Server server = createSecurityServer(localRepositoryPath); server.start(); - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository testRepository = new Repository( "id", getRepositoryUrl( server ) ); + Repository testRepository = new Repository("id", getRepositoryUrl(server)); - File sourceFile = new File( localRepositoryPath, "test-secured-resource" ); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), "top secret" ); + File sourceFile = new File(localRepositoryPath, "test-secured-resource"); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), "top secret"); - wagon.connect( testRepository, authInfo ); + wagon.connect(testRepository, authInfo); ByteArrayOutputStream out = new ByteArrayOutputStream(); - try - { - wagon.getToStream( "test-secured-resource", out ); - } - finally - { + try { + wagon.getToStream("test-secured-resource", out); + } finally { wagon.disconnect(); } - assertEquals( "top secret", out.toString( "US-ASCII" ) ); + assertEquals("top secret", out.toString("US-ASCII")); /* * We need to wait a bit for all Jetty workers/threads to complete their work. Otherwise @@ -1480,264 +1249,202 @@ public void runTestSecuredGetToStream( AuthenticationInfo authInfo ) * a test failure. */ // CHECKSTYLE_OFF: MagicNumber - Thread.sleep ( 2000L ); + Thread.sleep(2000L); // CHECKSTYLE_ON: MagicNumber - TestSecurityHandler securityHandler = server.getChildHandlerByClass( TestSecurityHandler.class ); - testPreemptiveAuthenticationGet( securityHandler, supportPreemptiveAuthenticationGet() ); - } - finally - { + TestSecurityHandler securityHandler = server.getChildHandlerByClass(TestSecurityHandler.class); + testPreemptiveAuthenticationGet(securityHandler, supportPreemptiveAuthenticationGet()); + } finally { server.stop(); } } - public void testSecuredResourceExistsUnauthorized() - throws Exception - { - try - { - runTestSecuredResourceExists( null ); + public void testSecuredResourceExistsUnauthorized() throws Exception { + try { + runTestSecuredResourceExists(null); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testSecuredResourceExistsWrongPassword() - throws Exception - { - try - { + public void testSecuredResourceExistsWrongPassword() throws Exception { + try { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "admin" ); - runTestSecuredResourceExists( authInfo ); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + authInfo.setUserName("user"); + authInfo.setPassword("admin"); + runTestSecuredResourceExists(authInfo); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testSecuredResourceExists() - throws Exception - { + public void testSecuredResourceExists() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "secret" ); - runTestSecuredResourceExists( authInfo ); + authInfo.setUserName("user"); + authInfo.setPassword("secret"); + runTestSecuredResourceExists(authInfo); } - public void runTestSecuredResourceExists( AuthenticationInfo authInfo ) - throws Exception - { + public void runTestSecuredResourceExists(AuthenticationInfo authInfo) throws Exception { String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - Server server = createSecurityServer( localRepositoryPath ); + Server server = createSecurityServer(localRepositoryPath); server.start(); - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository testRepository = new Repository( "id", getRepositoryUrl( server ) ); + Repository testRepository = new Repository("id", getRepositoryUrl(server)); - File sourceFile = new File( localRepositoryPath, "test-secured-resource-exists" ); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), "top secret" ); + File sourceFile = new File(localRepositoryPath, "test-secured-resource-exists"); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), "top secret"); - wagon.connect( testRepository, authInfo ); + wagon.connect(testRepository, authInfo); - try - { - assertTrue( wagon.resourceExists( "test-secured-resource-exists" ) ); + try { + assertTrue(wagon.resourceExists("test-secured-resource-exists")); - assertFalse( wagon.resourceExists( "test-secured-resource-not-exists" ) ); - } - finally - { + assertFalse(wagon.resourceExists("test-secured-resource-not-exists")); + } finally { wagon.disconnect(); } - } - finally - { + } finally { server.stop(); } } - private Server createSecurityServer( String localRepositoryPath ) - { - Server server = new Server( ); + private Server createSecurityServer(String localRepositoryPath) { + Server server = new Server(); SecurityHandler sh = createSecurityHandler(); - ServletContextHandler root = new ServletContextHandler( ServletContextHandler.SESSIONS - | ServletContextHandler.SECURITY ); - root.setResourceBase( localRepositoryPath ); - root.setSecurityHandler( sh ); - ServletHolder servletHolder = new ServletHolder( new DefaultServlet() ); - root.addServlet( servletHolder, "/*" ); + ServletContextHandler root = + new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY); + root.setResourceBase(localRepositoryPath); + root.setSecurityHandler(sh); + ServletHolder servletHolder = new ServletHolder(new DefaultServlet()); + root.addServlet(servletHolder, "/*"); - server.setHandler( root ); - addConnector( server ); + server.setHandler(root); + addConnector(server); return server; } - private Server createStatusServer( int status ) - { - Server server = new Server( ); + private Server createStatusServer(int status) { + Server server = new Server(); StatusHandler handler = new StatusHandler(); - handler.setStatusToReturn( status ); - server.setHandler( handler ); - addConnector( server ); + handler.setStatusToReturn(status); + server.setHandler(handler); + addConnector(server); return server; } - - private String writeTestFile( File parent, String child, String compressionType ) - throws IOException - { - File file = new File( parent, child ); + private String writeTestFile(File parent, String child, String compressionType) throws IOException { + File file = new File(parent, child); file.getParentFile().mkdirs(); file.deleteOnExit(); - OutputStream out = new FileOutputStream( file ); - try - { - out.write( child.getBytes() ); - } - finally - { + OutputStream out = new FileOutputStream(file); + try { + out.write(child.getBytes()); + } finally { out.close(); } String ext = ""; - if ( "gzip".equals( compressionType ) ) - { + if ("gzip".equals(compressionType)) { ext = ".gz"; } - if ( "deflate".equals( compressionType ) ) - { + if ("deflate".equals(compressionType)) { ext = ".deflate"; } - file = new File( parent, child + ext ); + file = new File(parent, child + ext); file.deleteOnExit(); String content; - out = new FileOutputStream( file ); - if ( "gzip".equals( compressionType ) ) - { - out = new GZIPOutputStream( out ); + out = new FileOutputStream(file); + if ("gzip".equals(compressionType)) { + out = new GZIPOutputStream(out); } - if ( "deflate".equals( compressionType ) ) - { - out = new DeflaterOutputStream( out ); + if ("deflate".equals(compressionType)) { + out = new DeflaterOutputStream(out); } - try - { + try { // write out different data than non-compressed file, so we can // assert the compressed version was returned content = file.getAbsolutePath(); - out.write( content.getBytes() ); - } - finally - { + out.write(content.getBytes()); + } finally { out.close(); } return content; } - public void testPutForbidden() - throws Exception - { - try - { - runTestPut( HttpServletResponse.SC_FORBIDDEN ); + public void testPutForbidden() throws Exception { + try { + runTestPut(HttpServletResponse.SC_FORBIDDEN); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testPut404() - throws Exception - { - try - { - runTestPut( HttpServletResponse.SC_NOT_FOUND ); + public void testPut404() throws Exception { + try { + runTestPut(HttpServletResponse.SC_NOT_FOUND); fail(); - } - catch ( ResourceDoesNotExistException e ) - { - assertTrue( true ); + } catch (ResourceDoesNotExistException e) { + assertTrue(true); } } - public void testPut500() - throws Exception - { - try - { - runTestPut( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + public void testPut500() throws Exception { + try { + runTestPut(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); fail(); - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } } - public void testPut429() - throws Exception - { + public void testPut429() throws Exception { - try - { + try { StreamingWagon wagon = (StreamingWagon) getWagon(); - Server server = new Server( ); + Server server = new Server(); final AtomicBoolean called = new AtomicBoolean(); - AbstractHandler handler = new AbstractHandler() - { - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { - if ( called.get() ) - { - response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - baseRequest.setHandled( true ); - } - else - { - called.set( true ); - response.setStatus( SC_TOO_MANY_REQUESTS ); - baseRequest.setHandled( true ); + AbstractHandler handler = new AbstractHandler() { + public void handle( + String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + if (called.get()) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + baseRequest.setHandled(true); + } else { + called.set(true); + response.setStatus(SC_TOO_MANY_REQUESTS); + baseRequest.setHandled(true); } } }; - server.setHandler( handler ); - addConnector( server ); + server.setHandler(handler); + addConnector(server); server.start(); - wagon.connect( new Repository( "id", getRepositoryUrl( server ) ) ); + wagon.connect(new Repository("id", getRepositoryUrl(server))); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); - FileUtils.fileWrite( tempFile.getAbsolutePath(), "content" ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), "content"); - try - { - wagon.put( tempFile, "resource" ); + try { + wagon.put(tempFile, "resource"); fail(); - } - finally - { + } finally { wagon.disconnect(); server.stop(); @@ -1745,44 +1452,34 @@ public void handle( String target, Request baseRequest, HttpServletRequest reque tempFile.delete(); } - } - catch ( TransferFailedException e ) - { - assertTrue( true ); + } catch (TransferFailedException e) { + assertTrue(true); } } - - private void runTestPut( int status ) - throws Exception - { + private void runTestPut(int status) throws Exception { StreamingWagon wagon = (StreamingWagon) getWagon(); - Server server = createStatusServer( status ); + Server server = createStatusServer(status); server.start(); - wagon.connect( new Repository( "id", getRepositoryUrl( server ) ) ); + wagon.connect(new Repository("id", getRepositoryUrl(server))); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); - FileUtils.fileWrite( tempFile.getAbsolutePath(), "content" ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), "content"); - String baseUrl = getRepositoryUrl( server ); + String baseUrl = getRepositoryUrl(server); String resourceName = "resource"; - String serverReasonPhrase = HttpStatus.getCode( status ).getMessage(); + String serverReasonPhrase = HttpStatus.getCode(status).getMessage(); - try - { - wagon.put( tempFile, resourceName ); + try { + wagon.put(tempFile, resourceName); fail(); - } - catch ( Exception e ) - { - verifyWagonExceptionMessage( e, status, baseUrl + "/" + resourceName, serverReasonPhrase ); + } catch (Exception e) { + verifyWagonExceptionMessage(e, status, baseUrl + "/" + resourceName, serverReasonPhrase); throw e; - } - finally - { + } finally { wagon.disconnect(); server.stop(); @@ -1791,258 +1488,200 @@ private void runTestPut( int status ) } } - public void testSecuredPutUnauthorized() - throws Exception - { - try - { - runTestSecuredPut( null ); + public void testSecuredPutUnauthorized() throws Exception { + try { + runTestSecuredPut(null); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testSecuredPutWrongPassword() - throws Exception - { - try - { + public void testSecuredPutWrongPassword() throws Exception { + try { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "admin" ); - runTestSecuredPut( authInfo ); + authInfo.setUserName("user"); + authInfo.setPassword("admin"); + runTestSecuredPut(authInfo); fail(); - } - catch ( AuthorizationException e ) - { - assertTrue( true ); + } catch (AuthorizationException e) { + assertTrue(true); } } - public void testSecuredPut() - throws Exception - { + public void testSecuredPut() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "secret" ); - runTestSecuredPut( authInfo ); + authInfo.setUserName("user"); + authInfo.setPassword("secret"); + runTestSecuredPut(authInfo); } - public void runTestSecuredPut( AuthenticationInfo authInfo ) - throws Exception - { - runTestSecuredPut( authInfo, 1 ); + public void runTestSecuredPut(AuthenticationInfo authInfo) throws Exception { + runTestSecuredPut(authInfo, 1); } - public void runTestSecuredPut( AuthenticationInfo authInfo, int putNumber ) - throws Exception - { + public void runTestSecuredPut(AuthenticationInfo authInfo, int putNumber) throws Exception { String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - Server server = new Server( ); + Server server = new Server(); TestSecurityHandler sh = createSecurityHandler(); - PutHandler putHandler = new PutHandler( new File( localRepositoryPath ) ); + PutHandler putHandler = new PutHandler(new File(localRepositoryPath)); - sh.setHandler( putHandler ); - server.setHandler( sh ); - addConnector( server ); + sh.setHandler(putHandler); + server.setHandler(sh); + addConnector(server); server.start(); StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository testRepository = new Repository( "id", getRepositoryUrl( server ) ); - wagon.connect( testRepository, authInfo ); - try - { - for ( int i = 0; i < putNumber; i++ ) - { - File sourceFile = new File( localRepositoryPath, "test-secured-put-resource" ); + Repository testRepository = new Repository("id", getRepositoryUrl(server)); + wagon.connect(testRepository, authInfo); + try { + for (int i = 0; i < putNumber; i++) { + File sourceFile = new File(localRepositoryPath, "test-secured-put-resource"); sourceFile.delete(); - assertFalse( sourceFile.exists() ); + assertFalse(sourceFile.exists()); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); - FileUtils.fileWrite( tempFile.getAbsolutePath(), "put top secret" ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), "put top secret"); - try - { - wagon.put( tempFile, "test-secured-put-resource" ); - } - finally - { + try { + wagon.put(tempFile, "test-secured-put-resource"); + } finally { tempFile.delete(); } - assertEquals( "put top secret", FileUtils.fileRead( sourceFile.getAbsolutePath() ) ); + assertEquals("put top secret", FileUtils.fileRead(sourceFile.getAbsolutePath())); } - } - finally - { + } finally { wagon.disconnect(); server.stop(); } - assertEquals( putNumber, putHandler.putCallNumber ); - testPreemptiveAuthenticationPut( sh, supportPreemptiveAuthenticationPut() ); + assertEquals(putNumber, putHandler.putCallNumber); + testPreemptiveAuthenticationPut(sh, supportPreemptiveAuthenticationPut()); } - public void testNonSecuredPutFromStream() - throws Exception - { + public void testNonSecuredPutFromStream() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "secret" ); - runTestSecuredPutFromStream( authInfo, 1, false ); + authInfo.setUserName("user"); + authInfo.setPassword("secret"); + runTestSecuredPutFromStream(authInfo, 1, false); } - public void testSecuredPutFromStream() - throws Exception - { + public void testSecuredPutFromStream() throws Exception { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "user" ); - authInfo.setPassword( "secret" ); - runTestSecuredPutFromStream( authInfo, 1, true ); + authInfo.setUserName("user"); + authInfo.setPassword("secret"); + runTestSecuredPutFromStream(authInfo, 1, true); } - public void runTestSecuredPutFromStream( AuthenticationInfo authInfo, int putNumber, boolean addSecurityHandler ) - throws Exception - { + public void runTestSecuredPutFromStream(AuthenticationInfo authInfo, int putNumber, boolean addSecurityHandler) + throws Exception { String localRepositoryPath = FileTestUtils.getTestOutputDir().toString(); - Server server = new Server( ); + Server server = new Server(); TestSecurityHandler sh = createSecurityHandler(); - PutHandler putHandler = new PutHandler( new File( localRepositoryPath ) ); + PutHandler putHandler = new PutHandler(new File(localRepositoryPath)); - if ( addSecurityHandler ) - { - sh.setHandler( putHandler ); - server.setHandler( sh ); - } - else - { - server.setHandler( putHandler ); + if (addSecurityHandler) { + sh.setHandler(putHandler); + server.setHandler(sh); + } else { + server.setHandler(putHandler); } - addConnector( server ); + addConnector(server); server.start(); StreamingWagon wagon = (StreamingWagon) getWagon(); - Repository testRepository = new Repository( "id", getRepositoryUrl( server ) ); - if ( addSecurityHandler ) - { - wagon.connect( testRepository, authInfo ); - } - else - { - wagon.connect( testRepository ); - } - try - { - for ( int i = 0; i < putNumber; i++ ) - { - File sourceFile = new File( localRepositoryPath, "test-secured-put-resource" ); + Repository testRepository = new Repository("id", getRepositoryUrl(server)); + if (addSecurityHandler) { + wagon.connect(testRepository, authInfo); + } else { + wagon.connect(testRepository); + } + try { + for (int i = 0; i < putNumber; i++) { + File sourceFile = new File(localRepositoryPath, "test-secured-put-resource"); sourceFile.delete(); - assertFalse( sourceFile.exists() ); + assertFalse(sourceFile.exists()); - File tempFile = File.createTempFile( "wagon", "tmp" ); + File tempFile = File.createTempFile("wagon", "tmp"); tempFile.deleteOnExit(); String content = "put top secret"; - FileUtils.fileWrite( tempFile.getAbsolutePath(), content ); + FileUtils.fileWrite(tempFile.getAbsolutePath(), content); - try ( FileInputStream fileInputStream = new FileInputStream( tempFile ) ) - { - wagon.putFromStream( fileInputStream, "test-secured-put-resource", content.length(), -1 ); - } - finally - { + try (FileInputStream fileInputStream = new FileInputStream(tempFile)) { + wagon.putFromStream(fileInputStream, "test-secured-put-resource", content.length(), -1); + } finally { tempFile.delete(); } - assertEquals( content, FileUtils.fileRead( sourceFile.getAbsolutePath() ) ); + assertEquals(content, FileUtils.fileRead(sourceFile.getAbsolutePath())); } - } - finally - { + } finally { wagon.disconnect(); server.stop(); } - assertEquals( putNumber, putHandler.putCallNumber ); - if ( addSecurityHandler ) - { - testPreemptiveAuthenticationPut( sh, supportPreemptiveAuthenticationPut() ); + assertEquals(putNumber, putHandler.putCallNumber); + if (addSecurityHandler) { + testPreemptiveAuthenticationPut(sh, supportPreemptiveAuthenticationPut()); } // ensure we didn't use chunked transfer which doesn't work on ngnix - for ( DeployedResource deployedResource : putHandler.deployedResources ) - { - if ( StringUtils.equalsIgnoreCase( "chunked", deployedResource.transferEncoding ) ) - { - fail( "deployedResource use chunked: " + deployedResource ); + for (DeployedResource deployedResource : putHandler.deployedResources) { + if (StringUtils.equalsIgnoreCase("chunked", deployedResource.transferEncoding)) { + fail("deployedResource use chunked: " + deployedResource); } } } - protected abstract boolean supportPreemptiveAuthenticationPut(); protected abstract boolean supportPreemptiveAuthenticationGet(); protected abstract boolean supportProxyPreemptiveAuthentication(); - protected void testPreemptiveAuthenticationGet( TestSecurityHandler sh, boolean preemptive ) - { - testPreemptiveAuthentication( sh, preemptive, HttpServletResponse.SC_OK ); + protected void testPreemptiveAuthenticationGet(TestSecurityHandler sh, boolean preemptive) { + testPreemptiveAuthentication(sh, preemptive, HttpServletResponse.SC_OK); } - protected void testPreemptiveAuthenticationPut( TestSecurityHandler sh, boolean preemptive ) - { - testPreemptiveAuthentication( sh, preemptive, HttpServletResponse.SC_CREATED ); + protected void testPreemptiveAuthenticationPut(TestSecurityHandler sh, boolean preemptive) { + testPreemptiveAuthentication(sh, preemptive, HttpServletResponse.SC_CREATED); } - protected void testPreemptiveAuthentication( TestSecurityHandler sh, boolean preemptive, int statusCode ) - { - - if ( preemptive ) - { - assertEquals( "not 1 security handler use " + sh.handlerRequestResponses, 1, - sh.handlerRequestResponses.size() ); - assertEquals( statusCode, sh.handlerRequestResponses.get( 0 ).responseCode ); - } - else - { - assertEquals( "not 2 security handler use " + sh.handlerRequestResponses, 2, - sh.handlerRequestResponses.size() ); - assertEquals( HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( statusCode, sh.handlerRequestResponses.get( 1 ).responseCode ); + protected void testPreemptiveAuthentication(TestSecurityHandler sh, boolean preemptive, int statusCode) { + if (preemptive) { + assertEquals( + "not 1 security handler use " + sh.handlerRequestResponses, 1, sh.handlerRequestResponses.size()); + assertEquals(statusCode, sh.handlerRequestResponses.get(0).responseCode); + } else { + assertEquals( + "not 2 security handler use " + sh.handlerRequestResponses, 2, sh.handlerRequestResponses.size()); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get(0).responseCode); + assertEquals(statusCode, sh.handlerRequestResponses.get(1).responseCode); } } - static class StatusHandler - extends AbstractHandler - { + static class StatusHandler extends AbstractHandler { private int status; - public void setStatusToReturn( int status ) - { + public void setStatusToReturn(int status) { this.status = status; } - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { - if ( status != 0 ) - { - response.setStatus( status ); - baseRequest.setHandled( true ); + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + if (status != 0) { + response.setStatus(status); + baseRequest.setHandled(true); } } } - static class DeployedResource - { + static class DeployedResource { String httpMethod; String requestUri; @@ -2051,21 +1690,19 @@ static class DeployedResource String transferEncoding; - DeployedResource() - { + DeployedResource() { // no op } @Override - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder(); - sb.append( "DeployedResource" ); - sb.append( "{httpMethod='" ).append( httpMethod ).append( '\'' ); - sb.append( ", requestUri='" ).append( requestUri ).append( '\'' ); - sb.append( ", contentLength='" ).append( contentLength ).append( '\'' ); - sb.append( ", transferEncoding='" ).append( transferEncoding ).append( '\'' ); - sb.append( '}' ); + sb.append("DeployedResource"); + sb.append("{httpMethod='").append(httpMethod).append('\''); + sb.append(", requestUri='").append(requestUri).append('\''); + sb.append(", contentLength='").append(contentLength).append('\''); + sb.append(", transferEncoding='").append(transferEncoding).append('\''); + sb.append('}'); return sb.toString(); } } @@ -2073,10 +1710,8 @@ public String toString() /** * */ - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static class PutHandler - extends AbstractHandler - { + @SuppressWarnings("checkstyle:visibilitymodifier") + public static class PutHandler extends AbstractHandler { private final File resourceBase; public List deployedResources = new ArrayList<>(); @@ -2085,206 +1720,179 @@ public static class PutHandler public List handlerRequestResponses = new ArrayList<>(); - public PutHandler( File repositoryDirectory ) - { + public PutHandler(File repositoryDirectory) { this.resourceBase = repositoryDirectory; } - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { - if ( baseRequest.isHandled() || !"PUT".equals( baseRequest.getMethod() ) ) - { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + if (baseRequest.isHandled() || !"PUT".equals(baseRequest.getMethod())) { return; } - baseRequest.setHandled( true ); + baseRequest.setHandled(true); - File file = new File( resourceBase, URLDecoder.decode( request.getPathInfo() ) ); + File file = new File(resourceBase, URLDecoder.decode(request.getPathInfo())); file.getParentFile().mkdirs(); OutputStream out = null; InputStream in = null; - try - { + try { in = request.getInputStream(); - out = new FileOutputStream( file ); - IOUtil.copy( in, out ); + out = new FileOutputStream(file); + IOUtil.copy(in, out); out.close(); out = null; in.close(); in = null; - } - finally - { - IOUtil.close( in ); - IOUtil.close( out ); + } finally { + IOUtil.close(in); + IOUtil.close(out); } putCallNumber++; DeployedResource deployedResource = new DeployedResource(); deployedResource.httpMethod = request.getMethod(); deployedResource.requestUri = request.getRequestURI(); - deployedResource.transferEncoding = request.getHeader( "Transfer-Encoding" ); - deployedResource.contentLength = request.getHeader( "Content-Length" ); - deployedResources.add( deployedResource ); + deployedResource.transferEncoding = request.getHeader("Transfer-Encoding"); + deployedResource.contentLength = request.getHeader("Content-Length"); + deployedResources.add(deployedResource); - response.setStatus( HttpServletResponse.SC_CREATED ); + response.setStatus(HttpServletResponse.SC_CREATED); - handlerRequestResponses.add( - new HandlerRequestResponse( request.getMethod(), ( (Response) response ).getStatus(), - request.getRequestURI() ) ); + handlerRequestResponses.add(new HandlerRequestResponse( + request.getMethod(), ((Response) response).getStatus(), request.getRequestURI())); } } - private static class AuthorizingProxyHandler - extends TestHeaderHandler - { + private static class AuthorizingProxyHandler extends TestHeaderHandler { List handlerRequestResponses = new ArrayList<>(); - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { - System.out.println( " handle proxy request" ); - if ( request.getHeader( "Proxy-Authorization" ) == null ) - { - handlerRequestResponses.add( - new HandlerRequestResponse( request.getMethod(), - HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, - request.getRequestURI() ) ); - response.setStatus( HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED ); - response.addHeader( "Proxy-Authenticate", "Basic realm=\"Squid proxy-caching web server\"" ); - - baseRequest.setHandled( true ); + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + System.out.println(" handle proxy request"); + if (request.getHeader("Proxy-Authorization") == null) { + handlerRequestResponses.add(new HandlerRequestResponse( + request.getMethod(), + HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, + request.getRequestURI())); + response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); + response.addHeader("Proxy-Authenticate", "Basic realm=\"Squid proxy-caching web server\""); + + baseRequest.setHandled(true); return; } - handlerRequestResponses.add( - new HandlerRequestResponse( request.getMethod(), HttpServletResponse.SC_OK, request.getRequestURI() ) ); - super.handle( target, baseRequest, request, response ); + handlerRequestResponses.add(new HandlerRequestResponse( + request.getMethod(), HttpServletResponse.SC_OK, request.getRequestURI())); + super.handle(target, baseRequest, request, response); } } /** * */ - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - private static class TestHeaderHandler - extends AbstractHandler - { + @SuppressWarnings("checkstyle:visibilitymodifier") + private static class TestHeaderHandler extends AbstractHandler { public Map headers = Collections.emptyMap(); public List handlerRequestResponses = new ArrayList<>(); - TestHeaderHandler() - { - } + TestHeaderHandler() {} - public void handle( String target, Request baseRrequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { + public void handle( + String target, Request baseRrequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { headers = new HashMap<>(); - for ( Enumeration e = baseRrequest.getHeaderNames(); e.hasMoreElements(); ) - { + for (Enumeration e = baseRrequest.getHeaderNames(); e.hasMoreElements(); ) { String name = e.nextElement(); - Enumeration headerValues = baseRrequest.getHeaders( name ); + Enumeration headerValues = baseRrequest.getHeaders(name); // as per HTTP spec http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html // multiple values for the same header key are concatenated separated by comma // otherwise we wouldn't notice headers with same key added multiple times StringBuffer combinedHeaderValue = new StringBuffer(); - for ( int i = 0; headerValues.hasMoreElements(); i++ ) - { - if ( i > 0 ) - { - combinedHeaderValue.append( "," ); + for (int i = 0; headerValues.hasMoreElements(); i++) { + if (i > 0) { + combinedHeaderValue.append(","); } - combinedHeaderValue.append( headerValues.nextElement() ); + combinedHeaderValue.append(headerValues.nextElement()); } - headers.put( name, combinedHeaderValue.toString() ); + headers.put(name, combinedHeaderValue.toString()); } - response.setContentType( "text/plain" ); - response.setStatus( HttpServletResponse.SC_OK ); - response.getWriter().print( "Hello, World!" ); + response.setContentType("text/plain"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().print("Hello, World!"); - handlerRequestResponses.add( - new HandlerRequestResponse( baseRrequest.getMethod(), ( (Response) response ).getStatus(), - baseRrequest.getRequestURI() ) ); + handlerRequestResponses.add(new HandlerRequestResponse( + baseRrequest.getMethod(), ((Response) response).getStatus(), baseRrequest.getRequestURI())); - baseRrequest.setHandled( true ); + baseRrequest.setHandled(true); } - } - protected TestSecurityHandler createSecurityHandler() - { + protected TestSecurityHandler createSecurityHandler() { Constraint constraint = new Constraint(); - constraint.setName( Constraint.__BASIC_AUTH ); - constraint.setRoles( new String[]{ "admin" } ); - constraint.setAuthenticate( true ); + constraint.setName(Constraint.__BASIC_AUTH); + constraint.setRoles(new String[] {"admin"}); + constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); - cm.setConstraint( constraint ); - cm.setPathSpec( "/*" ); + cm.setConstraint(constraint); + cm.setPathSpec("/*"); TestSecurityHandler sh = new TestSecurityHandler(); - HashLoginService hashLoginService = new HashLoginService( "MyRealm" ); - hashLoginService.putUser( "user", new Password( "secret" ), new String[] { "admin" } ); - sh.setLoginService( hashLoginService ); - sh.setConstraintMappings( new ConstraintMapping[]{ cm } ); - sh.setAuthenticator ( new BasicAuthenticator() ); + HashLoginService hashLoginService = new HashLoginService("MyRealm"); + hashLoginService.putUser("user", new Password("secret"), new String[] {"admin"}); + sh.setLoginService(hashLoginService); + sh.setConstraintMappings(new ConstraintMapping[] {cm}); + sh.setAuthenticator(new BasicAuthenticator()); return sh; } /** * */ - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static class TestSecurityHandler - extends ConstraintSecurityHandler - { + @SuppressWarnings("checkstyle:visibilitymodifier") + public static class TestSecurityHandler extends ConstraintSecurityHandler { public List handlerRequestResponses = new ArrayList<>(); @Override - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { String method = request.getMethod(); - super.handle( target, baseRequest, request, response ); + super.handle(target, baseRequest, request, response); handlerRequestResponses.add( - new HandlerRequestResponse( method, ( (Response) response ).getStatus(), request.getRequestURI() ) ); + new HandlerRequestResponse(method, ((Response) response).getStatus(), request.getRequestURI())); } } /** * */ - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static class HandlerRequestResponse - { + @SuppressWarnings("checkstyle:visibilitymodifier") + public static class HandlerRequestResponse { public String method; public int responseCode; public String requestUri; - private HandlerRequestResponse( String method, int responseCode, String requestUri ) - { + private HandlerRequestResponse(String method, int responseCode, String requestUri) { this.method = method; this.responseCode = responseCode; this.requestUri = requestUri; } @Override - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder(); - sb.append( "HandlerRequestResponse" ); - sb.append( "{method='" ).append( method ).append( '\'' ); - sb.append( ", responseCode=" ).append( responseCode ); - sb.append( ", requestUri='" ).append( requestUri ).append( '\'' ); - sb.append( '}' ); + sb.append("HandlerRequestResponse"); + sb.append("{method='").append(method).append('\''); + sb.append(", responseCode=").append(responseCode); + sb.append(", requestUri='").append(requestUri).append('\''); + sb.append('}'); return sb.toString(); } } @@ -2301,75 +1909,87 @@ public String toString() * @param forUrl the url that triggered the exception * @param forReasonPhrase the optional status line reason phrase the server returned */ - protected void verifyWagonExceptionMessage( Exception e, int forStatusCode, String forUrl, String forReasonPhrase ) - { + protected void verifyWagonExceptionMessage(Exception e, int forStatusCode, String forUrl, String forReasonPhrase) { // TODO: handle AuthenticationException for Wagon.connect() calls - assertNotNull( e ); - try - { - assertTrue( "only verify instances of WagonException", e instanceof WagonException ); + assertNotNull(e); + try { + assertTrue("only verify instances of WagonException", e instanceof WagonException); String reasonPhrase; String assertMessageForBadMessage = "exception message not described properly"; - switch ( forStatusCode ) - { + switch (forStatusCode) { case HttpServletResponse.SC_NOT_FOUND: // TODO: add test for 410: Gone? - assertTrue( "404 not found response should throw ResourceDoesNotExistException", - e instanceof ResourceDoesNotExistException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - ? " Not Found" : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "resource missing at " + forUrl + ", status: 404" - + reasonPhrase, e.getMessage() ); + assertTrue( + "404 not found response should throw ResourceDoesNotExistException", + e instanceof ResourceDoesNotExistException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Not Found" + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "resource missing at " + forUrl + ", status: 404" + reasonPhrase, + e.getMessage()); break; case HttpServletResponse.SC_UNAUTHORIZED: // FIXME assumes Wagon.get()/put() returning 401 instead of Wagon.connect() - assertTrue( "401 Unauthorized should throw AuthorizationException since " + assertTrue( + "401 Unauthorized should throw AuthorizationException since " + " AuthenticationException is not explicitly declared as thrown from wagon " + "methods", - e instanceof AuthorizationException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - ? " Unauthorized" : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "authentication failed for " + forUrl + ", status: 401" - + reasonPhrase, e.getMessage() ); + e instanceof AuthorizationException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Unauthorized" + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "authentication failed for " + forUrl + ", status: 401" + reasonPhrase, + e.getMessage()); break; case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: - assertTrue( "407 Proxy authentication required should throw AuthorizationException", - e instanceof AuthorizationException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - ? " Proxy Authentication Required" : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "proxy authentication failed for " - + forUrl + ", status: 407" + reasonPhrase, e.getMessage() ); + assertTrue( + "407 Proxy authentication required should throw AuthorizationException", + e instanceof AuthorizationException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Proxy Authentication Required" + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "proxy authentication failed for " + forUrl + ", status: 407" + reasonPhrase, + e.getMessage()); break; case HttpServletResponse.SC_FORBIDDEN: - assertTrue( "403 Forbidden should throw AuthorizationException", - e instanceof AuthorizationException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - ? " Forbidden" : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "authorization failed for " + forUrl + ", status: 403" - + reasonPhrase, e.getMessage() ); + assertTrue( + "403 Forbidden should throw AuthorizationException", e instanceof AuthorizationException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Forbidden" + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "authorization failed for " + forUrl + ", status: 403" + reasonPhrase, + e.getMessage()); break; default: - assertTrue( "transfer failures should at least be wrapped in a TransferFailedException", e - instanceof TransferFailedException ); - assertTrue( "expected status code for transfer failures should be >= 400", - forStatusCode >= HttpServletResponse.SC_BAD_REQUEST ); + assertTrue( + "transfer failures should at least be wrapped in a TransferFailedException", + e instanceof TransferFailedException); + assertTrue( + "expected status code for transfer failures should be >= 400", + forStatusCode >= HttpServletResponse.SC_BAD_REQUEST); reasonPhrase = forReasonPhrase == null ? "" : " " + forReasonPhrase; - assertEquals( assertMessageForBadMessage, "transfer failed for " + forUrl + ", status: " - + forStatusCode + reasonPhrase, e.getMessage() ); + assertEquals( + assertMessageForBadMessage, + "transfer failed for " + forUrl + ", status: " + forStatusCode + reasonPhrase, + e.getMessage()); break; } - } - catch ( AssertionError assertionError ) - { - logger.error( "Exception which failed assertions: ", e ); + } catch (AssertionError assertionError) { + logger.error("Exception which failed assertions: ", e); throw assertionError; } - } - } diff --git a/wagon-providers/wagon-file/src/main/java/org/apache/maven/wagon/providers/file/FileWagon.java b/wagon-providers/wagon-file/src/main/java/org/apache/maven/wagon/providers/file/FileWagon.java index 1e8695ecf..778f28d41 100644 --- a/wagon-providers/wagon-file/src/main/java/org/apache/maven/wagon/providers/file/FileWagon.java +++ b/wagon-providers/wagon-file/src/main/java/org/apache/maven/wagon/providers/file/FileWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.file; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -48,115 +47,90 @@ * * @plexus.component role="org.apache.maven.wagon.Wagon" role-hint="file" instantiation-strategy="per-lookup" */ -public class FileWagon - extends StreamWagon -{ - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException - { - if ( getRepository().getBasedir() == null ) - { - throw new TransferFailedException( "Unable to operate with a null basedir." ); +public class FileWagon extends StreamWagon { + public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException { + if (getRepository().getBasedir() == null) { + throw new TransferFailedException("Unable to operate with a null basedir."); } Resource resource = inputData.getResource(); - File file = new File( getRepository().getBasedir(), resource.getName() ); + File file = new File(getRepository().getBasedir(), resource.getName()); - if ( !file.exists() ) - { - throw new ResourceDoesNotExistException( "File: " + file + " does not exist" ); + if (!file.exists()) { + throw new ResourceDoesNotExistException("File: " + file + " does not exist"); } - try - { - InputStream in = new BufferedInputStream( new FileInputStream( file ) ); + try { + InputStream in = new BufferedInputStream(new FileInputStream(file)); - inputData.setInputStream( in ); + inputData.setInputStream(in); - resource.setContentLength( file.length() ); + resource.setContentLength(file.length()); - resource.setLastModified( file.lastModified() ); - } - catch ( FileNotFoundException e ) - { - throw new TransferFailedException( "Could not read from file: " + file.getAbsolutePath(), e ); + resource.setLastModified(file.lastModified()); + } catch (FileNotFoundException e) { + throw new TransferFailedException("Could not read from file: " + file.getAbsolutePath(), e); } } - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - if ( getRepository().getBasedir() == null ) - { - throw new TransferFailedException( "Unable to operate with a null basedir." ); + public void fillOutputData(OutputData outputData) throws TransferFailedException { + if (getRepository().getBasedir() == null) { + throw new TransferFailedException("Unable to operate with a null basedir."); } Resource resource = outputData.getResource(); - File file = new File( getRepository().getBasedir(), resource.getName() ); + File file = new File(getRepository().getBasedir(), resource.getName()); - createParentDirectories( file ); + createParentDirectories(file); - OutputStream outputStream = new BufferedOutputStream( new LazyFileOutputStream( file ) ); + OutputStream outputStream = new BufferedOutputStream(new LazyFileOutputStream(file)); - outputData.setOutputStream( outputStream ); + outputData.setOutputStream(outputStream); } - protected void openConnectionInternal() - throws ConnectionException - { - if ( getRepository() == null ) - { - throw new ConnectionException( "Unable to operate with a null repository." ); + protected void openConnectionInternal() throws ConnectionException { + if (getRepository() == null) { + throw new ConnectionException("Unable to operate with a null repository."); } - if ( getRepository().getBasedir() == null ) - { + if (getRepository().getBasedir() == null) { // This condition is possible when using wagon-file under integration testing conditions. - fireSessionDebug( "Using a null basedir." ); + fireSessionDebug("Using a null basedir."); return; } // Check the File repository exists - File basedir = new File( getRepository().getBasedir() ); - if ( !basedir.exists() ) - { - if ( !basedir.mkdirs() ) - { - throw new ConnectionException( "Repository path " + basedir + " does not exist," - + " and cannot be created." ); + File basedir = new File(getRepository().getBasedir()); + if (!basedir.exists()) { + if (!basedir.mkdirs()) { + throw new ConnectionException( + "Repository path " + basedir + " does not exist," + " and cannot be created."); } } - if ( !basedir.canRead() ) - { - throw new ConnectionException( "Repository path " + basedir + " cannot be read" ); + if (!basedir.canRead()) { + throw new ConnectionException("Repository path " + basedir + " cannot be read"); } } - public void closeConnection() - { - } + public void closeConnection() {} - public boolean supportsDirectoryCopy() - { + public boolean supportsDirectoryCopy() { // TODO: should we test for null basedir here? return true; } - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( getRepository().getBasedir() == null ) - { - throw new TransferFailedException( "Unable to putDirectory() with a null basedir." ); + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (getRepository().getBasedir() == null) { + throw new TransferFailedException("Unable to putDirectory() with a null basedir."); } - File path = resolveDestinationPath( destinationDirectory ); + File path = resolveDestinationPath(destinationDirectory); - try - { + try { /* * Done to address issue found in HP-UX with regards to "." directory references. Details found in .. * WAGON-30 - wagon-file failed when used by maven-site-plugin WAGON-33 - FileWagon#putDirectory() fails in @@ -167,104 +141,83 @@ public void putDirectory( File sourceDirectory, String destinationDirectory ) */ File realFile = path.getCanonicalFile(); realFile.mkdirs(); - } - catch ( IOException e ) - { + } catch (IOException e) { // Fall back to standard way if getCanonicalFile() fails. path.mkdirs(); } - if ( !path.exists() || !path.isDirectory() ) - { + if (!path.exists() || !path.isDirectory()) { String emsg = "Could not make directory '" + path.getAbsolutePath() + "'."; // Add assistive message in case of failure. - File basedir = new File( getRepository().getBasedir() ); - if ( !basedir.canWrite() ) - { + File basedir = new File(getRepository().getBasedir()); + if (!basedir.canWrite()) { emsg += " The base directory " + basedir + " is read-only."; } - throw new TransferFailedException( emsg ); + throw new TransferFailedException(emsg); } - try - { - FileUtils.copyDirectoryStructure( sourceDirectory, path ); - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error copying directory structure", e ); + try { + FileUtils.copyDirectoryStructure(sourceDirectory, path); + } catch (IOException e) { + throw new TransferFailedException("Error copying directory structure", e); } } - private File resolveDestinationPath( String destinationPath ) - { + private File resolveDestinationPath(String destinationPath) { String basedir = getRepository().getBasedir(); - destinationPath = destinationPath.replace( "\\", "/" ); + destinationPath = destinationPath.replace("\\", "/"); File path; - if ( destinationPath.equals( "." ) ) - { - path = new File( basedir ); - } - else - { - path = new File( basedir, destinationPath ); + if (destinationPath.equals(".")) { + path = new File(basedir); + } else { + path = new File(basedir, destinationPath); } return path; } - public List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( getRepository().getBasedir() == null ) - { - throw new TransferFailedException( "Unable to getFileList() with a null basedir." ); + public List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (getRepository().getBasedir() == null) { + throw new TransferFailedException("Unable to getFileList() with a null basedir."); } - File path = resolveDestinationPath( destinationDirectory ); + File path = resolveDestinationPath(destinationDirectory); - if ( !path.exists() ) - { - throw new ResourceDoesNotExistException( "Directory does not exist: " + destinationDirectory ); + if (!path.exists()) { + throw new ResourceDoesNotExistException("Directory does not exist: " + destinationDirectory); } - if ( !path.isDirectory() ) - { - throw new ResourceDoesNotExistException( "Path is not a directory: " + destinationDirectory ); + if (!path.isDirectory()) { + throw new ResourceDoesNotExistException("Path is not a directory: " + destinationDirectory); } File[] files = path.listFiles(); - List list = new ArrayList<>( files.length ); - for ( File file : files ) - { + List list = new ArrayList<>(files.length); + for (File file : files) { String name = file.getName(); - if ( file.isDirectory() && !name.endsWith( "/" ) ) - { + if (file.isDirectory() && !name.endsWith("/")) { name += "/"; } - list.add( name ); + list.add(name); } return list; } - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - if ( getRepository().getBasedir() == null ) - { - throw new TransferFailedException( "Unable to getFileList() with a null basedir." ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + if (getRepository().getBasedir() == null) { + throw new TransferFailedException("Unable to getFileList() with a null basedir."); } - File file = resolveDestinationPath( resourceName ); + File file = resolveDestinationPath(resourceName); - if ( resourceName.endsWith( "/" ) ) - { + if (resourceName.endsWith("/")) { return file.isDirectory(); } diff --git a/wagon-providers/wagon-file/src/test/java/org/apache/maven/wagon/providers/file/FileWagonTest.java b/wagon-providers/wagon-file/src/test/java/org/apache/maven/wagon/providers/file/FileWagonTest.java index ce48b8130..e1b551f4c 100644 --- a/wagon-providers/wagon-file/src/test/java/org/apache/maven/wagon/providers/file/FileWagonTest.java +++ b/wagon-providers/wagon-file/src/test/java/org/apache/maven/wagon/providers/file/FileWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.file; + +import java.io.File; +import java.io.IOException; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.FileTestUtils; @@ -27,25 +29,17 @@ import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; -import java.io.File; -import java.io.IOException; - /** * @author Michal Maczka * */ -public class FileWagonTest - extends StreamingWagonTestCase -{ - protected String getProtocol() - { +public class FileWagonTest extends StreamingWagonTestCase { + protected String getProtocol() { return "file"; } - protected String getTestRepositoryUrl() - throws IOException - { - File file = FileTestUtils.createUniqueDir( getName() + ".file-repository." ); + protected String getTestRepositoryUrl() throws IOException { + File file = FileTestUtils.createUniqueDir(getName() + ".file-repository."); return file.toPath().toUri().toASCIIString(); } @@ -57,35 +51,31 @@ protected String getTestRepositoryUrl() * @throws ConnectionException * @throws AuthenticationException */ - public void testNullFileWagon() throws ConnectionException, AuthenticationException - { + public void testNullFileWagon() throws ConnectionException, AuthenticationException { Wagon wagon = new FileWagon(); Resource resource = new Resource(); - resource.setContentLength( 100000 ); + resource.setContentLength(100000); Repository repository = new Repository(); - wagon.connect( repository ); + wagon.connect(repository); wagon.disconnect(); } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - return new File( repository.getBasedir(), resource.getName() ).lastModified(); + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + return new File(repository.getBasedir(), resource.getName()).lastModified(); } - public void testResourceExists() - throws Exception - { - String url = new File( getBasedir() ).toPath().toUri().toASCIIString(); + public void testResourceExists() throws Exception { + String url = new File(getBasedir()).toPath().toUri().toASCIIString(); Wagon wagon = new FileWagon(); - Repository repository = new Repository( "someID", url ); - wagon.connect( repository ); + Repository repository = new Repository("someID", url); + wagon.connect(repository); - assertTrue( wagon.resourceExists( "target" ) ); - assertTrue( wagon.resourceExists( "target/" ) ); - assertTrue( wagon.resourceExists( "pom.xml" ) ); + assertTrue(wagon.resourceExists("target")); + assertTrue(wagon.resourceExists("target/")); + assertTrue(wagon.resourceExists("pom.xml")); - assertFalse( wagon.resourceExists( "pom.xml/" ) ); + assertFalse(wagon.resourceExists("pom.xml/")); wagon.disconnect(); } diff --git a/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpHttpWagon.java b/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpHttpWagon.java index f657c3534..e2067face 100644 --- a/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpHttpWagon.java +++ b/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpHttpWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ftp; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ftp; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPHTTPClient; @@ -33,21 +32,17 @@ * role-hint="ftph" * instantiation-strategy="per-lookup" */ -public class FtpHttpWagon - extends FtpWagon -{ +public class FtpHttpWagon extends FtpWagon { - private static final Logger LOG = LoggerFactory.getLogger( FtpHttpWagon.class ); + private static final Logger LOG = LoggerFactory.getLogger(FtpHttpWagon.class); @Override - protected FTPClient createClient() - { + protected FTPClient createClient() { ProxyInfo proxyInfo = getProxyInfo(); - - LOG.debug( "Creating FTP over HTTP proxy client. Proxy Host: [{}].", proxyInfo.getHost() ); - return new FTPHTTPClient( proxyInfo.getHost(), proxyInfo.getPort(), proxyInfo.getUserName(), - proxyInfo.getPassword() ); - } + LOG.debug("Creating FTP over HTTP proxy client. Proxy Host: [{}].", proxyInfo.getHost()); + return new FTPHTTPClient( + proxyInfo.getHost(), proxyInfo.getPort(), proxyInfo.getUserName(), proxyInfo.getPassword()); + } } diff --git a/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpWagon.java b/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpWagon.java index 8dc5208e1..7fd651d47 100644 --- a/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpWagon.java +++ b/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ftp; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ftp; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.net.ProtocolCommandEvent; @@ -40,16 +48,6 @@ import org.apache.maven.wagon.repository.RepositoryPermissions; import org.apache.maven.wagon.resource.Resource; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - - /** * FtpWagon * @@ -58,9 +56,7 @@ * role-hint="ftp" * instantiation-strategy="per-lookup" */ -public class FtpWagon - extends StreamWagon -{ +public class FtpWagon extends StreamWagon { private FTPClient ftp; /** @@ -73,63 +69,53 @@ public class FtpWagon */ private String controlEncoding = FTP.DEFAULT_CONTROL_ENCODING; - public boolean isPassiveMode() - { + public boolean isPassiveMode() { return passiveMode; } - public void setPassiveMode( boolean passiveMode ) - { + public void setPassiveMode(boolean passiveMode) { this.passiveMode = passiveMode; } @Override - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { + protected void openConnectionInternal() throws ConnectionException, AuthenticationException { AuthenticationInfo authInfo = getAuthenticationInfo(); - if ( authInfo == null ) - { - throw new NullPointerException( "authenticationInfo cannot be null" ); + if (authInfo == null) { + throw new NullPointerException("authenticationInfo cannot be null"); } - if ( authInfo.getUserName() == null ) - { - authInfo.setUserName( System.getProperty( "user.name" ) ); + if (authInfo.getUserName() == null) { + authInfo.setUserName(System.getProperty("user.name")); } String username = authInfo.getUserName(); String password = authInfo.getPassword(); - if ( username == null ) - { - throw new AuthenticationException( "Username not specified for repository " + getRepository().getId() ); + if (username == null) { + throw new AuthenticationException( + "Username not specified for repository " + getRepository().getId()); } - if ( password == null ) - { - throw new AuthenticationException( "Password not specified for repository " + getRepository().getId() ); + if (password == null) { + throw new AuthenticationException( + "Password not specified for repository " + getRepository().getId()); } String host = getRepository().getHost(); ftp = createClient(); - ftp.setDefaultTimeout( getTimeout() ); - ftp.setDataTimeout( getTimeout() ); - ftp.setControlEncoding( getControlEncoding() ); + ftp.setDefaultTimeout(getTimeout()); + ftp.setDataTimeout(getTimeout()); + ftp.setControlEncoding(getControlEncoding()); - ftp.addProtocolCommandListener( new PrintCommandListener( this ) ); + ftp.addProtocolCommandListener(new PrintCommandListener(this)); - try - { - if ( getRepository().getPort() != WagonConstants.UNKNOWN_PORT ) - { - ftp.connect( host, getRepository().getPort() ); - } - else - { - ftp.connect( host ); + try { + if (getRepository().getPort() != WagonConstants.UNKNOWN_PORT) { + ftp.connect(host, getRepository().getPort()); + } else { + ftp.connect(host); } // After connection attempt, you should check the reply code to @@ -137,212 +123,166 @@ protected void openConnectionInternal() // success. int reply = ftp.getReplyCode(); - if ( !FTPReply.isPositiveCompletion( reply ) ) - { + if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); - throw new AuthenticationException( "FTP server refused connection." ); + throw new AuthenticationException("FTP server refused connection."); } - } - catch ( IOException e ) - { - if ( ftp.isConnected() ) - { - try - { - fireSessionError( e ); + } catch (IOException e) { + if (ftp.isConnected()) { + try { + fireSessionError(e); ftp.disconnect(); - } - catch ( IOException f ) - { + } catch (IOException f) { // do nothing } } - throw new AuthenticationException( "Could not connect to server.", e ); + throw new AuthenticationException("Could not connect to server.", e); } - try - { - if ( !ftp.login( username, password ) ) - { - throw new AuthenticationException( "Cannot login to remote system" ); + try { + if (!ftp.login(username, password)) { + throw new AuthenticationException("Cannot login to remote system"); } - fireSessionDebug( "Remote system is " + ftp.getSystemName() ); + fireSessionDebug("Remote system is " + ftp.getSystemName()); // Set to binary mode. - ftp.setFileType( FTP.BINARY_FILE_TYPE ); - ftp.setListHiddenFiles( true ); + ftp.setFileType(FTP.BINARY_FILE_TYPE); + ftp.setListHiddenFiles(true); // Use passive mode as default because most of us are // behind firewalls these days. - if ( isPassiveMode() ) - { + if (isPassiveMode()) { ftp.enterLocalPassiveMode(); } - } - catch ( IOException e ) - { - throw new ConnectionException( "Cannot login to remote system", e ); + } catch (IOException e) { + throw new ConnectionException("Cannot login to remote system", e); } } - protected FTPClient createClient() - { + protected FTPClient createClient() { return new FTPClient(); } @Override - protected void firePutCompleted( Resource resource, File file ) - { - try - { + protected void firePutCompleted(Resource resource, File file) { + try { // TODO [BP]: verify the order is correct ftp.completePendingCommand(); RepositoryPermissions permissions = repository.getPermissions(); - if ( permissions != null && permissions.getGroup() != null ) - { + if (permissions != null && permissions.getGroup() != null) { // ignore failures - ftp.sendSiteCommand( "CHGRP " + permissions.getGroup() + " " + resource.getName() ); + ftp.sendSiteCommand("CHGRP " + permissions.getGroup() + " " + resource.getName()); } - if ( permissions != null && permissions.getFileMode() != null ) - { + if (permissions != null && permissions.getFileMode() != null) { // ignore failures - ftp.sendSiteCommand( "CHMOD " + permissions.getFileMode() + " " + resource.getName() ); + ftp.sendSiteCommand("CHMOD " + permissions.getFileMode() + " " + resource.getName()); } - } - catch ( IOException e ) - { + } catch (IOException e) { // TODO: handle // michal I am not sure what error means in that context // I think that we will be able to recover or simply we will fail later on } - super.firePutCompleted( resource, file ); + super.firePutCompleted(resource, file); } @Override - protected void fireGetCompleted( Resource resource, File localFile ) - { - try - { + protected void fireGetCompleted(Resource resource, File localFile) { + try { ftp.completePendingCommand(); - } - catch ( IOException e ) - { + } catch (IOException e) { // TODO: handle // michal I am not sure what error means in that context // actually I am not even sure why we have to invoke that command // I think that we will be able to recover or simply we will fail later on } - super.fireGetCompleted( resource, localFile ); + super.fireGetCompleted(resource, localFile); } @Override - public void closeConnection() - throws ConnectionException - { - if ( ftp != null && ftp.isConnected() ) - { - try - { + public void closeConnection() throws ConnectionException { + if (ftp != null && ftp.isConnected()) { + try { // This is a NPE rethink shutting down the streams ftp.disconnect(); - } - catch ( IOException e ) - { - throw new ConnectionException( "Failed to close connection to FTP repository", e ); + } catch (IOException e) { + throw new ConnectionException("Failed to close connection to FTP repository", e); } } } @Override - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { + public void fillOutputData(OutputData outputData) throws TransferFailedException { OutputStream os; Resource resource = outputData.getResource(); RepositoryPermissions permissions = repository.getPermissions(); - try - { - if ( !ftp.changeWorkingDirectory( getRepository().getBasedir() ) ) - { + try { + if (!ftp.changeWorkingDirectory(getRepository().getBasedir())) { throw new TransferFailedException( - "Required directory: '" + getRepository().getBasedir() + "' " + "is missing" ); + "Required directory: '" + getRepository().getBasedir() + "' " + "is missing"); } - String[] dirs = PathUtils.dirnames( resource.getName() ); + String[] dirs = PathUtils.dirnames(resource.getName()); - for ( String dir : dirs ) - { - boolean dirChanged = ftp.changeWorkingDirectory( dir ); + for (String dir : dirs) { + boolean dirChanged = ftp.changeWorkingDirectory(dir); - if ( !dirChanged ) - { + if (!dirChanged) { // first, try to create it - boolean success = ftp.makeDirectory( dir ); + boolean success = ftp.makeDirectory(dir); - if ( success ) - { - if ( permissions != null && permissions.getGroup() != null ) - { + if (success) { + if (permissions != null && permissions.getGroup() != null) { // ignore failures - ftp.sendSiteCommand( "CHGRP " + permissions.getGroup() + " " + dir ); + ftp.sendSiteCommand("CHGRP " + permissions.getGroup() + " " + dir); } - if ( permissions != null && permissions.getDirectoryMode() != null ) - { + if (permissions != null && permissions.getDirectoryMode() != null) { // ignore failures - ftp.sendSiteCommand( "CHMOD " + permissions.getDirectoryMode() + " " + dir ); + ftp.sendSiteCommand("CHMOD " + permissions.getDirectoryMode() + " " + dir); } - dirChanged = ftp.changeWorkingDirectory( dir ); + dirChanged = ftp.changeWorkingDirectory(dir); } } - if ( !dirChanged ) - { - throw new TransferFailedException( "Unable to create directory " + dir ); + if (!dirChanged) { + throw new TransferFailedException("Unable to create directory " + dir); } } // we come back to original basedir so // FTP wagon is ready for next requests - if ( !ftp.changeWorkingDirectory( getRepository().getBasedir() ) ) - { - throw new TransferFailedException( "Unable to return to the base directory" ); + if (!ftp.changeWorkingDirectory(getRepository().getBasedir())) { + throw new TransferFailedException("Unable to return to the base directory"); } - os = ftp.storeFileStream( resource.getName() ); - - if ( os == null ) - { - String msg = - "Cannot transfer resource: '" + resource + "'. Output stream is null. FTP Server response: " - + ftp.getReplyString(); + os = ftp.storeFileStream(resource.getName()); - throw new TransferFailedException( msg ); + if (os == null) { + String msg = "Cannot transfer resource: '" + resource + + "'. Output stream is null. FTP Server response: " + ftp.getReplyString(); + throw new TransferFailedException(msg); } - fireTransferDebug( "resource = " + resource ); + fireTransferDebug("resource = " + resource); - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error transferring over FTP", e ); + } catch (IOException e) { + throw new TransferFailedException("Error transferring over FTP", e); } - outputData.setOutputStream( os ); - + outputData.setOutputStream(os); } // ---------------------------------------------------------------------- @@ -350,67 +290,57 @@ public void fillOutputData( OutputData outputData ) // ---------------------------------------------------------------------- @Override - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException - { + public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException { InputStream is; Resource resource = inputData.getResource(); - try - { - ftpChangeDirectory( resource ); + try { + ftpChangeDirectory(resource); - String filename = PathUtils.filename( resource.getName() ); - FTPFile[] ftpFiles = ftp.listFiles( filename ); + String filename = PathUtils.filename(resource.getName()); + FTPFile[] ftpFiles = ftp.listFiles(filename); - if ( ftpFiles == null || ftpFiles.length <= 0 ) - { - throw new ResourceDoesNotExistException( "Could not find file: '" + resource + "'" ); + if (ftpFiles == null || ftpFiles.length <= 0) { + throw new ResourceDoesNotExistException("Could not find file: '" + resource + "'"); } long contentLength = ftpFiles[0].getSize(); - //@todo check how it works! javadoc of common login says: + // @todo check how it works! javadoc of common login says: // Returns the file timestamp. This usually the last modification time. // Calendar timestamp = ftpFiles[0].getTimestamp(); long lastModified = timestamp != null ? timestamp.getTimeInMillis() : 0; - resource.setContentLength( contentLength ); + resource.setContentLength(contentLength); - resource.setLastModified( lastModified ); + resource.setLastModified(lastModified); - is = ftp.retrieveFileStream( filename ); - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error transferring file via FTP", e ); + is = ftp.retrieveFileStream(filename); + } catch (IOException e) { + throw new TransferFailedException("Error transferring file via FTP", e); } - inputData.setInputStream( is ); + inputData.setInputStream(is); } - private void ftpChangeDirectory( Resource resource ) - throws IOException, TransferFailedException, ResourceDoesNotExistException - { - if ( !ftp.changeWorkingDirectory( getRepository().getBasedir() ) ) - { + private void ftpChangeDirectory(Resource resource) + throws IOException, TransferFailedException, ResourceDoesNotExistException { + if (!ftp.changeWorkingDirectory(getRepository().getBasedir())) { throw new ResourceDoesNotExistException( - "Required directory: '" + getRepository().getBasedir() + "' " + "is missing" ); + "Required directory: '" + getRepository().getBasedir() + "' " + "is missing"); } - String[] dirs = PathUtils.dirnames( resource.getName() ); + String[] dirs = PathUtils.dirnames(resource.getName()); - for ( String dir : dirs ) - { - boolean dirChanged = ftp.changeWorkingDirectory( dir ); + for (String dir : dirs) { + boolean dirChanged = ftp.changeWorkingDirectory(dir); - if ( !dirChanged ) - { + if (!dirChanged) { String msg = "Resource " + resource + " not found. Directory " + dir + " does not exist"; - throw new ResourceDoesNotExistException( msg ); + throw new ResourceDoesNotExistException(msg); } } } @@ -418,285 +348,217 @@ private void ftpChangeDirectory( Resource resource ) /** * */ - public class PrintCommandListener - implements ProtocolCommandListener - { + public class PrintCommandListener implements ProtocolCommandListener { private FtpWagon wagon; - public PrintCommandListener( FtpWagon wagon ) - { + public PrintCommandListener(FtpWagon wagon) { this.wagon = wagon; } @Override - public void protocolCommandSent( ProtocolCommandEvent event ) - { - wagon.fireSessionDebug( "Command sent: " + event.getMessage() ); - + public void protocolCommandSent(ProtocolCommandEvent event) { + wagon.fireSessionDebug("Command sent: " + event.getMessage()); } @Override - public void protocolReplyReceived( ProtocolCommandEvent event ) - { - wagon.fireSessionDebug( "Reply received: " + event.getMessage() ); + public void protocolReplyReceived(ProtocolCommandEvent event) { + wagon.fireSessionDebug("Reply received: " + event.getMessage()); } } @Override - protected void fireSessionDebug( String msg ) - { - super.fireSessionDebug( msg ); + protected void fireSessionDebug(String msg) { + super.fireSessionDebug(msg); } @Override - public List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( destinationDirectory ); + public List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(destinationDirectory); - try - { - ftpChangeDirectory( resource ); + try { + ftpChangeDirectory(resource); - String filename = PathUtils.filename( resource.getName() ); - FTPFile[] ftpFiles = ftp.listFiles( filename ); + String filename = PathUtils.filename(resource.getName()); + FTPFile[] ftpFiles = ftp.listFiles(filename); - if ( ftpFiles == null || ftpFiles.length <= 0 ) - { - throw new ResourceDoesNotExistException( "Could not find file: '" + resource + "'" ); + if (ftpFiles == null || ftpFiles.length <= 0) { + throw new ResourceDoesNotExistException("Could not find file: '" + resource + "'"); } List ret = new ArrayList<>(); - for ( FTPFile file : ftpFiles ) - { + for (FTPFile file : ftpFiles) { String name = file.getName(); - if ( file.isDirectory() && !name.endsWith( "/" ) ) - { + if (file.isDirectory() && !name.endsWith("/")) { name += "/"; } - ret.add( name ); + ret.add(name); } return ret; - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error transferring file via FTP", e ); + } catch (IOException e) { + throw new TransferFailedException("Error transferring file via FTP", e); } } @Override - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - Resource resource = new Resource( resourceName ); - - try - { - ftpChangeDirectory( resource ); - - String filename = PathUtils.filename( resource.getName() ); - int status = ftp.stat( filename ); - - return ( ( status == FTPReply.FILE_STATUS ) || ( status == FTPReply.DIRECTORY_STATUS ) || ( status - == FTPReply.FILE_STATUS_OK ) // not in the RFC but used by some FTP servers - || ( status == FTPReply.COMMAND_OK ) // not in the RFC but used by some FTP servers - || ( status == FTPReply.SYSTEM_STATUS ) ); - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error transferring file via FTP", e ); - } - catch ( ResourceDoesNotExistException e ) - { + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + Resource resource = new Resource(resourceName); + + try { + ftpChangeDirectory(resource); + + String filename = PathUtils.filename(resource.getName()); + int status = ftp.stat(filename); + + return ((status == FTPReply.FILE_STATUS) + || (status == FTPReply.DIRECTORY_STATUS) + || (status == FTPReply.FILE_STATUS_OK) // not in the RFC but used by some FTP servers + || (status == FTPReply.COMMAND_OK) // not in the RFC but used by some FTP servers + || (status == FTPReply.SYSTEM_STATUS)); + } catch (IOException e) { + throw new TransferFailedException("Error transferring file via FTP", e); + } catch (ResourceDoesNotExistException e) { return false; } } @Override - public boolean supportsDirectoryCopy() - { + public boolean supportsDirectoryCopy() { return true; } @Override - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { // Change to root. - try - { - if ( !ftp.changeWorkingDirectory( getRepository().getBasedir() ) ) - { + try { + if (!ftp.changeWorkingDirectory(getRepository().getBasedir())) { RepositoryPermissions permissions = getRepository().getPermissions(); - if ( !makeFtpDirectoryRecursive( getRepository().getBasedir(), permissions ) ) - { + if (!makeFtpDirectoryRecursive(getRepository().getBasedir(), permissions)) { throw new TransferFailedException( - "Required directory: '" + getRepository().getBasedir() + "' " + "could not get created" ); + "Required directory: '" + getRepository().getBasedir() + "' " + "could not get created"); } // try it again sam ... - if ( !ftp.changeWorkingDirectory( getRepository().getBasedir() ) ) - { - throw new TransferFailedException( "Required directory: '" + getRepository().getBasedir() + "' " - + "is missing and could not get created" ); + if (!ftp.changeWorkingDirectory(getRepository().getBasedir())) { + throw new TransferFailedException("Required directory: '" + + getRepository().getBasedir() + "' " + "is missing and could not get created"); } } - } - catch ( IOException e ) - { - throw new TransferFailedException( "Cannot change to root path " + getRepository().getBasedir(), e ); + } catch (IOException e) { + throw new TransferFailedException( + "Cannot change to root path " + getRepository().getBasedir(), e); } fireTransferDebug( - "Recursively uploading directory " + sourceDirectory.getAbsolutePath() + " as " + destinationDirectory ); - ftpRecursivePut( sourceDirectory, destinationDirectory ); + "Recursively uploading directory " + sourceDirectory.getAbsolutePath() + " as " + destinationDirectory); + ftpRecursivePut(sourceDirectory, destinationDirectory); } - private void ftpRecursivePut( File sourceFile, String fileName ) - throws TransferFailedException - { + private void ftpRecursivePut(File sourceFile, String fileName) throws TransferFailedException { final RepositoryPermissions permissions = repository.getPermissions(); - fireTransferDebug( "processing = " + sourceFile.getAbsolutePath() + " as " + fileName ); + fireTransferDebug("processing = " + sourceFile.getAbsolutePath() + " as " + fileName); - if ( sourceFile.isDirectory() ) - { - if ( !fileName.equals( "." ) ) - { - try - { + if (sourceFile.isDirectory()) { + if (!fileName.equals(".")) { + try { // change directory if it already exists. - if ( !ftp.changeWorkingDirectory( fileName ) ) - { + if (!ftp.changeWorkingDirectory(fileName)) { // first, try to create it - if ( makeFtpDirectoryRecursive( fileName, permissions ) ) - { - if ( !ftp.changeWorkingDirectory( fileName ) ) - { - throw new TransferFailedException( - "Unable to change cwd on ftp server to " + fileName + " when processing " - + sourceFile.getAbsolutePath() ); + if (makeFtpDirectoryRecursive(fileName, permissions)) { + if (!ftp.changeWorkingDirectory(fileName)) { + throw new TransferFailedException("Unable to change cwd on ftp server to " + fileName + + " when processing " + sourceFile.getAbsolutePath()); } - } - else - { - throw new TransferFailedException( - "Unable to create directory " + fileName + " when processing " - + sourceFile.getAbsolutePath() ); + } else { + throw new TransferFailedException("Unable to create directory " + fileName + + " when processing " + sourceFile.getAbsolutePath()); } } - } - catch ( IOException e ) - { + } catch (IOException e) { throw new TransferFailedException( - "IOException caught while processing path at " + sourceFile.getAbsolutePath(), e ); + "IOException caught while processing path at " + sourceFile.getAbsolutePath(), e); } } File[] files = sourceFile.listFiles(); - if ( files != null && files.length > 0 ) - { - fireTransferDebug( "listing children of = " + sourceFile.getAbsolutePath() + " found " + files.length ); + if (files != null && files.length > 0) { + fireTransferDebug("listing children of = " + sourceFile.getAbsolutePath() + " found " + files.length); // Directories first, then files. Let's go deep early. - for ( File file : files ) - { - if ( file.isDirectory() ) - { - ftpRecursivePut( file, file.getName() ); + for (File file : files) { + if (file.isDirectory()) { + ftpRecursivePut(file, file.getName()); } } - for ( File file : files ) - { - if ( !file.isDirectory() ) - { - ftpRecursivePut( file, file.getName() ); + for (File file : files) { + if (!file.isDirectory()) { + ftpRecursivePut(file, file.getName()); } } } // Step back up a directory once we're done with the contents of this one. - try - { + try { ftp.changeToParentDirectory(); + } catch (IOException e) { + throw new TransferFailedException( + "IOException caught while attempting to step up to parent directory" + + " after successfully processing " + + sourceFile.getAbsolutePath(), + e); } - catch ( IOException e ) - { - throw new TransferFailedException( "IOException caught while attempting to step up to parent directory" - + " after successfully processing " - + sourceFile.getAbsolutePath(), e ); - } - } - else - { + } else { // Oh how I hope and pray, in denial, but today I am still just a file. FileInputStream sourceFileStream = null; - try - { - sourceFileStream = new FileInputStream( sourceFile ); + try { + sourceFileStream = new FileInputStream(sourceFile); // It's a file. Upload it in the current directory. - if ( ftp.storeFile( fileName, sourceFileStream ) ) - { - if ( permissions != null ) - { + if (ftp.storeFile(fileName, sourceFileStream)) { + if (permissions != null) { // Process permissions; note that if we get errors or exceptions here, they are ignored. // This appears to be a conscious decision, based on other parts of this code. String group = permissions.getGroup(); - if ( group != null ) - { - try - { - ftp.sendSiteCommand( "CHGRP " + permissions.getGroup() ); - } - catch ( IOException e ) - { + if (group != null) { + try { + ftp.sendSiteCommand("CHGRP " + permissions.getGroup()); + } catch (IOException e) { // ignore } } String mode = permissions.getFileMode(); - if ( mode != null ) - { - try - { - ftp.sendSiteCommand( "CHMOD " + permissions.getDirectoryMode() ); - } - catch ( IOException e ) - { + if (mode != null) { + try { + ftp.sendSiteCommand("CHMOD " + permissions.getDirectoryMode()); + } catch (IOException e) { // ignore } } } - } - else - { - String msg = - "Cannot transfer resource: '" + sourceFile.getAbsolutePath() + "' FTP Server response: " - + ftp.getReplyString(); - throw new TransferFailedException( msg ); + } else { + String msg = "Cannot transfer resource: '" + sourceFile.getAbsolutePath() + + "' FTP Server response: " + ftp.getReplyString(); + throw new TransferFailedException(msg); } sourceFileStream.close(); sourceFileStream = null; - } - catch ( IOException e ) - { + } catch (IOException e) { throw new TransferFailedException( - "IOException caught while attempting to upload " + sourceFile.getAbsolutePath(), e ); - } - finally - { - IOUtils.closeQuietly( sourceFileStream ); + "IOException caught while attempting to upload " + sourceFile.getAbsolutePath(), e); + } finally { + IOUtils.closeQuietly(sourceFileStream); } - } - fireTransferDebug( "completed = " + sourceFile.getAbsolutePath() ); + fireTransferDebug("completed = " + sourceFile.getAbsolutePath()); } /** @@ -707,33 +569,23 @@ private void ftpRecursivePut( File sourceFile, String fileName ) * * @param permissions group and directory permissions */ - private void setPermissions( RepositoryPermissions permissions ) - { - if ( permissions != null ) - { + private void setPermissions(RepositoryPermissions permissions) { + if (permissions != null) { // Process permissions; note that if we get errors or exceptions here, they are ignored. // This appears to be a conscious decision, based on other parts of this code. String group = permissions.getGroup(); - if ( group != null ) - { - try - { - ftp.sendSiteCommand( "CHGRP " + permissions.getGroup() ); - } - catch ( IOException e ) - { + if (group != null) { + try { + ftp.sendSiteCommand("CHGRP " + permissions.getGroup()); + } catch (IOException e) { // ignore } } String mode = permissions.getDirectoryMode(); - if ( mode != null ) - { - try - { - ftp.sendSiteCommand( "CHMOD " + permissions.getDirectoryMode() ); - } - catch ( IOException e ) - { + if (mode != null) { + try { + ftp.sendSiteCommand("CHMOD " + permissions.getDirectoryMode()); + } catch (IOException e) { // ignore } } @@ -748,88 +600,75 @@ private void setPermissions( RepositoryPermissions permissions ) * @return ok * @throws IOException */ - private boolean makeFtpDirectoryRecursive( String fileName, RepositoryPermissions permissions ) - throws IOException - { - if ( fileName == null || fileName.length() == 0 - || fileName.replace( '/', '_' ).trim().length() == 0 ) // if a string is '/', '//' or similar + private boolean makeFtpDirectoryRecursive(String fileName, RepositoryPermissions permissions) throws IOException { + if (fileName == null + || fileName.length() == 0 + || fileName.replace('/', '_').trim().length() == 0) // if a string is '/', '//' or similar { return false; } - int slashPos = fileName.indexOf( "/" ); + int slashPos = fileName.indexOf("/"); String oldPwd = null; boolean ok = true; - if ( slashPos == 0 ) - { + if (slashPos == 0) { // this is an absolute directory oldPwd = ftp.printWorkingDirectory(); // start with the root - ftp.changeWorkingDirectory( "/" ); - fileName = fileName.substring( 1 ); + ftp.changeWorkingDirectory("/"); + fileName = fileName.substring(1); // look up the next path separator - slashPos = fileName.indexOf( "/" ); + slashPos = fileName.indexOf("/"); } - if ( slashPos >= 0 && slashPos < ( fileName.length() - 1 ) ) // not only a slash at the end, like in 'newDir/' + if (slashPos >= 0 && slashPos < (fileName.length() - 1)) // not only a slash at the end, like in 'newDir/' { - if ( oldPwd == null ) - { + if (oldPwd == null) { oldPwd = ftp.printWorkingDirectory(); } - String nextDir = fileName.substring( 0, slashPos ); + String nextDir = fileName.substring(0, slashPos); boolean changedDir = false; // we only create the nextDir if it doesn't yet exist - if ( !ftp.changeWorkingDirectory( nextDir ) ) - { - ok &= ftp.makeDirectory( nextDir ); - } - else - { + if (!ftp.changeWorkingDirectory(nextDir)) { + ok &= ftp.makeDirectory(nextDir); + } else { changedDir = true; } - if ( ok ) - { + if (ok) { // set the permissions for the freshly created directory - setPermissions( permissions ); + setPermissions(permissions); - if ( !changedDir ) - { - ftp.changeWorkingDirectory( nextDir ); + if (!changedDir) { + ftp.changeWorkingDirectory(nextDir); } // now create the deeper directories - final String remainingDirs = fileName.substring( slashPos + 1 ); - ok &= makeFtpDirectoryRecursive( remainingDirs, permissions ); + final String remainingDirs = fileName.substring(slashPos + 1); + ok &= makeFtpDirectoryRecursive(remainingDirs, permissions); } - } - else - { - ok = ftp.makeDirectory( fileName ); + } else { + ok = ftp.makeDirectory(fileName); } - if ( oldPwd != null ) - { + if (oldPwd != null) { // change back to the old working directory - ftp.changeWorkingDirectory( oldPwd ); + ftp.changeWorkingDirectory(oldPwd); } return ok; } - public String getControlEncoding() - { + public String getControlEncoding() { return controlEncoding; } - public void setControlEncoding( String controlEncoding ) - { + public void setControlEncoding(String controlEncoding) { this.controlEncoding = controlEncoding; } } diff --git a/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpsWagon.java b/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpsWagon.java index 373644964..cb878518f 100644 --- a/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpsWagon.java +++ b/wagon-providers/wagon-ftp/src/main/java/org/apache/maven/wagon/providers/ftp/FtpsWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ftp; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ftp; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPSClient; @@ -32,10 +31,8 @@ * role-hint="ftps" * instantiation-strategy="per-lookup" */ -public class FtpsWagon - extends FtpWagon -{ - private static final Logger LOG = LoggerFactory.getLogger( FtpsWagon.class ); +public class FtpsWagon extends FtpWagon { + private static final Logger LOG = LoggerFactory.getLogger(FtpsWagon.class); /** * @plexus.configuration default-value="TLS" @@ -53,12 +50,14 @@ public class FtpsWagon private boolean endpointChecking = true; @Override - protected FTPClient createClient() - { - LOG.debug( "Creating secure FTP client. Protocol: [{}], implicit mode: [{}], endpoint checking: [{}].", - securityProtocol, implicit, endpointChecking ); - FTPSClient client = new FTPSClient( securityProtocol, implicit ); - client.setEndpointCheckingEnabled( endpointChecking ); + protected FTPClient createClient() { + LOG.debug( + "Creating secure FTP client. Protocol: [{}], implicit mode: [{}], endpoint checking: [{}].", + securityProtocol, + implicit, + endpointChecking); + FTPSClient client = new FTPSClient(securityProtocol, implicit); + client.setEndpointCheckingEnabled(endpointChecking); return client; } } diff --git a/wagon-providers/wagon-ftp/src/test/java/org/apache/maven/wagon/providers/ftp/FtpWagonTest.java b/wagon-providers/wagon-ftp/src/test/java/org/apache/maven/wagon/providers/ftp/FtpWagonTest.java index 83b702d7e..f206d20f4 100644 --- a/wagon-providers/wagon-ftp/src/test/java/org/apache/maven/wagon/providers/ftp/FtpWagonTest.java +++ b/wagon-providers/wagon-ftp/src/test/java/org/apache/maven/wagon/providers/ftp/FtpWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ftp; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ftp; import java.io.File; import java.util.ArrayList; @@ -45,43 +44,36 @@ * @author Michal Maczka * */ -public class FtpWagonTest - extends StreamingWagonTestCase -{ +public class FtpWagonTest extends StreamingWagonTestCase { private FtpServer server; - + private int testRepositoryPort; - - protected String getProtocol() - { + + protected String getProtocol() { return "ftp"; } - + protected int getTestRepositoryPort() { return testRepositoryPort; } - protected void setupWagonTestingFixtures() - throws Exception - { + protected void setupWagonTestingFixtures() throws Exception { File ftpHomeDir = getRepositoryDirectory(); - if ( !ftpHomeDir.exists() ) - { + if (!ftpHomeDir.exists()) { ftpHomeDir.mkdirs(); } - if ( server == null ) - { + if (server == null) { FtpServerFactory serverFactory = new FtpServerFactory(); ListenerFactory factory = new ListenerFactory(); // set the port of the listener - factory.setPort( 0 ); - + factory.setPort(0); + // replace the default listener Listener defaultListener = factory.createListener(); - serverFactory.addListener("default", defaultListener ); + serverFactory.addListener("default", defaultListener); PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory(); UserManager um = userManagerFactory.createUserManager(); @@ -91,16 +83,15 @@ protected void setupWagonTestingFixtures() user.setPassword("admin"); List authorities = new ArrayList<>(); - authorities.add( new WritePermission() ); - - user.setAuthorities( authorities ); + authorities.add(new WritePermission()); - user.setHomeDirectory( ftpHomeDir.getAbsolutePath() ); + user.setAuthorities(authorities); + user.setHomeDirectory(ftpHomeDir.getAbsolutePath()); um.save(user); - serverFactory.setUserManager( um ); + serverFactory.setUserManager(um); server = serverFactory.createServer(); @@ -111,130 +102,107 @@ protected void setupWagonTestingFixtures() } } - protected void createDirectory( Wagon wagon, String resourceToCreate, String dirName ) - throws Exception - { - super.createDirectory( wagon, resourceToCreate, dirName ); + protected void createDirectory(Wagon wagon, String resourceToCreate, String dirName) throws Exception { + super.createDirectory(wagon, resourceToCreate, dirName); getRepositoryDirectory().mkdirs(); } - protected void tearDownWagonTestingFixtures() - throws Exception - { + protected void tearDownWagonTestingFixtures() throws Exception { server.stop(); server = null; } - protected String getTestRepositoryUrl() - { + protected String getTestRepositoryUrl() { return "ftp://localhost:" + getTestRepositoryPort(); } - public AuthenticationInfo getAuthInfo() - { + public AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( "admin" ); + authInfo.setUserName("admin"); - authInfo.setPassword( "admin" ); + authInfo.setPassword("admin"); return authInfo; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - File file = new File( getRepositoryDirectory(), resource.getName() ); + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + File file = new File(getRepositoryDirectory(), resource.getName()); // granularity for FTP is minutes - return ( file.lastModified() / 60000 ) * 60000; + return (file.lastModified() / 60000) * 60000; } - private File getRepositoryDirectory() - { - return getTestFile( "target/test-output/local-repository" ); + private File getRepositoryDirectory() { + return getTestFile("target/test-output/local-repository"); } - public void testNoPassword() - throws Exception - { + public void testNoPassword() throws Exception { AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setUserName( "me" ); - try - { - getWagon().connect( new Repository( "id", getTestRepositoryUrl() ), authenticationInfo ); + authenticationInfo.setUserName("me"); + try { + getWagon().connect(new Repository("id", getTestRepositoryUrl()), authenticationInfo); fail(); - } - catch ( AuthenticationException e ) - { - assertTrue( true ); + } catch (AuthenticationException e) { + assertTrue(true); } } - public void testDefaultUserName() - throws Exception - { + public void testDefaultUserName() throws Exception { AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setPassword( "secret" ); - try - { - getWagon().connect( new Repository( "id", getTestRepositoryUrl() ), authenticationInfo ); + authenticationInfo.setPassword("secret"); + try { + getWagon().connect(new Repository("id", getTestRepositoryUrl()), authenticationInfo); fail(); - } - catch ( AuthenticationException e ) - { - assertEquals( System.getProperty( "user.name" ), authenticationInfo.getUserName() ); + } catch (AuthenticationException e) { + assertEquals(System.getProperty("user.name"), authenticationInfo.getUserName()); } } /** * This is a unit test to show WAGON-265 */ - public void testPutDirectoryCreation() - throws Exception - { + public void testPutDirectoryCreation() throws Exception { setupWagonTestingFixtures(); setupRepositories(); Wagon wagon = getWagon(); - if ( wagon.supportsDirectoryCopy() ) - { + if (wagon.supportsDirectoryCopy()) { // do the cleanup first - File destDir = new File( getRepositoryDirectory(), "dirExists" ); - FileUtils.deleteDirectory( destDir ); + File destDir = new File(getRepositoryDirectory(), "dirExists"); + FileUtils.deleteDirectory(destDir); destDir.mkdirs(); - destDir = new File( destDir, "not_yet_existing/also_not" ); + destDir = new File(destDir, "not_yet_existing/also_not"); - File sourceDir = new File( getRepositoryDirectory(), "testDirectory" ); + File sourceDir = new File(getRepositoryDirectory(), "testDirectory"); FileUtils.deleteDirectory(sourceDir); sourceDir.mkdir(); - File testRes = new File( sourceDir, "test-resource-1.txt" ); + File testRes = new File(sourceDir, "test-resource-1.txt"); testRes.createNewFile(); // This is the difference to our normal use case: // the directory specified in the repo string doesn't yet exist! - testRepository.setUrl( testRepository.getUrl() + "/dirExists/not_yet_existing/also_not" ); + testRepository.setUrl(testRepository.getUrl() + "/dirExists/not_yet_existing/also_not"); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - wagon.putDirectory( sourceDir, "testDirectory" ); + wagon.putDirectory(sourceDir, "testDirectory"); destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "testDirectory/test-resource-1.txt", destFile ); + wagon.get("testDirectory/test-resource-1.txt", destFile); wagon.disconnect(); } tearDownWagonTestingFixtures(); - - } } diff --git a/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagon.java b/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagon.java index 4cd937b58..67e298bd6 100644 --- a/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagon.java +++ b/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,20 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.ConnectionException; -import org.apache.maven.wagon.InputData; -import org.apache.maven.wagon.OutputData; -import org.apache.maven.wagon.ResourceDoesNotExistException; -import org.apache.maven.wagon.StreamWagon; -import org.apache.maven.wagon.TransferFailedException; -import org.apache.maven.wagon.authentication.AuthenticationException; -import org.apache.maven.wagon.authorization.AuthorizationException; -import org.apache.maven.wagon.events.TransferEvent; -import org.apache.maven.wagon.proxy.ProxyInfo; -import org.apache.maven.wagon.resource.Resource; -import org.apache.maven.wagon.shared.http.EncodingUtil; -import org.codehaus.plexus.util.Base64; +package org.apache.maven.wagon.providers.http; import java.io.FileNotFoundException; import java.io.IOException; @@ -53,6 +38,20 @@ import java.util.zip.DeflaterInputStream; import java.util.zip.GZIPInputStream; +import org.apache.maven.wagon.ConnectionException; +import org.apache.maven.wagon.InputData; +import org.apache.maven.wagon.OutputData; +import org.apache.maven.wagon.ResourceDoesNotExistException; +import org.apache.maven.wagon.StreamWagon; +import org.apache.maven.wagon.TransferFailedException; +import org.apache.maven.wagon.authentication.AuthenticationException; +import org.apache.maven.wagon.authorization.AuthorizationException; +import org.apache.maven.wagon.events.TransferEvent; +import org.apache.maven.wagon.proxy.ProxyInfo; +import org.apache.maven.wagon.resource.Resource; +import org.apache.maven.wagon.shared.http.EncodingUtil; +import org.codehaus.plexus.util.Base64; + import static java.lang.Integer.parseInt; import static org.apache.maven.wagon.shared.http.HttpMessageUtils.UNKNOWN_STATUS_CODE; import static org.apache.maven.wagon.shared.http.HttpMessageUtils.formatAuthorizationMessage; @@ -66,17 +65,15 @@ * @plexus.component role="org.apache.maven.wagon.Wagon" role-hint="http" instantiation-strategy="per-lookup" * @see HttpURLConnection */ -public class LightweightHttpWagon - extends StreamWagon -{ +public class LightweightHttpWagon extends StreamWagon { private boolean preemptiveAuthentication; private HttpURLConnection putConnection; private Proxy proxy = Proxy.NO_PROXY; - private static final Pattern IOEXCEPTION_MESSAGE_PATTERN = Pattern.compile( "Server returned HTTP response code: " - + "(\\d\\d\\d) for URL: (.*)" ); + private static final Pattern IOEXCEPTION_MESSAGE_PATTERN = + Pattern.compile("Server returned HTTP response code: " + "(\\d\\d\\d) for URL: (.*)"); public static final int MAX_REDIRECTS = 10; @@ -103,305 +100,246 @@ public class LightweightHttpWagon * @param resource the resource to extract the relative path from. * @return the complete URL */ - private String buildUrl( Resource resource ) - { - return EncodingUtil.encodeURLToString( getRepository().getUrl(), resource.getName() ); + private String buildUrl(Resource resource) { + return EncodingUtil.encodeURLToString(getRepository().getUrl(), resource.getName()); } - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Resource resource = inputData.getResource(); - String visitingUrl = buildUrl( resource ); + String visitingUrl = buildUrl(resource); List visitedUrls = new ArrayList<>(); - for ( int redirectCount = 0; redirectCount < MAX_REDIRECTS; redirectCount++ ) - { - if ( visitedUrls.contains( visitingUrl ) ) - { + for (int redirectCount = 0; redirectCount < MAX_REDIRECTS; redirectCount++) { + if (visitedUrls.contains(visitingUrl)) { // TODO add a test for this message - throw new TransferFailedException( "Cyclic http redirect detected. Aborting! " + visitingUrl ); + throw new TransferFailedException("Cyclic http redirect detected. Aborting! " + visitingUrl); } - visitedUrls.add( visitingUrl ); + visitedUrls.add(visitingUrl); URL url = null; - try - { - url = new URL( visitingUrl ); - } - catch ( MalformedURLException e ) - { + try { + url = new URL(visitingUrl); + } catch (MalformedURLException e) { // TODO add test for this - throw new ResourceDoesNotExistException( "Invalid repository URL: " + e.getMessage(), e ); + throw new ResourceDoesNotExistException("Invalid repository URL: " + e.getMessage(), e); } HttpURLConnection urlConnection = null; - try - { - urlConnection = ( HttpURLConnection ) url.openConnection( this.proxy ); - } - catch ( IOException e ) - { + try { + urlConnection = (HttpURLConnection) url.openConnection(this.proxy); + } catch (IOException e) { // TODO: add test for this - String message = formatTransferFailedMessage( visitingUrl, UNKNOWN_STATUS_CODE, - null, getProxyInfo() ); + String message = formatTransferFailedMessage(visitingUrl, UNKNOWN_STATUS_CODE, null, getProxyInfo()); // TODO include e.getMessage appended to main message? - throw new TransferFailedException( message, e ); + throw new TransferFailedException(message, e); } - try - { + try { - urlConnection.setRequestProperty( "Accept-Encoding", "gzip,deflate" ); - if ( !useCache ) - { - urlConnection.setRequestProperty( "Pragma", "no-cache" ); + urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); + if (!useCache) { + urlConnection.setRequestProperty("Pragma", "no-cache"); } - addHeaders( urlConnection ); + addHeaders(urlConnection); // TODO: handle all response codes int responseCode = urlConnection.getResponseCode(); String reasonPhrase = urlConnection.getResponseMessage(); // TODO Move 401/407 to AuthenticationException after WAGON-587 - if ( responseCode == HttpURLConnection.HTTP_FORBIDDEN + if (responseCode == HttpURLConnection.HTTP_FORBIDDEN || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED - || responseCode == HttpURLConnection.HTTP_PROXY_AUTH ) - { - throw new AuthorizationException( formatAuthorizationMessage( buildUrl( resource ), - responseCode, reasonPhrase, getProxyInfo() ) ); + || responseCode == HttpURLConnection.HTTP_PROXY_AUTH) { + throw new AuthorizationException( + formatAuthorizationMessage(buildUrl(resource), responseCode, reasonPhrase, getProxyInfo())); } - if ( responseCode == HttpURLConnection.HTTP_MOVED_PERM - || responseCode == HttpURLConnection.HTTP_MOVED_TEMP ) - { - visitingUrl = urlConnection.getHeaderField( "Location" ); + if (responseCode == HttpURLConnection.HTTP_MOVED_PERM + || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { + visitingUrl = urlConnection.getHeaderField("Location"); continue; } InputStream is = urlConnection.getInputStream(); - String contentEncoding = urlConnection.getHeaderField( "Content-Encoding" ); - boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase( contentEncoding ); - if ( isGZipped ) - { - is = new GZIPInputStream( is ); + String contentEncoding = urlConnection.getHeaderField("Content-Encoding"); + boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding); + if (isGZipped) { + is = new GZIPInputStream(is); } - boolean isDeflated = contentEncoding != null && "deflate".equalsIgnoreCase( contentEncoding ); - if ( isDeflated ) - { - is = new DeflaterInputStream( is ); + boolean isDeflated = contentEncoding != null && "deflate".equalsIgnoreCase(contentEncoding); + if (isDeflated) { + is = new DeflaterInputStream(is); } - inputData.setInputStream( is ); - resource.setLastModified( urlConnection.getLastModified() ); - resource.setContentLength( urlConnection.getContentLength() ); + inputData.setInputStream(is); + resource.setLastModified(urlConnection.getLastModified()); + resource.setContentLength(urlConnection.getContentLength()); break; - } - catch ( FileNotFoundException e ) - { + } catch (FileNotFoundException e) { // this could be 404 Not Found or 410 Gone - we don't have access to which it was. // TODO: 2019-10-03 url used should list all visited/redirected urls, not just the original - throw new ResourceDoesNotExistException( formatResourceDoesNotExistMessage( buildUrl( resource ), - UNKNOWN_STATUS_CODE, null, getProxyInfo() ), e ); - } - catch ( IOException originalIOException ) - { - throw convertHttpUrlConnectionException( originalIOException, urlConnection, buildUrl( resource ) ); + throw new ResourceDoesNotExistException( + formatResourceDoesNotExistMessage( + buildUrl(resource), UNKNOWN_STATUS_CODE, null, getProxyInfo()), + e); + } catch (IOException originalIOException) { + throw convertHttpUrlConnectionException(originalIOException, urlConnection, buildUrl(resource)); } - } - } - private void addHeaders( HttpURLConnection urlConnection ) - { - if ( httpHeaders != null ) - { - for ( Object header : httpHeaders.keySet() ) - { - urlConnection.setRequestProperty( (String) header, httpHeaders.getProperty( (String) header ) ); + private void addHeaders(HttpURLConnection urlConnection) { + if (httpHeaders != null) { + for (Object header : httpHeaders.keySet()) { + urlConnection.setRequestProperty((String) header, httpHeaders.getProperty((String) header)); } } - setAuthorization( urlConnection ); + setAuthorization(urlConnection); } - private void setAuthorization( HttpURLConnection urlConnection ) - { - if ( preemptiveAuthentication && authenticationInfo != null && authenticationInfo.getUserName() != null ) - { + private void setAuthorization(HttpURLConnection urlConnection) { + if (preemptiveAuthentication && authenticationInfo != null && authenticationInfo.getUserName() != null) { String credentials = authenticationInfo.getUserName() + ":" + authenticationInfo.getPassword(); - String encoded = new String( Base64.encodeBase64( credentials.getBytes() ) ); - urlConnection.setRequestProperty( "Authorization", "Basic " + encoded ); + String encoded = new String(Base64.encodeBase64(credentials.getBytes())); + urlConnection.setRequestProperty("Authorization", "Basic " + encoded); } } - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { + public void fillOutputData(OutputData outputData) throws TransferFailedException { Resource resource = outputData.getResource(); - try - { - URL url = new URL( buildUrl( resource ) ); - putConnection = (HttpURLConnection) url.openConnection( this.proxy ); + try { + URL url = new URL(buildUrl(resource)); + putConnection = (HttpURLConnection) url.openConnection(this.proxy); - addHeaders( putConnection ); + addHeaders(putConnection); - putConnection.setRequestMethod( "PUT" ); - putConnection.setDoOutput( true ); - outputData.setOutputStream( putConnection.getOutputStream() ); - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error transferring file: " + e.getMessage(), e ); + putConnection.setRequestMethod("PUT"); + putConnection.setDoOutput(true); + outputData.setOutputStream(putConnection.getOutputStream()); + } catch (IOException e) { + throw new TransferFailedException("Error transferring file: " + e.getMessage(), e); } } - protected void finishPutTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - try - { + protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + try { String reasonPhrase = putConnection.getResponseMessage(); int statusCode = putConnection.getResponseCode(); - switch ( statusCode ) - { - // Success Codes + switch (statusCode) { + // Success Codes case HttpURLConnection.HTTP_OK: // 200 case HttpURLConnection.HTTP_CREATED: // 201 case HttpURLConnection.HTTP_ACCEPTED: // 202 case HttpURLConnection.HTTP_NO_CONTENT: // 204 break; - // TODO Move 401/407 to AuthenticationException after WAGON-587 + // TODO Move 401/407 to AuthenticationException after WAGON-587 case HttpURLConnection.HTTP_FORBIDDEN: case HttpURLConnection.HTTP_UNAUTHORIZED: case HttpURLConnection.HTTP_PROXY_AUTH: - throw new AuthorizationException( formatAuthorizationMessage( buildUrl( resource ), statusCode, - reasonPhrase, getProxyInfo() ) ); + throw new AuthorizationException( + formatAuthorizationMessage(buildUrl(resource), statusCode, reasonPhrase, getProxyInfo())); case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_GONE: - throw new ResourceDoesNotExistException( formatResourceDoesNotExistMessage( buildUrl( resource ), - statusCode, reasonPhrase, getProxyInfo() ) ); + throw new ResourceDoesNotExistException(formatResourceDoesNotExistMessage( + buildUrl(resource), statusCode, reasonPhrase, getProxyInfo())); - // add more entries here + // add more entries here default: - throw new TransferFailedException( formatTransferFailedMessage( buildUrl( resource ), - statusCode, reasonPhrase, getProxyInfo() ) ) ; + throw new TransferFailedException( + formatTransferFailedMessage(buildUrl(resource), statusCode, reasonPhrase, getProxyInfo())); } - } - catch ( IOException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); - throw convertHttpUrlConnectionException( e, putConnection, buildUrl( resource ) ); + } catch (IOException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); + throw convertHttpUrlConnectionException(e, putConnection, buildUrl(resource)); } } - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { - final ProxyInfo proxyInfo = getProxyInfo( "http", getRepository().getHost() ); - if ( proxyInfo != null ) - { - this.proxy = getProxy( proxyInfo ); + protected void openConnectionInternal() throws ConnectionException, AuthenticationException { + final ProxyInfo proxyInfo = getProxyInfo("http", getRepository().getHost()); + if (proxyInfo != null) { + this.proxy = getProxy(proxyInfo); this.proxyInfo = proxyInfo; } - authenticator.setWagon( this ); + authenticator.setWagon(this); - boolean usePreemptiveAuthentication = - Boolean.getBoolean( "maven.wagon.http.preemptiveAuthentication" ) || Boolean.parseBoolean( - repository.getParameter( "preemptiveAuthentication" ) ) || this.preemptiveAuthentication; + boolean usePreemptiveAuthentication = Boolean.getBoolean("maven.wagon.http.preemptiveAuthentication") + || Boolean.parseBoolean(repository.getParameter("preemptiveAuthentication")) + || this.preemptiveAuthentication; - setPreemptiveAuthentication( usePreemptiveAuthentication ); + setPreemptiveAuthentication(usePreemptiveAuthentication); } - @SuppressWarnings( "deprecation" ) - public PasswordAuthentication requestProxyAuthentication() - { - if ( proxyInfo != null && proxyInfo.getUserName() != null ) - { + @SuppressWarnings("deprecation") + public PasswordAuthentication requestProxyAuthentication() { + if (proxyInfo != null && proxyInfo.getUserName() != null) { String password = ""; - if ( proxyInfo.getPassword() != null ) - { + if (proxyInfo.getPassword() != null) { password = proxyInfo.getPassword(); } - return new PasswordAuthentication( proxyInfo.getUserName(), password.toCharArray() ); + return new PasswordAuthentication(proxyInfo.getUserName(), password.toCharArray()); } return null; } - public PasswordAuthentication requestServerAuthentication() - { - if ( authenticationInfo != null && authenticationInfo.getUserName() != null ) - { + public PasswordAuthentication requestServerAuthentication() { + if (authenticationInfo != null && authenticationInfo.getUserName() != null) { String password = ""; - if ( authenticationInfo.getPassword() != null ) - { + if (authenticationInfo.getPassword() != null) { password = authenticationInfo.getPassword(); } - return new PasswordAuthentication( authenticationInfo.getUserName(), password.toCharArray() ); + return new PasswordAuthentication(authenticationInfo.getUserName(), password.toCharArray()); } return null; } - private Proxy getProxy( ProxyInfo proxyInfo ) - { - return new Proxy( getProxyType( proxyInfo ), getSocketAddress( proxyInfo ) ); + private Proxy getProxy(ProxyInfo proxyInfo) { + return new Proxy(getProxyType(proxyInfo), getSocketAddress(proxyInfo)); } - private Type getProxyType( ProxyInfo proxyInfo ) - { - if ( ProxyInfo.PROXY_SOCKS4.equals( proxyInfo.getType() ) || ProxyInfo.PROXY_SOCKS5.equals( - proxyInfo.getType() ) ) - { + private Type getProxyType(ProxyInfo proxyInfo) { + if (ProxyInfo.PROXY_SOCKS4.equals(proxyInfo.getType()) || ProxyInfo.PROXY_SOCKS5.equals(proxyInfo.getType())) { return Type.SOCKS; - } - else - { + } else { return Type.HTTP; } } - public SocketAddress getSocketAddress( ProxyInfo proxyInfo ) - { - return InetSocketAddress.createUnresolved( proxyInfo.getHost(), proxyInfo.getPort() ); + public SocketAddress getSocketAddress(ProxyInfo proxyInfo) { + return InetSocketAddress.createUnresolved(proxyInfo.getHost(), proxyInfo.getPort()); } - public void closeConnection() - throws ConnectionException - { - //FIXME WAGON-375 use persistent connection feature provided by the jdk - if ( putConnection != null ) - { + public void closeConnection() throws ConnectionException { + // FIXME WAGON-375 use persistent connection feature provided by the jdk + if (putConnection != null) { putConnection.disconnect(); } authenticator.resetWagon(); } - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { HttpURLConnection headConnection; - try - { - Resource resource = new Resource( resourceName ); - URL url = new URL( buildUrl( resource ) ); - headConnection = (HttpURLConnection) url.openConnection( this.proxy ); + try { + Resource resource = new Resource(resourceName); + URL url = new URL(buildUrl(resource)); + headConnection = (HttpURLConnection) url.openConnection(this.proxy); - addHeaders( headConnection ); + addHeaders(headConnection); - headConnection.setRequestMethod( "HEAD" ); + headConnection.setRequestMethod("HEAD"); int statusCode = headConnection.getResponseCode(); String reasonPhrase = headConnection.getResponseMessage(); - switch ( statusCode ) - { + switch (statusCode) { case HttpURLConnection.HTTP_OK: return true; @@ -409,68 +347,55 @@ public boolean resourceExists( String resourceName ) case HttpURLConnection.HTTP_GONE: return false; - // TODO Move 401/407 to AuthenticationException after WAGON-587 + // TODO Move 401/407 to AuthenticationException after WAGON-587 case HttpURLConnection.HTTP_FORBIDDEN: case HttpURLConnection.HTTP_UNAUTHORIZED: case HttpURLConnection.HTTP_PROXY_AUTH: - throw new AuthorizationException( formatAuthorizationMessage( buildUrl( resource ), - statusCode, reasonPhrase, getProxyInfo() ) ); + throw new AuthorizationException( + formatAuthorizationMessage(buildUrl(resource), statusCode, reasonPhrase, getProxyInfo())); default: - throw new TransferFailedException( formatTransferFailedMessage( buildUrl( resource ), - statusCode, reasonPhrase, getProxyInfo() ) ); + throw new TransferFailedException( + formatTransferFailedMessage(buildUrl(resource), statusCode, reasonPhrase, getProxyInfo())); } - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error transferring file: " + e.getMessage(), e ); + } catch (IOException e) { + throw new TransferFailedException("Error transferring file: " + e.getMessage(), e); } } - public boolean isUseCache() - { + public boolean isUseCache() { return useCache; } - public void setUseCache( boolean useCache ) - { + public void setUseCache(boolean useCache) { this.useCache = useCache; } - public Properties getHttpHeaders() - { + public Properties getHttpHeaders() { return httpHeaders; } - public void setHttpHeaders( Properties httpHeaders ) - { + public void setHttpHeaders(Properties httpHeaders) { this.httpHeaders = httpHeaders; } - void setSystemProperty( String key, String value ) - { - if ( value != null ) - { - System.setProperty( key, value ); - } - else - { - System.getProperties().remove( key ); + void setSystemProperty(String key, String value) { + if (value != null) { + System.setProperty(key, value); + } else { + System.getProperties().remove(key); } } - public void setPreemptiveAuthentication( boolean preemptiveAuthentication ) - { + public void setPreemptiveAuthentication(boolean preemptiveAuthentication) { this.preemptiveAuthentication = preemptiveAuthentication; } - public LightweightHttpWagonAuthenticator getAuthenticator() - { + public LightweightHttpWagonAuthenticator getAuthenticator() { return authenticator; } - public void setAuthenticator( LightweightHttpWagonAuthenticator authenticator ) - { + public void setAuthenticator(LightweightHttpWagonAuthenticator authenticator) { this.authenticator = authenticator; } @@ -487,27 +412,21 @@ public void setAuthenticator( LightweightHttpWagonAuthenticator authenticator ) * @param url originating url that triggered the IOException * @return exception that is representative of the original cause */ - private TransferFailedException convertHttpUrlConnectionException( IOException originalIOException, - HttpURLConnection urlConnection, - String url ) - { + private TransferFailedException convertHttpUrlConnectionException( + IOException originalIOException, HttpURLConnection urlConnection, String url) { // javadoc of HttpUrlConnection, HTTP transfer errors throw IOException // In that case, one may attempt to get the status code and reason phrase // from the errorstream. We do this, but by way of the following code path // getResponseCode()/getResponseMessage() - calls -> getHeaderFields() // getHeaderFields() - calls -> getErrorStream() - try - { + try { // call getResponseMessage first since impl calls getResponseCode as part of that anyways String errorResponseMessage = urlConnection.getResponseMessage(); // may be null int errorResponseCode = urlConnection.getResponseCode(); // may be -1 if the code cannot be discerned - String message = formatTransferFailedMessage( url, errorResponseCode, errorResponseMessage, - getProxyInfo() ); - return new TransferFailedException( message, originalIOException ); + String message = formatTransferFailedMessage(url, errorResponseCode, errorResponseMessage, getProxyInfo()); + return new TransferFailedException(message, originalIOException); - } - catch ( IOException errorStreamException ) - { + } catch (IOException errorStreamException) { // there was a problem using the standard methods, need to fall back to other options } @@ -515,31 +434,25 @@ private TransferFailedException convertHttpUrlConnectionException( IOException o // https://github.com/AdoptOpenJDK/openjdk-jdk11/blame/999dbd4192d0f819cb5224f26e9e7fa75ca6f289/src/java // .base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java#L1911L1913 String ioMsg = originalIOException.getMessage(); - if ( ioMsg != null ) - { - Matcher matcher = IOEXCEPTION_MESSAGE_PATTERN.matcher( ioMsg ); - if ( matcher.matches() ) - { - String codeStr = matcher.group( 1 ); - String urlStr = matcher.group( 2 ); + if (ioMsg != null) { + Matcher matcher = IOEXCEPTION_MESSAGE_PATTERN.matcher(ioMsg); + if (matcher.matches()) { + String codeStr = matcher.group(1); + String urlStr = matcher.group(2); int code = UNKNOWN_STATUS_CODE; - try - { - code = parseInt( codeStr ); - } - catch ( NumberFormatException nfe ) - { + try { + code = parseInt(codeStr); + } catch (NumberFormatException nfe) { // if here there is a regex problem } - String message = formatTransferFailedMessage( urlStr, code, null, getProxyInfo() ); - return new TransferFailedException( message, originalIOException ); + String message = formatTransferFailedMessage(urlStr, code, null, getProxyInfo()); + return new TransferFailedException(message, originalIOException); } } - String message = formatTransferFailedMessage( url, UNKNOWN_STATUS_CODE, null, getProxyInfo() ); - return new TransferFailedException( message, originalIOException ); + String message = formatTransferFailedMessage(url, UNKNOWN_STATUS_CODE, null, getProxyInfo()); + return new TransferFailedException(message, originalIOException); } - } diff --git a/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonAuthenticator.java b/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonAuthenticator.java index b904a02ab..526090417 100644 --- a/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonAuthenticator.java +++ b/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonAuthenticator.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import java.net.Authenticator; import java.net.PasswordAuthentication; @@ -26,36 +25,27 @@ * @author Nicolas De loof * @plexus.component role="org.apache.maven.wagon.providers.http.LightweightHttpWagonAuthenticator" */ -public class LightweightHttpWagonAuthenticator - extends Authenticator -{ +public class LightweightHttpWagonAuthenticator extends Authenticator { ThreadLocal localWagon = new ThreadLocal<>(); - protected PasswordAuthentication getPasswordAuthentication() - { + protected PasswordAuthentication getPasswordAuthentication() { LightweightHttpWagon wagon = localWagon.get(); - if ( wagon != null ) - { - if ( getRequestorType() == RequestorType.PROXY ) - { + if (wagon != null) { + if (getRequestorType() == RequestorType.PROXY) { return wagon.requestProxyAuthentication(); - } - else - { + } else { return wagon.requestServerAuthentication(); } } return null; } - public void setWagon( LightweightHttpWagon wagon ) - { - localWagon.set( wagon ); - Authenticator.setDefault( this ); + public void setWagon(LightweightHttpWagon wagon) { + localWagon.set(wagon); + Authenticator.setDefault(this); } - public void resetWagon() - { + public void resetWagon() { localWagon.remove(); } } diff --git a/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagon.java b/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagon.java index 686b8b8c9..4661b1611 100644 --- a/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagon.java +++ b/wagon-providers/wagon-http-lightweight/src/main/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.authentication.AuthenticationException; @@ -28,55 +27,45 @@ * * @author Joakim Erdfelt * - * - * @plexus.component role="org.apache.maven.wagon.Wagon" + * + * @plexus.component role="org.apache.maven.wagon.Wagon" * role-hint="https" * instantiation-strategy="per-lookup" */ -public class LightweightHttpsWagon - extends LightweightHttpWagon -{ +public class LightweightHttpsWagon extends LightweightHttpWagon { private String previousHttpsProxyHost; - + private String previousHttpsProxyPort; private String previousHttpsProxyExclusions; - public LightweightHttpsWagon() - { + public LightweightHttpsWagon() { super(); } - public void openConnection() - throws ConnectionException, AuthenticationException - { - previousHttpsProxyHost = System.getProperty( "https.proxyHost" ); - previousHttpsProxyPort = System.getProperty( "https.proxyPort" ); - previousHttpsProxyExclusions = System.getProperty( "https.nonProxyHosts" ); - - final ProxyInfo proxyInfo = getProxyInfo( "https", getRepository().getHost() ); - if ( proxyInfo != null ) - { - setSystemProperty( "https.proxyHost", proxyInfo.getHost() ); - setSystemProperty( "https.proxyPort", String.valueOf( proxyInfo.getPort() ) ); - setSystemProperty( "https.nonProxyHosts", proxyInfo.getNonProxyHosts() ); - } - else - { - setSystemProperty( "https.proxyHost", null ); - setSystemProperty( "https.proxyPort", null ); + public void openConnection() throws ConnectionException, AuthenticationException { + previousHttpsProxyHost = System.getProperty("https.proxyHost"); + previousHttpsProxyPort = System.getProperty("https.proxyPort"); + previousHttpsProxyExclusions = System.getProperty("https.nonProxyHosts"); + + final ProxyInfo proxyInfo = getProxyInfo("https", getRepository().getHost()); + if (proxyInfo != null) { + setSystemProperty("https.proxyHost", proxyInfo.getHost()); + setSystemProperty("https.proxyPort", String.valueOf(proxyInfo.getPort())); + setSystemProperty("https.nonProxyHosts", proxyInfo.getNonProxyHosts()); + } else { + setSystemProperty("https.proxyHost", null); + setSystemProperty("https.proxyPort", null); } - + super.openConnection(); } - public void closeConnection() - throws ConnectionException - { + public void closeConnection() throws ConnectionException { super.closeConnection(); - setSystemProperty( "https.proxyHost", previousHttpsProxyHost ); - setSystemProperty( "https.proxyPort", previousHttpsProxyPort ); - setSystemProperty( "https.nonProxyHosts", previousHttpsProxyExclusions ); + setSystemProperty("https.proxyHost", previousHttpsProxyHost); + setSystemProperty("https.proxyPort", previousHttpsProxyPort); + setSystemProperty("https.nonProxyHosts", previousHttpsProxyExclusions); } } diff --git a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonTest.java b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonTest.java index 660db32f6..0cb908cda 100644 --- a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonTest.java +++ b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; + +import javax.servlet.http.HttpServletResponse; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Properties; import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.StreamingWagon; @@ -26,147 +31,138 @@ import org.apache.maven.wagon.authorization.AuthorizationException; import org.apache.maven.wagon.http.HttpWagonTestCase; -import javax.servlet.http.HttpServletResponse; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Properties; - /** * @author Michal Maczka * */ -public class LightweightHttpWagonTest - extends HttpWagonTestCase -{ - protected String getProtocol() - { +public class LightweightHttpWagonTest extends HttpWagonTestCase { + protected String getProtocol() { return "http"; } - protected String getTestRepositoryUrl() - { + protected String getTestRepositoryUrl() { return getProtocol() + "://localhost:" + getTestRepositoryPort() + "/"; } - protected void setHttpConfiguration( StreamingWagon wagon, Properties headers, Properties params ) - { - ( (LightweightHttpWagon) wagon ).setHttpHeaders( headers ); + protected void setHttpConfiguration(StreamingWagon wagon, Properties headers, Properties params) { + ((LightweightHttpWagon) wagon).setHttpHeaders(headers); } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return false; } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return false; } @Override - protected boolean supportProxyPreemptiveAuthentication() - { + protected boolean supportProxyPreemptiveAuthentication() { return false; } @Override - protected void verifyWagonExceptionMessage( Exception e, int forStatusCode, String forUrl, String forReasonPhrase ) - { + protected void verifyWagonExceptionMessage(Exception e, int forStatusCode, String forUrl, String forReasonPhrase) { // HttpUrlConnection prevents direct API access to the response code or reasonPhrase for any // status code >= 400. So all we can do is check WagonException wraps the HttpUrlConnection // thrown IOException / FileNotFoundException as a cause, if cause is not null - assertNotNull( e ); - try - { - assertTrue( "only verify instances of WagonException", e instanceof WagonException ); + assertNotNull(e); + try { + assertTrue("only verify instances of WagonException", e instanceof WagonException); String assertMessageForBadMessage = "exception message not described properly: "; - switch ( forStatusCode ) - { + switch (forStatusCode) { case HttpServletResponse.SC_GONE: case HttpServletResponse.SC_NOT_FOUND: - assertTrue( "404 or 410 should throw ResourceDoesNotExistException", - e instanceof ResourceDoesNotExistException ); - - if ( e.getCause() != null ) - { - assertTrue( "ResourceDoesNotExistException should have the expected cause", - e.getCause() instanceof FileNotFoundException ); + assertTrue( + "404 or 410 should throw ResourceDoesNotExistException", + e instanceof ResourceDoesNotExistException); + + if (e.getCause() != null) { + assertTrue( + "ResourceDoesNotExistException should have the expected cause", + e.getCause() instanceof FileNotFoundException); // the status code and reason phrase cannot always be learned due to implementation limitations // which means the message may not include them - assertEquals( assertMessageForBadMessage, "resource missing at " + forUrl, e.getMessage() ); - } - else - { - assertEquals( assertMessageForBadMessage, "resource missing at " + forUrl - + ", status: " + forStatusCode + " " + forReasonPhrase, e.getMessage() ); + assertEquals(assertMessageForBadMessage, "resource missing at " + forUrl, e.getMessage()); + } else { + assertEquals( + assertMessageForBadMessage, + "resource missing at " + forUrl + ", status: " + forStatusCode + " " + forReasonPhrase, + e.getMessage()); } break; case HttpServletResponse.SC_FORBIDDEN: - assertTrue( "403 Forbidden throws AuthorizationException", - e instanceof AuthorizationException ); - - assertEquals( assertMessageForBadMessage, "authorization failed for " + forUrl + ", status: 403" - + ( (forReasonPhrase == null || forReasonPhrase.isEmpty()) ? " Forbidden" : ( " " + forReasonPhrase ) ), - e.getMessage() ); + assertTrue("403 Forbidden throws AuthorizationException", e instanceof AuthorizationException); + + assertEquals( + assertMessageForBadMessage, + "authorization failed for " + forUrl + ", status: 403" + + ((forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Forbidden" + : (" " + forReasonPhrase)), + e.getMessage()); break; case HttpServletResponse.SC_UNAUTHORIZED: - assertTrue( "401 Unauthorized throws AuthorizationException", - e instanceof AuthorizationException ); - - assertEquals( assertMessageForBadMessage, "authentication failed for " + forUrl + ", status: 401" - + ( (forReasonPhrase == null || forReasonPhrase.isEmpty()) ? " Unauthorized" : - ( " " + forReasonPhrase ) ), - e.getMessage() ); + assertTrue("401 Unauthorized throws AuthorizationException", e instanceof AuthorizationException); + + assertEquals( + assertMessageForBadMessage, + "authentication failed for " + forUrl + ", status: 401" + + ((forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Unauthorized" + : (" " + forReasonPhrase)), + e.getMessage()); break; default: - assertTrue( "general exception must be TransferFailedException", - e instanceof TransferFailedException ); - assertTrue( "expected status code for transfer failures should be >= 400, but none of " + assertTrue( + "general exception must be TransferFailedException", e instanceof TransferFailedException); + assertTrue( + "expected status code for transfer failures should be >= 400, but none of " + " the already handled codes", - forStatusCode >= HttpServletResponse.SC_BAD_REQUEST ); + forStatusCode >= HttpServletResponse.SC_BAD_REQUEST); - if ( e.getCause() != null ) - { - assertTrue( "TransferFailedException should have the original cause for diagnosis", - e.getCause() instanceof IOException ); + if (e.getCause() != null) { + assertTrue( + "TransferFailedException should have the original cause for diagnosis", + e.getCause() instanceof IOException); } // the status code and reason phrase cannot always be learned due to implementation limitations // so the message may not include them, but the implementation should use a consistent format - assertTrue( "message should always include url", - e.getMessage().startsWith( "transfer failed for " + forUrl ) ); - - if ( e.getMessage().length() > ( "transfer failed for " + forUrl ).length() ) - { - assertTrue( "message should include url and status code", - e.getMessage().startsWith( "transfer failed for " + forUrl + ", status: " + forStatusCode ) ); + assertTrue( + "message should always include url", + e.getMessage().startsWith("transfer failed for " + forUrl)); + + if (e.getMessage().length() > ("transfer failed for " + forUrl).length()) { + assertTrue( + "message should include url and status code", + e.getMessage() + .startsWith("transfer failed for " + forUrl + ", status: " + forStatusCode)); } - if ( e.getMessage().length() > ( "transfer failed for " + forUrl + ", status: " + forStatusCode ).length() ) - { - assertEquals( "message should include url and status code and reason phrase", + if (e.getMessage().length() + > ("transfer failed for " + forUrl + ", status: " + forStatusCode).length()) { + assertEquals( + "message should include url and status code and reason phrase", "transfer failed for " + forUrl + ", status: " + forStatusCode + " " + forReasonPhrase, - e.getMessage() ); + e.getMessage()); } break; } - } - catch ( AssertionError assertionError ) - { - logger.error( "Exception which failed assertions: ", e ); + } catch (AssertionError assertionError) { + logger.error("Exception which failed assertions: ", e); throw assertionError; } } - } diff --git a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonWithPreemptiveAuthenticationTest.java b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonWithPreemptiveAuthenticationTest.java index 1c866483c..8256e81ff 100644 --- a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonWithPreemptiveAuthenticationTest.java +++ b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpWagonWithPreemptiveAuthenticationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.Wagon; @@ -25,27 +24,21 @@ * @author Michal Maczka * */ -public class LightweightHttpWagonWithPreemptiveAuthenticationTest - extends LightweightHttpWagonTest -{ +public class LightweightHttpWagonWithPreemptiveAuthenticationTest extends LightweightHttpWagonTest { @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { LightweightHttpWagon wagon = (LightweightHttpWagon) super.getWagon(); - wagon.setPreemptiveAuthentication( true ); + wagon.setPreemptiveAuthentication(true); return wagon; } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return true; } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return true; } } diff --git a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagonTest.java b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagonTest.java index e9ab42d10..64fcfc4c8 100644 --- a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagonTest.java +++ b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/LightweightHttpsWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,39 +16,36 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; -public class LightweightHttpsWagonTest - extends LightweightHttpWagonTest -{ - protected String getProtocol() - { +public class LightweightHttpsWagonTest extends LightweightHttpWagonTest { + protected String getProtocol() { return "https"; } - protected ServerConnector addConnector( Server server ) - { - System.setProperty( "javax.net.ssl.trustStore", - getTestFile( "src/test/resources/ssl/keystore" ).getAbsolutePath() ); + protected ServerConnector addConnector(Server server) { + System.setProperty( + "javax.net.ssl.trustStore", + getTestFile("src/test/resources/ssl/keystore").getAbsolutePath()); SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setKeyStorePassword( "wagonhttp" ); - sslContextFactory.setKeyManagerPassword( "wagonhttp" ); - sslContextFactory.setTrustStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setTrustStorePassword( "wagonhttp" ); + sslContextFactory.setKeyStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setKeyStorePassword("wagonhttp"); + sslContextFactory.setKeyManagerPassword("wagonhttp"); + sslContextFactory.setTrustStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setTrustStorePassword("wagonhttp"); - ServerConnector serverConnector = new ServerConnector( server, sslContextFactory ); - server.addConnector( serverConnector ); + ServerConnector serverConnector = new ServerConnector(server, sslContextFactory); + server.addConnector(serverConnector); return serverConnector; } @Override - protected boolean assertOnTransferProgress() - { + protected boolean assertOnTransferProgress() { return false; } } diff --git a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java index 8342f40b7..b39fbd315 100644 --- a/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java +++ b/wagon-providers/wagon-http-lightweight/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.tck.http.GetWagonTests; import org.apache.maven.wagon.tck.http.HttpsGetWagonTests; @@ -27,9 +26,8 @@ /** * This test will runn the TCK suite on wagon-http-lightweight */ -@RunWith( Suite.class ) -@Suite.SuiteClasses( { GetWagonTests.class, HttpsGetWagonTests.class } ) -public class TckTest -{ +@RunWith(Suite.class) +@Suite.SuiteClasses({GetWagonTests.class, HttpsGetWagonTests.class}) +public class TckTest { // no op } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/AbstractHttpClientWagon.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/AbstractHttpClientWagon.java index 9cf7f0904..92dc157b7 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/AbstractHttpClientWagon.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/AbstractHttpClientWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,33 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; + +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; import org.apache.http.Header; import org.apache.http.HttpEntity; @@ -81,31 +106,6 @@ import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.RandomAccessFile; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; - import static org.apache.maven.wagon.shared.http.HttpMessageUtils.formatAuthorizationMessage; import static org.apache.maven.wagon.shared.http.HttpMessageUtils.formatResourceDoesNotExistMessage; import static org.apache.maven.wagon.shared.http.HttpMessageUtils.formatTransferDebugMessage; @@ -115,12 +115,8 @@ * @author Michal Maczka * @author James William Dumay */ -public abstract class AbstractHttpClientWagon - extends StreamWagon -{ - final class WagonHttpEntity - extends AbstractHttpEntity - { +public abstract class AbstractHttpClientWagon extends StreamWagon { + final class WagonHttpEntity extends AbstractHttpEntity { private final Resource resource; private final Wagon wagon; @@ -133,17 +129,12 @@ final class WagonHttpEntity private boolean repeatable; - private WagonHttpEntity( final InputStream stream, final Resource resource, final Wagon wagon, - final File source ) - throws TransferFailedException - { - if ( source != null ) - { + private WagonHttpEntity(final InputStream stream, final Resource resource, final Wagon wagon, final File source) + throws TransferFailedException { + if (source != null) { this.source = source; this.repeatable = true; - } - else - { + } else { this.stream = stream; this.repeatable = false; } @@ -153,72 +144,57 @@ private WagonHttpEntity( final InputStream stream, final Resource resource, fina this.wagon = wagon; } - public Resource getResource() - { + public Resource getResource() { return resource; } - public Wagon getWagon() - { + public Wagon getWagon() { return wagon; } - public InputStream getContent() - throws IOException, IllegalStateException - { - if ( this.source != null ) - { - return new FileInputStream( this.source ); + public InputStream getContent() throws IOException, IllegalStateException { + if (this.source != null) { + return new FileInputStream(this.source); } return stream; } - public File getSource() - { + public File getSource() { return source; } - public long getContentLength() - { + public long getContentLength() { return length; } - public boolean isRepeatable() - { + public boolean isRepeatable() { return repeatable; } - public void writeTo( final OutputStream output ) - throws IOException - { - if ( output == null ) - { - throw new NullPointerException( "output cannot be null" ); + public void writeTo(final OutputStream output) throws IOException { + if (output == null) { + throw new NullPointerException("output cannot be null"); } TransferEvent transferEvent = - new TransferEvent( wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_PUT ); - transferEvent.setTimestamp( System.currentTimeMillis() ); - - try ( ReadableByteChannel input = ( this.source != null ) - ? new RandomAccessFile( this.source, "r" ).getChannel() - : Channels.newChannel( stream ) ) - { - ByteBuffer buffer = ByteBuffer.allocate( getBufferCapacityForTransfer( this.length ) ); + new TransferEvent(wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_PUT); + transferEvent.setTimestamp(System.currentTimeMillis()); + + try (ReadableByteChannel input = (this.source != null) + ? new RandomAccessFile(this.source, "r").getChannel() + : Channels.newChannel(stream)) { + ByteBuffer buffer = ByteBuffer.allocate(getBufferCapacityForTransfer(this.length)); int halfBufferCapacity = buffer.capacity() / 2; long remaining = this.length < 0L ? Long.MAX_VALUE : this.length; - while ( remaining > 0L ) - { - int read = input.read( buffer ); - if ( read == -1 ) - { + while (remaining > 0L) { + int read = input.read(buffer); + if (read == -1) { // EOF, but some data has not been written yet. - if ( ( (Buffer) buffer ).position() != 0 ) - { - ( (Buffer) buffer ).flip(); - fireTransferProgress( transferEvent, buffer.array(), ( (Buffer) buffer ).limit() ); - output.write( buffer.array(), 0, ( (Buffer) buffer ).limit() ); - ( (Buffer) buffer ).clear(); + if (((Buffer) buffer).position() != 0) { + ((Buffer) buffer).flip(); + fireTransferProgress(transferEvent, buffer.array(), ((Buffer) buffer).limit()); + output.write(buffer.array(), 0, ((Buffer) buffer).limit()); + ((Buffer) buffer).clear(); } break; @@ -226,72 +202,67 @@ public void writeTo( final OutputStream output ) // Prevent minichunking/fragmentation: when less than half the buffer is utilized, // read some more bytes before writing and firing progress. - if ( ( (Buffer) buffer ).position() < halfBufferCapacity ) - { + if (((Buffer) buffer).position() < halfBufferCapacity) { continue; } - ( (Buffer) buffer ).flip(); - fireTransferProgress( transferEvent, buffer.array(), ( (Buffer) buffer ).limit() ); - output.write( buffer.array(), 0, ( (Buffer) buffer ).limit() ); - remaining -= ( (Buffer) buffer ).limit(); - ( (Buffer) buffer ).clear(); - + ((Buffer) buffer).flip(); + fireTransferProgress(transferEvent, buffer.array(), ((Buffer) buffer).limit()); + output.write(buffer.array(), 0, ((Buffer) buffer).limit()); + remaining -= ((Buffer) buffer).limit(); + ((Buffer) buffer).clear(); } output.flush(); } } - public boolean isStreaming() - { + public boolean isStreaming() { return true; } } - private static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone( "GMT" ); + private static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone("GMT"); /** * use http(s) connection pool mechanism. * enabled by default */ - private static boolean persistentPool = - Boolean.valueOf( System.getProperty( "maven.wagon.http.pool", "true" ) ); + private static boolean persistentPool = Boolean.valueOf(System.getProperty("maven.wagon.http.pool", "true")); /** * skip failure on certificate validity checks. * disabled by default */ private static final boolean SSL_INSECURE = - Boolean.valueOf( System.getProperty( "maven.wagon.http.ssl.insecure", "false" ) ); + Boolean.valueOf(System.getProperty("maven.wagon.http.ssl.insecure", "false")); /** * if using sslInsecure, certificate date issues will be ignored * disabled by default */ private static final boolean IGNORE_SSL_VALIDITY_DATES = - Boolean.valueOf( System.getProperty( "maven.wagon.http.ssl.ignore.validity.dates", "false" ) ); + Boolean.valueOf(System.getProperty("maven.wagon.http.ssl.ignore.validity.dates", "false")); /** * If enabled, ssl hostname verifier does not check hostname. Disable this will use a browser compat hostname * verifier disabled by default */ private static final boolean SSL_ALLOW_ALL = - Boolean.valueOf( System.getProperty( "maven.wagon.http.ssl.allowall", "false" ) ); - + Boolean.valueOf(System.getProperty("maven.wagon.http.ssl.allowall", "false")); /** * Maximum concurrent connections per distinct route. * 20 by default */ private static final int MAX_CONN_PER_ROUTE = - Integer.parseInt( System.getProperty( "maven.wagon.httpconnectionManager.maxPerRoute", "20" ) ); + Integer.parseInt(System.getProperty("maven.wagon.httpconnectionManager.maxPerRoute", "20")); /** * Maximum concurrent connections in total. * 40 by default */ private static final int MAX_CONN_TOTAL = - Integer.parseInt( System.getProperty( "maven.wagon.httpconnectionManager.maxTotal", "40" ) ); + Integer.parseInt(System.getProperty("maven.wagon.httpconnectionManager.maxTotal", "40")); /** * Time to live in seconds for an HTTP connection. After that time, the connection will be dropped. @@ -300,15 +271,13 @@ public boolean isStreaming() * * @since 3.2 */ - private static final long CONN_TTL = - Long.getLong( "maven.wagon.httpconnectionManager.ttlSeconds", 300L ); + private static final long CONN_TTL = Long.getLong("maven.wagon.httpconnectionManager.ttlSeconds", 300L); /** * Internal connection manager */ private static HttpClientConnectionManager httpClientConnectionManager = createConnManager(); - /** * See RFC6585 */ @@ -326,7 +295,7 @@ public boolean isStreaming() * @since 2.7 */ private int initialBackoffSeconds = - Integer.parseInt( System.getProperty( "maven.wagon.httpconnectionManager.backoffSeconds", "5" ) ); + Integer.parseInt(System.getProperty("maven.wagon.httpconnectionManager.backoffSeconds", "5")); /** * The maximum amount of time we want to back off in the case of @@ -335,70 +304,63 @@ public boolean isStreaming() * @since 2.7 */ private static final int MAX_BACKOFF_WAIT_SECONDS = - Integer.parseInt( System.getProperty( "maven.wagon.httpconnectionManager.maxBackoffSeconds", "180" ) ); + Integer.parseInt(System.getProperty("maven.wagon.httpconnectionManager.maxBackoffSeconds", "180")); - protected int backoff( int wait, String url ) - throws InterruptedException, TransferFailedException - { - TimeUnit.SECONDS.sleep( wait ); + protected int backoff(int wait, String url) throws InterruptedException, TransferFailedException { + TimeUnit.SECONDS.sleep(wait); int nextWait = wait * 2; - if ( nextWait >= getMaxBackoffWaitSeconds() ) - { - throw new TransferFailedException( formatTransferFailedMessage( url, SC_TOO_MANY_REQUESTS, - null, getProxyInfo() ) ); + if (nextWait >= getMaxBackoffWaitSeconds()) { + throw new TransferFailedException( + formatTransferFailedMessage(url, SC_TOO_MANY_REQUESTS, null, getProxyInfo())); } return nextWait; } - @SuppressWarnings( "checkstyle:linelength" ) - private static PoolingHttpClientConnectionManager createConnManager() - { + @SuppressWarnings("checkstyle:linelength") + private static PoolingHttpClientConnectionManager createConnManager() { - String sslProtocolsStr = System.getProperty( "https.protocols" ); - String cipherSuitesStr = System.getProperty( "https.cipherSuites" ); - String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split( " *, *" ) : null; - String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split( " *, *" ) : null; + String sslProtocolsStr = System.getProperty("https.protocols"); + String cipherSuitesStr = System.getProperty("https.cipherSuites"); + String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null; + String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null; SSLConnectionSocketFactory sslConnectionSocketFactory; - if ( SSL_INSECURE ) - { - try - { - SSLContext sslContext = new SSLContextBuilder().useSSL().loadTrustMaterial( null, - new RelaxedTrustStrategy( - IGNORE_SSL_VALIDITY_DATES ) ).build(); - sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContext, sslProtocols, cipherSuites, - SSL_ALLOW_ALL - ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER - : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER ); - } - catch ( Exception ex ) - { - throw new SSLInitializationException( ex.getMessage(), ex ); + if (SSL_INSECURE) { + try { + SSLContext sslContext = new SSLContextBuilder() + .useSSL() + .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)) + .build(); + sslConnectionSocketFactory = new SSLConnectionSocketFactory( + sslContext, + sslProtocols, + cipherSuites, + SSL_ALLOW_ALL + ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER + : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + } catch (Exception ex) { + throw new SSLInitializationException(ex.getMessage(), ex); } - } - else - { - sslConnectionSocketFactory = - new SSLConnectionSocketFactory( HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, - cipherSuites, - SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER ); + } else { + sslConnectionSocketFactory = new SSLConnectionSocketFactory( + HttpsURLConnection.getDefaultSSLSocketFactory(), + sslProtocols, + cipherSuites, + SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } - Registry registry = RegistryBuilder.create().register( "http", - PlainConnectionSocketFactory.INSTANCE ).register( - "https", sslConnectionSocketFactory ).build(); + Registry registry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", sslConnectionSocketFactory) + .build(); PoolingHttpClientConnectionManager connManager = - new PoolingHttpClientConnectionManager( registry, null, null, null, CONN_TTL, TimeUnit.SECONDS ); - if ( persistentPool ) - { - connManager.setDefaultMaxPerRoute( MAX_CONN_PER_ROUTE ); - connManager.setMaxTotal( MAX_CONN_TOTAL ); - } - else - { - connManager.setMaxTotal( 1 ); + new PoolingHttpClientConnectionManager(registry, null, null, null, CONN_TTL, TimeUnit.SECONDS); + if (persistentPool) { + connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE); + connManager.setMaxTotal(MAX_CONN_TOTAL); + } else { + connManager.setMaxTotal(1); } return connManager; } @@ -412,7 +374,7 @@ private static PoolingHttpClientConnectionManager createConnManager() * @since 3.2 */ private static final String RETRY_HANDLER_CLASS = - System.getProperty( "maven.wagon.http.retryHandler.class", "standard" ); + System.getProperty("maven.wagon.http.retryHandler.class", "standard"); /** * Whether or not methods that have successfully sent their request will be retried, @@ -422,7 +384,7 @@ private static PoolingHttpClientConnectionManager createConnManager() * @since 3.2 */ private static final boolean RETRY_HANDLER_REQUEST_SENT_ENABLED = - Boolean.getBoolean( "maven.wagon.http.retryHandler.requestSentEnabled" ); + Boolean.getBoolean("maven.wagon.http.retryHandler.requestSentEnabled"); /** * Number of retries for the retry handler, defaults to 3. @@ -430,8 +392,7 @@ private static PoolingHttpClientConnectionManager createConnManager() * * @since 3.2 */ - private static final int RETRY_HANDLER_COUNT = - Integer.getInteger( "maven.wagon.http.retryHandler.count", 3 ); + private static final int RETRY_HANDLER_COUNT = Integer.getInteger("maven.wagon.http.retryHandler.count", 3); /** * Comma-separated list of non-retryable exception classes. @@ -440,34 +401,27 @@ private static PoolingHttpClientConnectionManager createConnManager() * @since 3.2 */ private static final String RETRY_HANDLER_EXCEPTIONS = - System.getProperty( "maven.wagon.http.retryHandler.nonRetryableClasses" ); + System.getProperty("maven.wagon.http.retryHandler.nonRetryableClasses"); - private static HttpRequestRetryHandler createRetryHandler() - { - switch ( RETRY_HANDLER_CLASS ) - { + private static HttpRequestRetryHandler createRetryHandler() { + switch (RETRY_HANDLER_CLASS) { case "default": - if ( RETRY_HANDLER_EXCEPTIONS == null || RETRY_HANDLER_EXCEPTIONS.isEmpty() ) - { - return new DefaultHttpRequestRetryHandler( - RETRY_HANDLER_COUNT, RETRY_HANDLER_REQUEST_SENT_ENABLED ); + if (RETRY_HANDLER_EXCEPTIONS == null || RETRY_HANDLER_EXCEPTIONS.isEmpty()) { + return new DefaultHttpRequestRetryHandler(RETRY_HANDLER_COUNT, RETRY_HANDLER_REQUEST_SENT_ENABLED); } return new DefaultHttpRequestRetryHandler( - RETRY_HANDLER_COUNT, RETRY_HANDLER_REQUEST_SENT_ENABLED, getNonRetryableExceptions() ) - { - }; + RETRY_HANDLER_COUNT, RETRY_HANDLER_REQUEST_SENT_ENABLED, getNonRetryableExceptions()) {}; case "standard": - return new StandardHttpRequestRetryHandler( RETRY_HANDLER_COUNT, RETRY_HANDLER_REQUEST_SENT_ENABLED ); + return new StandardHttpRequestRetryHandler(RETRY_HANDLER_COUNT, RETRY_HANDLER_REQUEST_SENT_ENABLED); default: - try - { + try { final ClassLoader classLoader = AbstractHttpClientWagon.class.getClassLoader(); - return HttpRequestRetryHandler.class.cast( classLoader.loadClass( RETRY_HANDLER_CLASS ) - .getConstructor().newInstance() ); - } - catch ( final Exception e ) - { - throw new IllegalArgumentException( e ); + return HttpRequestRetryHandler.class.cast(classLoader + .loadClass(RETRY_HANDLER_CLASS) + .getConstructor() + .newInstance()); + } catch (final Exception e) { + throw new IllegalArgumentException(e); } } } @@ -479,70 +433,63 @@ RETRY_HANDLER_COUNT, RETRY_HANDLER_REQUEST_SENT_ENABLED, getNonRetryableExceptio * a fully qualified name class with a no-arg or none to not use a ServiceUnavailableRetryStrategy. */ private static final String SERVICE_UNAVAILABLE_RETRY_STRATEGY_CLASS = - System.getProperty( "maven.wagon.http.serviceUnavailableRetryStrategy.class", "none" ); + System.getProperty("maven.wagon.http.serviceUnavailableRetryStrategy.class", "none"); /** * Interval in milliseconds between retries when using a serviceUnavailableRetryStrategy. * 1000 by default */ private static final int SERVICE_UNAVAILABLE_RETRY_STRATEGY_RETRY_INTERVAL = - Integer.getInteger( "maven.wagon.http.serviceUnavailableRetryStrategy.retryInterval", 1000 ); + Integer.getInteger("maven.wagon.http.serviceUnavailableRetryStrategy.retryInterval", 1000); /** * Maximum number of retries when using a serviceUnavailableRetryStrategy. * 5 by default */ private static final int SERVICE_UNAVAILABLE_RETRY_STRATEGY_MAX_RETRIES = - Integer.getInteger( "maven.wagon.http.serviceUnavailableRetryStrategy.maxRetries", 5 ); + Integer.getInteger("maven.wagon.http.serviceUnavailableRetryStrategy.maxRetries", 5); - private static ServiceUnavailableRetryStrategy createServiceUnavailableRetryStrategy() - { - switch ( SERVICE_UNAVAILABLE_RETRY_STRATEGY_CLASS ) - { - case "none": return null; + private static ServiceUnavailableRetryStrategy createServiceUnavailableRetryStrategy() { + switch (SERVICE_UNAVAILABLE_RETRY_STRATEGY_CLASS) { + case "none": + return null; case "default": return new DefaultServiceUnavailableRetryStrategy( - SERVICE_UNAVAILABLE_RETRY_STRATEGY_MAX_RETRIES, SERVICE_UNAVAILABLE_RETRY_STRATEGY_RETRY_INTERVAL ); + SERVICE_UNAVAILABLE_RETRY_STRATEGY_MAX_RETRIES, + SERVICE_UNAVAILABLE_RETRY_STRATEGY_RETRY_INTERVAL); case "standard": return new StandardServiceUnavailableRetryStrategy( - SERVICE_UNAVAILABLE_RETRY_STRATEGY_MAX_RETRIES, SERVICE_UNAVAILABLE_RETRY_STRATEGY_RETRY_INTERVAL ); + SERVICE_UNAVAILABLE_RETRY_STRATEGY_MAX_RETRIES, + SERVICE_UNAVAILABLE_RETRY_STRATEGY_RETRY_INTERVAL); default: - try - { + try { final ClassLoader classLoader = AbstractHttpClientWagon.class.getClassLoader(); - return ServiceUnavailableRetryStrategy.class.cast( - classLoader.loadClass( SERVICE_UNAVAILABLE_RETRY_STRATEGY_CLASS ) - .getConstructor().newInstance() ); - } - catch ( final Exception e ) - { - throw new IllegalArgumentException( e ); + return ServiceUnavailableRetryStrategy.class.cast(classLoader + .loadClass(SERVICE_UNAVAILABLE_RETRY_STRATEGY_CLASS) + .getConstructor() + .newInstance()); + } catch (final Exception e) { + throw new IllegalArgumentException(e); } } } - private static Registry createAuthSchemeRegistry() - { + private static Registry createAuthSchemeRegistry() { return RegistryBuilder.create() - .register( AuthSchemes.BASIC, new BasicSchemeFactory( StandardCharsets.UTF_8 ) ) - .register( AuthSchemes.DIGEST, new DigestSchemeFactory( StandardCharsets.UTF_8 ) ) - .register( AuthSchemes.NTLM, new NTLMSchemeFactory() ) - .build(); + .register(AuthSchemes.BASIC, new BasicSchemeFactory(StandardCharsets.UTF_8)) + .register(AuthSchemes.DIGEST, new DigestSchemeFactory(StandardCharsets.UTF_8)) + .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) + .build(); } - private static Collection> getNonRetryableExceptions() - { + private static Collection> getNonRetryableExceptions() { final List> exceptions = new ArrayList<>(); final ClassLoader loader = AbstractHttpClientWagon.class.getClassLoader(); - for ( final String ex : RETRY_HANDLER_EXCEPTIONS.split( "," ) ) - { - try - { - exceptions.add( ( Class ) loader.loadClass( ex ) ); - } - catch ( final ClassNotFoundException e ) - { - throw new IllegalArgumentException( e ); + for (final String ex : RETRY_HANDLER_EXCEPTIONS.split(",")) { + try { + exceptions.add((Class) loader.loadClass(ex)); + } catch (final ClassNotFoundException e) { + throw new IllegalArgumentException(e); } } return exceptions; @@ -550,17 +497,16 @@ private static Collection> getNonRetryableException private static CloseableHttpClient httpClient = createClient(); - private static CloseableHttpClient createClient() - { + private static CloseableHttpClient createClient() { return HttpClientBuilder.create() // - .useSystemProperties() // - .disableConnectionState() // - .setConnectionManager( httpClientConnectionManager ) // - .setRetryHandler( createRetryHandler() ) - .setServiceUnavailableRetryStrategy( createServiceUnavailableRetryStrategy() ) - .setDefaultAuthSchemeRegistry( createAuthSchemeRegistry() ) - .setRedirectStrategy( new WagonRedirectStrategy() ) - .build(); + .useSystemProperties() // + .disableConnectionState() // + .setConnectionManager(httpClientConnectionManager) // + .setRetryHandler(createRetryHandler()) + .setServiceUnavailableRetryStrategy(createServiceUnavailableRetryStrategy()) + .setDefaultAuthSchemeRegistry(createAuthSchemeRegistry()) + .setRedirectStrategy(new WagonRedirectStrategy()) + .build(); } private CredentialsProvider credentialsProvider; @@ -592,133 +538,114 @@ private static CloseableHttpClient createClient() */ private BasicAuthScope proxyAuth; - public void openConnectionInternal() - { - repository.setUrl( getURL( repository ) ); + public void openConnectionInternal() { + repository.setUrl(getURL(repository)); credentialsProvider = new BasicCredentialsProvider(); authCache = new BasicAuthCache(); - if ( authenticationInfo != null ) - { + if (authenticationInfo != null) { String username = authenticationInfo.getUserName(); String password = authenticationInfo.getPassword(); - if ( ( username != null && !username.isEmpty() ) && ( password != null && !password.isEmpty() ) ) - { - Credentials creds = new UsernamePasswordCredentials( username, password ); + if ((username != null && !username.isEmpty()) && (password != null && !password.isEmpty())) { + Credentials creds = new UsernamePasswordCredentials(username, password); - AuthScope targetScope = getBasicAuthScope().getScope( getRepository().getHost(), - getRepository().getPort() ); - credentialsProvider.setCredentials( targetScope, creds ); + AuthScope targetScope = getBasicAuthScope() + .getScope(getRepository().getHost(), getRepository().getPort()); + credentialsProvider.setCredentials(targetScope, creds); } } - ProxyInfo proxyInfo = getProxyInfo( getRepository().getProtocol(), getRepository().getHost() ); - if ( proxyInfo != null ) - { + ProxyInfo proxyInfo = + getProxyInfo(getRepository().getProtocol(), getRepository().getHost()); + if (proxyInfo != null) { String proxyUsername = proxyInfo.getUserName(); String proxyPassword = proxyInfo.getPassword(); String proxyHost = proxyInfo.getHost(); String proxyNtlmHost = proxyInfo.getNtlmHost(); String proxyNtlmDomain = proxyInfo.getNtlmDomain(); - if ( proxyHost != null ) - { - if ( proxyUsername != null && proxyPassword != null ) - { + if (proxyHost != null) { + if (proxyUsername != null && proxyPassword != null) { Credentials creds; - if ( proxyNtlmHost != null || proxyNtlmDomain != null ) - { - creds = new NTCredentials( proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain ); - } - else - { - creds = new UsernamePasswordCredentials( proxyUsername, proxyPassword ); + if (proxyNtlmHost != null || proxyNtlmDomain != null) { + creds = new NTCredentials(proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain); + } else { + creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword); } - AuthScope proxyScope = getProxyBasicAuthScope().getScope( proxyHost, proxyInfo.getPort() ); - credentialsProvider.setCredentials( proxyScope, creds ); + AuthScope proxyScope = getProxyBasicAuthScope().getScope(proxyHost, proxyInfo.getPort()); + credentialsProvider.setCredentials(proxyScope, creds); } } } } - public void closeConnection() - { - if ( !persistentPool ) - { - httpClientConnectionManager.closeIdleConnections( 0, TimeUnit.MILLISECONDS ); + public void closeConnection() { + if (!persistentPool) { + httpClientConnectionManager.closeIdleConnections(0, TimeUnit.MILLISECONDS); } - if ( authCache != null ) - { + if (authCache != null) { authCache.clear(); authCache = null; } - if ( credentialsProvider != null ) - { + if (credentialsProvider != null) { credentialsProvider.clear(); credentialsProvider = null; } } - public static CloseableHttpClient getHttpClient() - { + public static CloseableHttpClient getHttpClient() { return httpClient; } - public static void setPersistentPool( boolean persistent ) - { + public static void setPersistentPool(boolean persistent) { persistentPool = persistent; } public static void setPoolingHttpClientConnectionManager( - PoolingHttpClientConnectionManager poolingHttpClientConnectionManager ) - { + PoolingHttpClientConnectionManager poolingHttpClientConnectionManager) { httpClientConnectionManager = poolingHttpClientConnectionManager; httpClient = createClient(); } - public void put( File source, String resourceName ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( resourceName ); + public void put(File source, String resourceName) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(resourceName); - firePutInitiated( resource, source ); + firePutInitiated(resource, source); - resource.setContentLength( source.length() ); + resource.setContentLength(source.length()); - resource.setLastModified( source.lastModified() ); + resource.setLastModified(source.lastModified()); - put( null, resource, source ); + put(null, resource, source); } - public void putFromStream( final InputStream stream, String destination, long contentLength, long lastModified ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( destination ); + public void putFromStream(final InputStream stream, String destination, long contentLength, long lastModified) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(destination); - firePutInitiated( resource, null ); + firePutInitiated(resource, null); - resource.setContentLength( contentLength ); + resource.setContentLength(contentLength); - resource.setLastModified( lastModified ); + resource.setLastModified(lastModified); - put( stream, resource, null ); + put(stream, resource, null); } - private void put( final InputStream stream, Resource resource, File source ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - put( resource, source, new WagonHttpEntity( stream, resource, this, source ) ); + private void put(final InputStream stream, Resource resource, File source) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + put(resource, source, new WagonHttpEntity(stream, resource, this, source)); } - private void put( Resource resource, File source, HttpEntity httpEntity ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - put( resource, source, httpEntity, buildUrl( resource ) ); + private void put(Resource resource, File source, HttpEntity httpEntity) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + put(resource, source, httpEntity, buildUrl(resource)); } /** @@ -727,9 +654,8 @@ private void put( Resource resource, File source, HttpEntity httpEntity ) * @param resource the resource to extract the relative path from. * @return the complete URL */ - private String buildUrl( Resource resource ) - { - return buildUrl( resource.getName() ); + private String buildUrl(Resource resource) { + return buildUrl(resource.getName()); } /** @@ -738,34 +664,25 @@ private String buildUrl( Resource resource ) * @param resourceName the resourcerelative path * @return the complete URL */ - private String buildUrl( String resourceName ) - { - return EncodingUtil.encodeURLToString( getRepository().getUrl(), resourceName ); + private String buildUrl(String resourceName) { + return EncodingUtil.encodeURLToString(getRepository().getUrl(), resourceName); } - private void put( Resource resource, File source, HttpEntity httpEntity, String url ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - put( getInitialBackoffSeconds(), resource, source, httpEntity, url ); + private void put(Resource resource, File source, HttpEntity httpEntity, String url) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + put(getInitialBackoffSeconds(), resource, source, httpEntity, url); } + private void put(int wait, Resource resource, File source, HttpEntity httpEntity, String url) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { - private void put( int wait, Resource resource, File source, HttpEntity httpEntity, String url ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - - //Parent directories need to be created before posting - try - { - mkdirs( PathUtils.dirname( resource.getName() ) ); - } - catch ( HttpException he ) - { - fireTransferError( resource, he, TransferEvent.REQUEST_PUT ); - } - catch ( IOException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + // Parent directories need to be created before posting + try { + mkdirs(PathUtils.dirname(resource.getName())); + } catch (HttpException he) { + fireTransferError(resource, he, TransferEvent.REQUEST_PUT); + } catch (IOException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); } // preemptive for put @@ -773,116 +690,107 @@ private void put( int wait, Resource resource, File source, HttpEntity httpEntit // FIXME Perform only when preemptive has been configured Repository repo = getRepository(); - HttpHost targetHost = new HttpHost( repo.getHost(), repo.getPort(), repo.getProtocol() ); - AuthScope targetScope = getBasicAuthScope().getScope( targetHost ); + HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol()); + AuthScope targetScope = getBasicAuthScope().getScope(targetHost); - if ( credentialsProvider.getCredentials( targetScope ) != null ) - { - BasicScheme targetAuth = new BasicScheme( StandardCharsets.UTF_8 ); - authCache.put( targetHost, targetAuth ); + if (credentialsProvider.getCredentials(targetScope) != null) { + BasicScheme targetAuth = new BasicScheme(StandardCharsets.UTF_8); + authCache.put(targetHost, targetAuth); } - HttpPut putMethod = new HttpPut( url ); + HttpPut putMethod = new HttpPut(url); - firePutStarted( resource, source ); + firePutStarted(resource, source); - try - { - putMethod.setEntity( httpEntity ); + try { + putMethod.setEntity(httpEntity); - CloseableHttpResponse response = execute( putMethod ); - try - { - fireTransferDebug( formatTransferDebugMessage( url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); + CloseableHttpResponse response = execute(putMethod); + try { + fireTransferDebug(formatTransferDebugMessage( + url, + response.getStatusLine().getStatusCode(), + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); int statusCode = response.getStatusLine().getStatusCode(); // Check that we didn't run out of retries. - switch ( statusCode ) - { - // Success Codes + switch (statusCode) { + // Success Codes case HttpStatus.SC_OK: // 200 case HttpStatus.SC_CREATED: // 201 case HttpStatus.SC_ACCEPTED: // 202 - case HttpStatus.SC_NO_CONTENT: // 204 + case HttpStatus.SC_NO_CONTENT: // 204 break; - // TODO Move 401/407 to AuthenticationException after WAGON-587 + // TODO Move 401/407 to AuthenticationException after WAGON-587 case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: - EntityUtils.consumeQuietly( response.getEntity() ); + EntityUtils.consumeQuietly(response.getEntity()); fireSessionConnectionRefused(); - throw new AuthorizationException( formatAuthorizationMessage( url, + throw new AuthorizationException(formatAuthorizationMessage( + url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); case HttpStatus.SC_NOT_FOUND: case HttpStatus.SC_GONE: - EntityUtils.consumeQuietly( response.getEntity() ); - throw new ResourceDoesNotExistException( formatResourceDoesNotExistMessage( url, + EntityUtils.consumeQuietly(response.getEntity()); + throw new ResourceDoesNotExistException(formatResourceDoesNotExistMessage( + url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); case SC_TOO_MANY_REQUESTS: - EntityUtils.consumeQuietly( response.getEntity() ); - put( backoff( wait, url ), resource, source, httpEntity, url ); + EntityUtils.consumeQuietly(response.getEntity()); + put(backoff(wait, url), resource, source, httpEntity, url); break; - //add more entries here + // add more entries here default: - EntityUtils.consumeQuietly( response.getEntity() ); - TransferFailedException e = new TransferFailedException( formatTransferFailedMessage( url, + EntityUtils.consumeQuietly(response.getEntity()); + TransferFailedException e = new TransferFailedException(formatTransferFailedMessage( + url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; } - firePutCompleted( resource, source ); + firePutCompleted(resource, source); - EntityUtils.consume( response.getEntity() ); - } - finally - { + EntityUtils.consume(response.getEntity()); + } finally { response.close(); } - } - catch ( IOException | HttpException | InterruptedException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + } catch (IOException | HttpException | InterruptedException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( formatTransferFailedMessage( url, getProxyInfo() ), e ); + throw new TransferFailedException(formatTransferFailedMessage(url, getProxyInfo()), e); } - } - protected void mkdirs( String dirname ) - throws HttpException, IOException - { + protected void mkdirs(String dirname) throws HttpException, IOException { // nothing to do } - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - return resourceExists( getInitialBackoffSeconds(), resourceName ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + return resourceExists(getInitialBackoffSeconds(), resourceName); } - - private boolean resourceExists( int wait, String resourceName ) - throws TransferFailedException, AuthorizationException - { - String url = buildUrl( resourceName ); - HttpHead headMethod = new HttpHead( url ); - try - { - CloseableHttpResponse response = execute( headMethod ); - try - { + private boolean resourceExists(int wait, String resourceName) + throws TransferFailedException, AuthorizationException { + String url = buildUrl(resourceName); + HttpHead headMethod = new HttpHead(url); + try { + CloseableHttpResponse response = execute(headMethod); + try { int statusCode = response.getStatusLine().getStatusCode(); boolean result; - switch ( statusCode ) - { + switch (statusCode) { case HttpStatus.SC_OK: result = true; break; @@ -890,13 +798,15 @@ private boolean resourceExists( int wait, String resourceName ) result = true; break; - // TODO Move 401/407 to AuthenticationException after WAGON-587 + // TODO Move 401/407 to AuthenticationException after WAGON-587 case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: - throw new AuthorizationException( formatAuthorizationMessage( url, + throw new AuthorizationException(formatAuthorizationMessage( + url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); case HttpStatus.SC_NOT_FOUND: case HttpStatus.SC_GONE: @@ -904,161 +814,135 @@ private boolean resourceExists( int wait, String resourceName ) break; case SC_TOO_MANY_REQUESTS: - return resourceExists( backoff( wait, resourceName ), resourceName ); + return resourceExists(backoff(wait, resourceName), resourceName); - //add more entries here + // add more entries here default: - throw new TransferFailedException( formatTransferFailedMessage( url, + throw new TransferFailedException(formatTransferFailedMessage( + url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); } return result; - } - finally - { + } finally { response.close(); } + } catch (IOException | HttpException | InterruptedException e) { + throw new TransferFailedException(formatTransferFailedMessage(url, getProxyInfo()), e); } - catch ( IOException | HttpException | InterruptedException e ) - { - throw new TransferFailedException( formatTransferFailedMessage( url, getProxyInfo() ), e ); - } - } - protected CloseableHttpResponse execute( HttpUriRequest httpMethod ) - throws HttpException, IOException - { - setHeaders( httpMethod ); - String userAgent = getUserAgent( httpMethod ); - if ( userAgent != null ) - { - httpMethod.setHeader( HTTP.USER_AGENT, userAgent ); + protected CloseableHttpResponse execute(HttpUriRequest httpMethod) throws HttpException, IOException { + setHeaders(httpMethod); + String userAgent = getUserAgent(httpMethod); + if (userAgent != null) { + httpMethod.setHeader(HTTP.USER_AGENT, userAgent); } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); // WAGON-273: default the cookie-policy to browser compatible - requestConfigBuilder.setCookieSpec( CookieSpecs.BROWSER_COMPATIBILITY ); + requestConfigBuilder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY); Repository repo = getRepository(); - ProxyInfo proxyInfo = getProxyInfo( repo.getProtocol(), repo.getHost() ); - if ( proxyInfo != null ) - { - HttpHost proxy = new HttpHost( proxyInfo.getHost(), proxyInfo.getPort() ); - requestConfigBuilder.setProxy( proxy ); + ProxyInfo proxyInfo = getProxyInfo(repo.getProtocol(), repo.getHost()); + if (proxyInfo != null) { + HttpHost proxy = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort()); + requestConfigBuilder.setProxy(proxy); } - requestConfigBuilder.setConnectTimeout( getTimeout() ); - requestConfigBuilder.setSocketTimeout( getReadTimeout() ); + requestConfigBuilder.setConnectTimeout(getTimeout()); + requestConfigBuilder.setSocketTimeout(getReadTimeout()); // We don't apply this to MKCOL because RFC 7231 says that this will not work without a body // and our MKCOL requests don't have a body. They will logically behave like GET. - if ( httpMethod instanceof HttpPut ) - { - requestConfigBuilder.setExpectContinueEnabled( true ); + if (httpMethod instanceof HttpPut) { + requestConfigBuilder.setExpectContinueEnabled(true); } HttpMethodConfiguration config = - httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration( httpMethod ); - if ( config != null ) - { - ConfigurationUtils.copyConfig( config, requestConfigBuilder ); + httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(httpMethod); + if (config != null) { + ConfigurationUtils.copyConfig(config, requestConfigBuilder); } HttpClientContext localContext = HttpClientContext.create(); - localContext.setCredentialsProvider( credentialsProvider ); - localContext.setAuthCache( authCache ); - localContext.setRequestConfig( requestConfigBuilder.build() ); - - if ( config != null && config.isUsePreemptive() ) - { - HttpHost targetHost = new HttpHost( repo.getHost(), repo.getPort(), repo.getProtocol() ); - AuthScope targetScope = getBasicAuthScope().getScope( targetHost ); - - if ( credentialsProvider.getCredentials( targetScope ) != null ) - { - BasicScheme targetAuth = new BasicScheme( StandardCharsets.UTF_8 ); - authCache.put( targetHost, targetAuth ); + localContext.setCredentialsProvider(credentialsProvider); + localContext.setAuthCache(authCache); + localContext.setRequestConfig(requestConfigBuilder.build()); + + if (config != null && config.isUsePreemptive()) { + HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol()); + AuthScope targetScope = getBasicAuthScope().getScope(targetHost); + + if (credentialsProvider.getCredentials(targetScope) != null) { + BasicScheme targetAuth = new BasicScheme(StandardCharsets.UTF_8); + authCache.put(targetHost, targetAuth); } } - if ( proxyInfo != null ) - { - if ( proxyInfo.getHost() != null ) - { - HttpHost proxyHost = new HttpHost( proxyInfo.getHost(), proxyInfo.getPort() ); - AuthScope proxyScope = getProxyBasicAuthScope().getScope( proxyHost ); + if (proxyInfo != null) { + if (proxyInfo.getHost() != null) { + HttpHost proxyHost = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort()); + AuthScope proxyScope = getProxyBasicAuthScope().getScope(proxyHost); - if ( credentialsProvider.getCredentials( proxyScope ) != null ) - { + if (credentialsProvider.getCredentials(proxyScope) != null) { /* This is extremely ugly because we need to set challengeState to PROXY, but * the constructor is deprecated. Alternatively, we could subclass BasicScheme * to ProxyBasicScheme and set the state internally in the constructor. */ - BasicScheme proxyAuth = new BasicScheme( ChallengeState.PROXY ); - authCache.put( proxyHost, proxyAuth ); + BasicScheme proxyAuth = new BasicScheme(ChallengeState.PROXY); + authCache.put(proxyHost, proxyAuth); } } } - return httpClient.execute( httpMethod, localContext ); + return httpClient.execute(httpMethod, localContext); } - public void setHeaders( HttpUriRequest method ) - { + public void setHeaders(HttpUriRequest method) { HttpMethodConfiguration config = - httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration( method ); - if ( config == null || config.isUseDefaultHeaders() ) - { + httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(method); + if (config == null || config.isUseDefaultHeaders()) { // TODO: merge with the other headers and have some better defaults, unify with lightweight headers - method.addHeader( "Cache-control", "no-cache" ); - method.addHeader( "Pragma", "no-cache" ); + method.addHeader("Cache-control", "no-cache"); + method.addHeader("Pragma", "no-cache"); } - if ( httpHeaders != null ) - { - for ( Map.Entry entry : httpHeaders.entrySet() ) - { - method.setHeader( (String) entry.getKey(), (String) entry.getValue() ); + if (httpHeaders != null) { + for (Map.Entry entry : httpHeaders.entrySet()) { + method.setHeader((String) entry.getKey(), (String) entry.getValue()); } } Header[] headers = config == null ? null : config.asRequestHeaders(); - if ( headers != null ) - { - for ( Header header : headers ) - { - method.setHeader( header ); + if (headers != null) { + for (Header header : headers) { + method.setHeader(header); } } - Header userAgentHeader = method.getFirstHeader( HTTP.USER_AGENT ); - if ( userAgentHeader == null ) - { - String userAgent = getUserAgent( method ); - if ( userAgent != null ) - { - method.setHeader( HTTP.USER_AGENT, userAgent ); + Header userAgentHeader = method.getFirstHeader(HTTP.USER_AGENT); + if (userAgentHeader == null) { + String userAgent = getUserAgent(method); + if (userAgent != null) { + method.setHeader(HTTP.USER_AGENT, userAgent); } } } - protected String getUserAgent( HttpUriRequest method ) - { - if ( httpHeaders != null ) - { - String value = (String) httpHeaders.get( HTTP.USER_AGENT ); - if ( value != null ) - { + protected String getUserAgent(HttpUriRequest method) { + if (httpHeaders != null) { + String value = (String) httpHeaders.get(HTTP.USER_AGENT); + if (value != null) { return value; } } HttpMethodConfiguration config = - httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration( method ); + httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(method); - if ( config != null ) - { - return (String) config.getHeaders().get( HTTP.USER_AGENT ); + if (config != null) { + return (String) config.getHeaders().get(HTTP.USER_AGENT); } return null; } @@ -1070,18 +954,15 @@ protected String getUserAgent( HttpUriRequest method ) * @param repository * @return */ - protected String getURL( Repository repository ) - { + protected String getURL(Repository repository) { return repository.getUrl(); } - public HttpConfiguration getHttpConfiguration() - { + public HttpConfiguration getHttpConfiguration() { return httpConfiguration; } - public void setHttpConfiguration( HttpConfiguration httpConfiguration ) - { + public void setHttpConfiguration(HttpConfiguration httpConfiguration) { this.httpConfiguration = httpConfiguration; } @@ -1090,10 +971,8 @@ public void setHttpConfiguration( HttpConfiguration httpConfiguration ) * * @return the basicAuth */ - public BasicAuthScope getBasicAuthScope() - { - if ( basicAuth == null ) - { + public BasicAuthScope getBasicAuthScope() { + if (basicAuth == null) { basicAuth = new BasicAuthScope(); } return basicAuth; @@ -1104,8 +983,7 @@ public BasicAuthScope getBasicAuthScope() * * @param basicAuth the AuthScope to set */ - public void setBasicAuthScope( BasicAuthScope basicAuth ) - { + public void setBasicAuthScope(BasicAuthScope basicAuth) { this.basicAuth = basicAuth; } @@ -1114,10 +992,8 @@ public void setBasicAuthScope( BasicAuthScope basicAuth ) * * @return the proxyAuth */ - public BasicAuthScope getProxyBasicAuthScope() - { - if ( proxyAuth == null ) - { + public BasicAuthScope getProxyBasicAuthScope() { + if (proxyAuth == null) { proxyAuth = new BasicAuthScope(); } return proxyAuth; @@ -1128,45 +1004,42 @@ public BasicAuthScope getProxyBasicAuthScope() * * @param proxyAuth the AuthScope to set */ - public void setProxyBasicAuthScope( BasicAuthScope proxyAuth ) - { + public void setProxyBasicAuthScope(BasicAuthScope proxyAuth) { this.proxyAuth = proxyAuth; } - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - fillInputData( getInitialBackoffSeconds(), inputData ); + public void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + fillInputData(getInitialBackoffSeconds(), inputData); } - private void fillInputData( int wait, InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + private void fillInputData(int wait, InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Resource resource = inputData.getResource(); - String url = buildUrl( resource ); - HttpGet getMethod = new HttpGet( url ); + String url = buildUrl(resource); + HttpGet getMethod = new HttpGet(url); long timestamp = resource.getLastModified(); - if ( timestamp > 0 ) - { - SimpleDateFormat fmt = new SimpleDateFormat( "EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US ); - fmt.setTimeZone( GMT_TIME_ZONE ); - Header hdr = new BasicHeader( "If-Modified-Since", fmt.format( new Date( timestamp ) ) ); - fireTransferDebug( "sending ==> " + hdr + "(" + timestamp + ")" ); - getMethod.addHeader( hdr ); + if (timestamp > 0) { + SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US); + fmt.setTimeZone(GMT_TIME_ZONE); + Header hdr = new BasicHeader("If-Modified-Since", fmt.format(new Date(timestamp))); + fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")"); + getMethod.addHeader(hdr); } - try - { - CloseableHttpResponse response = execute( getMethod ); + try { + CloseableHttpResponse response = execute(getMethod); closeable = response; - fireTransferDebug( formatTransferDebugMessage( url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); + fireTransferDebug(formatTransferDebugMessage( + url, + response.getStatusLine().getStatusCode(), + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); int statusCode = response.getStatusLine().getStatusCode(); - switch ( statusCode ) - { + switch (statusCode) { case HttpStatus.SC_OK: break; @@ -1174,154 +1047,132 @@ private void fillInputData( int wait, InputData inputData ) // return, leaving last modified set to original value so getIfNewer should return unmodified return; - // TODO Move 401/407 to AuthenticationException after WAGON-587 + // TODO Move 401/407 to AuthenticationException after WAGON-587 case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: - EntityUtils.consumeQuietly( response.getEntity() ); + EntityUtils.consumeQuietly(response.getEntity()); fireSessionConnectionRefused(); - throw new AuthorizationException( formatAuthorizationMessage( url, - response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), - getProxyInfo() ) ); + throw new AuthorizationException(formatAuthorizationMessage( + url, + response.getStatusLine().getStatusCode(), + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); case HttpStatus.SC_NOT_FOUND: case HttpStatus.SC_GONE: - EntityUtils.consumeQuietly( response.getEntity() ); - throw new ResourceDoesNotExistException( formatResourceDoesNotExistMessage( url, + EntityUtils.consumeQuietly(response.getEntity()); + throw new ResourceDoesNotExistException(formatResourceDoesNotExistMessage( + url, response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase(), getProxyInfo() ) ); + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); case SC_TOO_MANY_REQUESTS: - EntityUtils.consumeQuietly( response.getEntity() ); - fillInputData( backoff( wait, url ), inputData ); + EntityUtils.consumeQuietly(response.getEntity()); + fillInputData(backoff(wait, url), inputData); break; - // add more entries here + // add more entries here default: - EntityUtils.consumeQuietly( response.getEntity() ); - cleanupGetTransfer( resource ); - TransferFailedException e = new TransferFailedException( formatTransferFailedMessage( url, - response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), - getProxyInfo() ) ); - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + EntityUtils.consumeQuietly(response.getEntity()); + cleanupGetTransfer(resource); + TransferFailedException e = new TransferFailedException(formatTransferFailedMessage( + url, + response.getStatusLine().getStatusCode(), + response.getStatusLine().getReasonPhrase(), + getProxyInfo())); + fireTransferError(resource, e, TransferEvent.REQUEST_GET); throw e; } - Header contentLengthHeader = response.getFirstHeader( "Content-Length" ); + Header contentLengthHeader = response.getFirstHeader("Content-Length"); - if ( contentLengthHeader != null ) - { - try - { - long contentLength = Long.parseLong( contentLengthHeader.getValue() ); + if (contentLengthHeader != null) { + try { + long contentLength = Long.parseLong(contentLengthHeader.getValue()); - resource.setContentLength( contentLength ); - } - catch ( NumberFormatException e ) - { + resource.setContentLength(contentLength); + } catch (NumberFormatException e) { fireTransferDebug( - "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e ); + "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e); } } - Header lastModifiedHeader = response.getFirstHeader( "Last-Modified" ); - if ( lastModifiedHeader != null ) - { - Date lastModified = DateUtils.parseDate( lastModifiedHeader.getValue() ); - if ( lastModified != null ) - { - resource.setLastModified( lastModified.getTime() ); - fireTransferDebug( "last-modified = " + lastModifiedHeader.getValue() + " (" - + lastModified.getTime() + ")" ); + Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); + if (lastModifiedHeader != null) { + Date lastModified = DateUtils.parseDate(lastModifiedHeader.getValue()); + if (lastModified != null) { + resource.setLastModified(lastModified.getTime()); + fireTransferDebug( + "last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified.getTime() + ")"); } } HttpEntity entity = response.getEntity(); - if ( entity != null ) - { - inputData.setInputStream( entity.getContent() ); + if (entity != null) { + inputData.setInputStream(entity.getContent()); } - } - catch ( IOException | HttpException | InterruptedException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + } catch (IOException | HttpException | InterruptedException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); - throw new TransferFailedException( formatTransferFailedMessage( url, getProxyInfo() ), e ); + throw new TransferFailedException(formatTransferFailedMessage(url, getProxyInfo()), e); } - } - protected void cleanupGetTransfer( Resource resource ) - { - if ( closeable != null ) - { - try - { + protected void cleanupGetTransfer(Resource resource) { + if (closeable != null) { + try { closeable.close(); - } - catch ( IOException ignore ) - { + } catch (IOException ignore) { // ignore } - } } - @Override - public void putFromStream( InputStream stream, String destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - putFromStream( stream, destination, -1, -1 ); + public void putFromStream(InputStream stream, String destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + putFromStream(stream, destination, -1, -1); } @Override - protected void putFromStream( InputStream stream, Resource resource ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - putFromStream( stream, resource.getName(), -1, -1 ); + protected void putFromStream(InputStream stream, Resource resource) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + putFromStream(stream, resource.getName(), -1, -1); } - public Properties getHttpHeaders() - { + public Properties getHttpHeaders() { return httpHeaders; } - public void setHttpHeaders( Properties httpHeaders ) - { + public void setHttpHeaders(Properties httpHeaders) { this.httpHeaders = httpHeaders; } @Override - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { + public void fillOutputData(OutputData outputData) throws TransferFailedException { // no needed in this implementation but throw an Exception if used - throw new IllegalStateException( "this wagon http client must not use fillOutputData" ); + throw new IllegalStateException("this wagon http client must not use fillOutputData"); } - protected CredentialsProvider getCredentialsProvider() - { + protected CredentialsProvider getCredentialsProvider() { return credentialsProvider; } - protected AuthCache getAuthCache() - { + protected AuthCache getAuthCache() { return authCache; } - public int getInitialBackoffSeconds() - { + public int getInitialBackoffSeconds() { return initialBackoffSeconds; } - public void setInitialBackoffSeconds( int initialBackoffSeconds ) - { + public void setInitialBackoffSeconds(int initialBackoffSeconds) { this.initialBackoffSeconds = initialBackoffSeconds; } - public static int getMaxBackoffWaitSeconds() - { + public static int getMaxBackoffWaitSeconds() { return MAX_BACKOFF_WAIT_SECONDS; } } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/BasicAuthScope.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/BasicAuthScope.java index 3060cbfc3..33da94d97 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/BasicAuthScope.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/BasicAuthScope.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; @@ -25,8 +24,7 @@ /** * @since 2.8 */ -public class BasicAuthScope -{ +public class BasicAuthScope { private String host; private String port; @@ -36,32 +34,28 @@ public class BasicAuthScope /** * @return the host */ - public String getHost() - { + public String getHost() { return host; } /** * @param host the host to set */ - public void setHost( String host ) - { + public void setHost(String host) { this.host = host; } /** * @return the realm */ - public String getRealm() - { + public String getRealm() { return realm; } /** * @param realm the realm to set */ - public void setRealm( String realm ) - { + public void setRealm(String realm) { this.realm = realm; } @@ -78,26 +72,20 @@ public void setRealm( String realm ) * @param port The server setting's /server/port value * @return */ - public AuthScope getScope( String host, int port ) - { - if ( getHost() != null // - && "ANY".compareTo( getHost() ) == 0 // - && getPort() != null // - && "ANY".compareTo( getPort() ) == 0 // - && getRealm() != null // - && "ANY".compareTo( getRealm() ) == 0 ) - { + public AuthScope getScope(String host, int port) { + if (getHost() != null // + && "ANY".compareTo(getHost()) == 0 // + && getPort() != null // + && "ANY".compareTo(getPort()) == 0 // + && getRealm() != null // + && "ANY".compareTo(getRealm()) == 0) { return AuthScope.ANY; } String scopeHost = host; - if ( getHost() != null ) - { - if ( "ANY".compareTo( getHost() ) == 0 ) - { + if (getHost() != null) { + if ("ANY".compareTo(getHost()) == 0) { scopeHost = AuthScope.ANY_HOST; - } - else - { + } else { scopeHost = getHost(); } } @@ -106,47 +94,37 @@ && getRealm() != null // // -1 for server/port settings does this, but providing an override here // in // the BasicAuthScope config - if ( getPort() != null ) - { - if ( "ANY".compareTo( getPort() ) == 0 ) - { + if (getPort() != null) { + if ("ANY".compareTo(getPort()) == 0) { scopePort = AuthScope.ANY_PORT; - } - else - { - scopePort = Integer.parseInt( getPort() ); + } else { + scopePort = Integer.parseInt(getPort()); } } String scopeRealm = AuthScope.ANY_REALM; - if ( getRealm() != null ) - { - if ( "ANY".compareTo( getRealm() ) != 0 ) - { + if (getRealm() != null) { + if ("ANY".compareTo(getRealm()) != 0) { scopeRealm = getRealm(); - } - else - { + } else { scopeRealm = getRealm(); } } - return new AuthScope( scopeHost, scopePort, scopeRealm ); + return new AuthScope(scopeHost, scopePort, scopeRealm); } /** * @return the port */ - public String getPort() - { + public String getPort() { return port; } /** * @param port the port to set */ - public void setPort( String port ) - { + public void setPort(String port) { this.port = port; } @@ -161,8 +139,7 @@ public void setPort( String port ) * @param targetHost * @return */ - public AuthScope getScope( HttpHost targetHost ) - { - return getScope( targetHost.getHostName(), targetHost.getPort() ); + public AuthScope getScope(HttpHost targetHost) { + return getScope(targetHost.getHostName(), targetHost.getPort()); } } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/ConfigurationUtils.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/ConfigurationUtils.java index 5214739ed..44e53338a 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/ConfigurationUtils.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/ConfigurationUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.message.BasicHeader; -import org.apache.maven.wagon.Wagon; +package org.apache.maven.wagon.shared.http; import java.net.InetAddress; import java.net.UnknownHostException; @@ -33,206 +26,153 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.http.Header; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.message.BasicHeader; +import org.apache.maven.wagon.Wagon; + /** * Configuration helper class */ -public class ConfigurationUtils -{ - - private static final String SO_TIMEOUT = "http.socket.timeout"; - private static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck"; - private static final String CONNECTION_TIMEOUT = "http.connection.timeout"; - private static final String USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; - private static final String DEFAULT_PROXY = "http.route.default-proxy"; - private static final String LOCAL_ADDRESS = "http.route.local-address"; - private static final String PROXY_AUTH_PREF = "http.auth.proxy-scheme-pref"; - private static final String TARGET_AUTH_PREF = "http.auth.target-scheme-pref"; - private static final String HANDLE_AUTHENTICATION = "http.protocol.handle-authentication"; - private static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; - private static final String CONN_MANAGER_TIMEOUT = "http.conn-manager.timeout"; - private static final String COOKIE_POLICY = "http.protocol.cookie-policy"; - private static final String MAX_REDIRECTS = "http.protocol.max-redirects"; - private static final String HANDLE_REDIRECTS = "http.protocol.handle-redirects"; - private static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; - private static final String HANDLE_CONTENT_COMPRESSION = "http.protocol.handle-content-compression"; - private static final String HANDLE_URI_NORMALIZATION = "http.protocol.handle-uri-normalization"; +public class ConfigurationUtils { + + private static final String SO_TIMEOUT = "http.socket.timeout"; + private static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck"; + private static final String CONNECTION_TIMEOUT = "http.connection.timeout"; + private static final String USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; + private static final String DEFAULT_PROXY = "http.route.default-proxy"; + private static final String LOCAL_ADDRESS = "http.route.local-address"; + private static final String PROXY_AUTH_PREF = "http.auth.proxy-scheme-pref"; + private static final String TARGET_AUTH_PREF = "http.auth.target-scheme-pref"; + private static final String HANDLE_AUTHENTICATION = "http.protocol.handle-authentication"; + private static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; + private static final String CONN_MANAGER_TIMEOUT = "http.conn-manager.timeout"; + private static final String COOKIE_POLICY = "http.protocol.cookie-policy"; + private static final String MAX_REDIRECTS = "http.protocol.max-redirects"; + private static final String HANDLE_REDIRECTS = "http.protocol.handle-redirects"; + private static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; + private static final String HANDLE_CONTENT_COMPRESSION = "http.protocol.handle-content-compression"; + private static final String HANDLE_URI_NORMALIZATION = "http.protocol.handle-uri-normalization"; private static final String COERCE_PATTERN = "%(\\w+),(.+)"; - public static void copyConfig( HttpMethodConfiguration config, RequestConfig.Builder builder ) - { - builder.setConnectTimeout( config.getConnectionTimeout() ); - builder.setSocketTimeout( config.getReadTimeout() ); + public static void copyConfig(HttpMethodConfiguration config, RequestConfig.Builder builder) { + builder.setConnectTimeout(config.getConnectionTimeout()); + builder.setSocketTimeout(config.getReadTimeout()); Properties params = config.getParams(); - if ( params != null ) - { + if (params != null) { - Pattern coercePattern = Pattern.compile( COERCE_PATTERN ); - for ( Map.Entry entry : params.entrySet() ) - { + Pattern coercePattern = Pattern.compile(COERCE_PATTERN); + for (Map.Entry entry : params.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); - Matcher matcher = coercePattern.matcher( value ); - if ( matcher.matches() ) - { - value = matcher.group( 2 ); - } - - if ( key.equals( SO_TIMEOUT ) ) - { - builder.setSocketTimeout( Integer.parseInt( value ) ); - } - else if ( key.equals( STALE_CONNECTION_CHECK ) ) - { - builder.setStaleConnectionCheckEnabled( Boolean.valueOf( value ) ); - } - else if ( key.equals( CONNECTION_TIMEOUT ) ) - { - builder.setConnectTimeout( Integer.parseInt( value ) ); - } - else if ( key.equals( USE_EXPECT_CONTINUE ) ) - { - builder.setExpectContinueEnabled( Boolean.valueOf( value ) ); - } - else if ( key.equals( DEFAULT_PROXY ) ) - { - builder.setProxy( HttpHost.create( value ) ); - } - else if ( key.equals( LOCAL_ADDRESS ) ) - { - try - { - builder.setLocalAddress( InetAddress.getByName( value ) ); - } - catch ( UnknownHostException ignore ) - { + Matcher matcher = coercePattern.matcher(value); + if (matcher.matches()) { + value = matcher.group(2); + } + + if (key.equals(SO_TIMEOUT)) { + builder.setSocketTimeout(Integer.parseInt(value)); + } else if (key.equals(STALE_CONNECTION_CHECK)) { + builder.setStaleConnectionCheckEnabled(Boolean.valueOf(value)); + } else if (key.equals(CONNECTION_TIMEOUT)) { + builder.setConnectTimeout(Integer.parseInt(value)); + } else if (key.equals(USE_EXPECT_CONTINUE)) { + builder.setExpectContinueEnabled(Boolean.valueOf(value)); + } else if (key.equals(DEFAULT_PROXY)) { + builder.setProxy(HttpHost.create(value)); + } else if (key.equals(LOCAL_ADDRESS)) { + try { + builder.setLocalAddress(InetAddress.getByName(value)); + } catch (UnknownHostException ignore) { // ignore } - } - else if ( key.equals( PROXY_AUTH_PREF ) ) - { - builder.setProxyPreferredAuthSchemes( Arrays.asList( value.split( "," ) ) ); - } - else if ( key.equals( TARGET_AUTH_PREF ) ) - { - builder.setTargetPreferredAuthSchemes( Arrays.asList( value.split( "," ) ) ); - } - else if ( key.equals( HANDLE_AUTHENTICATION ) ) - { - builder.setAuthenticationEnabled( Boolean.valueOf( value ) ); - } - else if ( key.equals( ALLOW_CIRCULAR_REDIRECTS ) ) - { - builder.setCircularRedirectsAllowed( Boolean.valueOf( value ) ); - } - else if ( key.equals( CONN_MANAGER_TIMEOUT ) ) - { - builder.setConnectionRequestTimeout( Integer.parseInt( value ) ); - } - else if ( key.equals( COOKIE_POLICY ) ) - { - builder.setCookieSpec( value ); - } - else if ( key.equals( MAX_REDIRECTS ) ) - { - builder.setMaxRedirects( Integer.parseInt( value ) ); - } - else if ( key.equals( HANDLE_REDIRECTS ) ) - { - builder.setRedirectsEnabled( Boolean.valueOf( value ) ); - } - else if ( key.equals( REJECT_RELATIVE_REDIRECT ) ) - { - builder.setRelativeRedirectsAllowed( !Boolean.valueOf( value ) ); - } - else if ( key.equals ( HANDLE_CONTENT_COMPRESSION ) ) - { - builder.setContentCompressionEnabled( Boolean.valueOf( value ) ); - } - else if ( key.equals ( HANDLE_URI_NORMALIZATION ) ) - { - builder.setNormalizeUri( Boolean.valueOf( value ) ); + } else if (key.equals(PROXY_AUTH_PREF)) { + builder.setProxyPreferredAuthSchemes(Arrays.asList(value.split(","))); + } else if (key.equals(TARGET_AUTH_PREF)) { + builder.setTargetPreferredAuthSchemes(Arrays.asList(value.split(","))); + } else if (key.equals(HANDLE_AUTHENTICATION)) { + builder.setAuthenticationEnabled(Boolean.valueOf(value)); + } else if (key.equals(ALLOW_CIRCULAR_REDIRECTS)) { + builder.setCircularRedirectsAllowed(Boolean.valueOf(value)); + } else if (key.equals(CONN_MANAGER_TIMEOUT)) { + builder.setConnectionRequestTimeout(Integer.parseInt(value)); + } else if (key.equals(COOKIE_POLICY)) { + builder.setCookieSpec(value); + } else if (key.equals(MAX_REDIRECTS)) { + builder.setMaxRedirects(Integer.parseInt(value)); + } else if (key.equals(HANDLE_REDIRECTS)) { + builder.setRedirectsEnabled(Boolean.valueOf(value)); + } else if (key.equals(REJECT_RELATIVE_REDIRECT)) { + builder.setRelativeRedirectsAllowed(!Boolean.valueOf(value)); + } else if (key.equals(HANDLE_CONTENT_COMPRESSION)) { + builder.setContentCompressionEnabled(Boolean.valueOf(value)); + } else if (key.equals(HANDLE_URI_NORMALIZATION)) { + builder.setNormalizeUri(Boolean.valueOf(value)); } } } } - public static Header[] asRequestHeaders( HttpMethodConfiguration config ) - { + public static Header[] asRequestHeaders(HttpMethodConfiguration config) { Properties headers = config.getHeaders(); - if ( headers == null ) - { + if (headers == null) { return new Header[0]; } Header[] result = new Header[headers.size()]; int index = 0; - for ( Map.Entry entry : headers.entrySet() ) - { + for (Map.Entry entry : headers.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); - Header header = new BasicHeader( key, value ); + Header header = new BasicHeader(key, value); result[index++] = header; } return result; } - public static HttpMethodConfiguration merge( HttpMethodConfiguration defaults, HttpMethodConfiguration base, - HttpMethodConfiguration local ) - { - HttpMethodConfiguration result = merge( defaults, base ); - return merge( result, local ); + public static HttpMethodConfiguration merge( + HttpMethodConfiguration defaults, HttpMethodConfiguration base, HttpMethodConfiguration local) { + HttpMethodConfiguration result = merge(defaults, base); + return merge(result, local); } - public static HttpMethodConfiguration merge( HttpMethodConfiguration base, HttpMethodConfiguration local ) - { - if ( base == null && local == null ) - { + public static HttpMethodConfiguration merge(HttpMethodConfiguration base, HttpMethodConfiguration local) { + if (base == null && local == null) { return null; - } - else if ( base == null ) - { + } else if (base == null) { return local; - } - else if ( local == null ) - { + } else if (local == null) { return base; - } - else - { + } else { HttpMethodConfiguration result = base.copy(); - if ( local.getConnectionTimeout() != Wagon.DEFAULT_CONNECTION_TIMEOUT ) - { - result.setConnectionTimeout( local.getConnectionTimeout() ); + if (local.getConnectionTimeout() != Wagon.DEFAULT_CONNECTION_TIMEOUT) { + result.setConnectionTimeout(local.getConnectionTimeout()); } - if ( local.getReadTimeout() != Wagon.DEFAULT_READ_TIMEOUT ) - { - result.setReadTimeout( local.getReadTimeout() ); + if (local.getReadTimeout() != Wagon.DEFAULT_READ_TIMEOUT) { + result.setReadTimeout(local.getReadTimeout()); } - if ( local.getHeaders() != null ) - { - result.getHeaders().putAll( local.getHeaders() ); + if (local.getHeaders() != null) { + result.getHeaders().putAll(local.getHeaders()); } - if ( local.getParams() != null ) - { - result.getParams().putAll( local.getParams() ); + if (local.getParams() != null) { + result.getParams().putAll(local.getParams()); } - if ( local.getUseDefaultHeaders() != null ) - { - result.setUseDefaultHeaders( local.isUseDefaultHeaders() ); + if (local.getUseDefaultHeaders() != null) { + result.setUseDefaultHeaders(local.isUseDefaultHeaders()); } return result; } } - } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/EncodingUtil.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/EncodingUtil.java index c0a992cc2..6d90372bb 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/EncodingUtil.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/EncodingUtil.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; import java.net.MalformedURLException; import java.net.URI; @@ -31,8 +30,7 @@ * * @since 2.7 */ -public class EncodingUtil -{ +public class EncodingUtil { /** * Parses and returns an encoded version of the given URL string. * @@ -43,17 +41,15 @@ public class EncodingUtil * @deprecated to be removed with 4.0.0 */ @Deprecated - public static URI encodeURL( String url ) - throws MalformedURLException, URISyntaxException - { - URL urlObject = new URL( url ); + public static URI encodeURL(String url) throws MalformedURLException, URISyntaxException { + URL urlObject = new URL(url); - URI uriEncoded = - new URI( urlObject.getProtocol(), // - urlObject.getAuthority(), // - urlObject.getPath(), // - urlObject.getQuery(), // - urlObject.getRef() ); + URI uriEncoded = new URI( + urlObject.getProtocol(), // + urlObject.getAuthority(), // + urlObject.getPath(), // + urlObject.getQuery(), // + urlObject.getRef()); return uriEncoded; } @@ -68,15 +64,11 @@ public static URI encodeURL( String url ) * @deprecated To be remvoed with 4.0.0 */ @Deprecated - public static String encodeURLToString( String url ) - { - try - { - return encodeURL( url ).toString(); - } - catch ( Exception e ) - { - throw new IllegalArgumentException( String.format( "Error parsing url: %s", url ), e ); + public static String encodeURLToString(String url) { + try { + return encodeURL(url).toString(); + } catch (Exception e) { + throw new IllegalArgumentException(String.format("Error parsing url: %s", url), e); } } @@ -88,13 +80,11 @@ public static String encodeURLToString( String url ) * @return Composed URL (base + path) already encoded, separating the individual path segments by "/". * @since TODO */ - public static String encodeURLToString( String baseUrl, String path ) - { - String[] pathSegments = path == null ? new String[0] : path.split( "/" ); + public static String encodeURLToString(String baseUrl, String path) { + String[] pathSegments = path == null ? new String[0] : path.split("/"); - String encodedUrl = encodeURLToString( baseUrl, pathSegments ); - if ( path != null && path.endsWith( "/" ) ) - { + String encodedUrl = encodeURLToString(baseUrl, pathSegments); + if (path != null && path.endsWith("/")) { return encodedUrl + "/"; } @@ -109,20 +99,18 @@ public static String encodeURLToString( String baseUrl, String path ) * @return Composed URL (base + path) already encoded, separating the individual path segments by "/". * @since TODO */ - public static String encodeURLToString( String baseUrl, String... pathSegments ) - { - StringBuilder url = new StringBuilder( baseUrl ); + public static String encodeURLToString(String baseUrl, String... pathSegments) { + StringBuilder url = new StringBuilder(baseUrl); String[] segments = pathSegments == null ? new String[0] : pathSegments; - String path = URLEncodedUtils.formatSegments( segments ); + String path = URLEncodedUtils.formatSegments(segments); - if ( url.toString().endsWith( "/" ) && !path.isEmpty() ) - { - url.deleteCharAt( url.length() - 1 ); + if (url.toString().endsWith("/") && !path.isEmpty()) { + url.deleteCharAt(url.length() - 1); } - url.append( path ); + url.append(path); return url.toString(); } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpConfiguration.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpConfiguration.java index 14fde8c75..9609abac2 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpConfiguration.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; import org.apache.http.client.methods.HttpUriRequest; /** * */ -public class HttpConfiguration -{ +public class HttpConfiguration { private HttpMethodConfiguration all; @@ -37,76 +35,63 @@ public class HttpConfiguration private HttpMethodConfiguration mkcol; - public HttpMethodConfiguration getAll() - { + public HttpMethodConfiguration getAll() { return all; } - public HttpConfiguration setAll( HttpMethodConfiguration all ) - { + public HttpConfiguration setAll(HttpMethodConfiguration all) { this.all = all; return this; } - public HttpMethodConfiguration getGet() - { + public HttpMethodConfiguration getGet() { return get; } - public HttpConfiguration setGet( HttpMethodConfiguration get ) - { + public HttpConfiguration setGet(HttpMethodConfiguration get) { this.get = get; return this; } - public HttpMethodConfiguration getPut() - { + public HttpMethodConfiguration getPut() { return put; } - public HttpConfiguration setPut( HttpMethodConfiguration put ) - { + public HttpConfiguration setPut(HttpMethodConfiguration put) { this.put = put; return this; } - public HttpMethodConfiguration getHead() - { + public HttpMethodConfiguration getHead() { return head; } - public HttpConfiguration setHead( HttpMethodConfiguration head ) - { + public HttpConfiguration setHead(HttpMethodConfiguration head) { this.head = head; return this; } - public HttpMethodConfiguration getMkcol() - { + public HttpMethodConfiguration getMkcol() { return mkcol; } - public HttpConfiguration setMkcol( HttpMethodConfiguration mkcol ) - { + public HttpConfiguration setMkcol(HttpMethodConfiguration mkcol) { this.mkcol = mkcol; return this; } - public HttpMethodConfiguration getMethodConfiguration( HttpUriRequest method ) - { - switch ( method.getMethod() ) - { - case "GET": - return ConfigurationUtils.merge( all, get ); - case "PUT": - return ConfigurationUtils.merge( all, put ); - case "HEAD": - return ConfigurationUtils.merge( all, head ); - case "MKCOL": - return ConfigurationUtils.merge( all, mkcol ); - default: - return all; + public HttpMethodConfiguration getMethodConfiguration(HttpUriRequest method) { + switch (method.getMethod()) { + case "GET": + return ConfigurationUtils.merge(all, get); + case "PUT": + return ConfigurationUtils.merge(all, put); + case "HEAD": + return ConfigurationUtils.merge(all, head); + case "MKCOL": + return ConfigurationUtils.merge(all, mkcol); + default: + return all; } } - } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMessageUtils.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMessageUtils.java index 99dcd3cae..7103253c5 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMessageUtils.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMessageUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; import java.util.Objects; @@ -49,8 +48,7 @@ * * @since 3.3.4 */ -public class HttpMessageUtils -{ +public class HttpMessageUtils { // status codes here to avoid checkstyle magic number and not have have hard depend on non-wagon classes private static final int SC_UNAUTHORIZED = 401; private static final int SC_FORBIDDEN = 403; @@ -79,21 +77,17 @@ public class HttpMessageUtils * @return a formatted debug message combining the parameters of this method * @throws NullPointerException if url is null */ - public static String formatTransferDebugMessage( String url, int statusCode, String reasonPhrase, - ProxyInfo proxyInfo ) - { - Objects.requireNonNull( url, "url cannot be null" ); + public static String formatTransferDebugMessage( + String url, int statusCode, String reasonPhrase, ProxyInfo proxyInfo) { + Objects.requireNonNull(url, "url cannot be null"); String msg = url; - if ( statusCode != UNKNOWN_STATUS_CODE ) - { + if (statusCode != UNKNOWN_STATUS_CODE) { msg += " -- status code: " + statusCode; - if ( reasonPhrase != null && !reasonPhrase.isEmpty() ) - { + if (reasonPhrase != null && !reasonPhrase.isEmpty()) { msg += ", reason phrase: " + reasonPhrase; } } - if ( proxyInfo != null ) - { + if (proxyInfo != null) { msg += " -- proxy: " + proxyInfo; } return msg; @@ -110,10 +104,8 @@ public static String formatTransferDebugMessage( String url, int statusCode, Str * @param proxyInfo proxy server used during the transfer, may be null if none used * @return a formatted failure message combining the parameters of this method */ - public static String formatTransferFailedMessage( String url, ProxyInfo proxyInfo ) - { - return formatTransferFailedMessage( url, UNKNOWN_STATUS_CODE, null, - proxyInfo ); + public static String formatTransferFailedMessage(String url, ProxyInfo proxyInfo) { + return formatTransferFailedMessage(url, UNKNOWN_STATUS_CODE, null, proxyInfo); } /** @@ -125,10 +117,9 @@ public static String formatTransferFailedMessage( String url, ProxyInfo proxyInf * @param proxyInfo proxy server used during the transfer, may be null if none used * @return a formatted failure message combining the parameters of this method */ - public static String formatTransferFailedMessage( String url, int statusCode, String reasonPhrase, - ProxyInfo proxyInfo ) - { - return formatMessage( "transfer failed for ", url, statusCode, reasonPhrase, proxyInfo ); + public static String formatTransferFailedMessage( + String url, int statusCode, String reasonPhrase, ProxyInfo proxyInfo) { + return formatMessage("transfer failed for ", url, statusCode, reasonPhrase, proxyInfo); } /** @@ -144,26 +135,23 @@ public static String formatTransferFailedMessage( String url, int statusCode, St * @return a consistent message for a HTTP related {@link AuthorizationException} */ // TODO Split when WAGON-568 is implemented - public static String formatAuthorizationMessage( String url, int statusCode, String reasonPhrase, - ProxyInfo proxyInfo ) - { - switch ( statusCode ) - { + public static String formatAuthorizationMessage( + String url, int statusCode, String reasonPhrase, ProxyInfo proxyInfo) { + switch (statusCode) { case SC_UNAUTHORIZED: // no credentials or auth was not valid - return formatMessage( "authentication failed for ", url, statusCode, reasonPhrase, null ); + return formatMessage("authentication failed for ", url, statusCode, reasonPhrase, null); case SC_FORBIDDEN: // forbidden based on permissions usually - return formatMessage( "authorization failed for ", url, statusCode, reasonPhrase, null ); + return formatMessage("authorization failed for ", url, statusCode, reasonPhrase, null); case SC_PROXY_AUTH_REQUIRED: - return formatMessage( "proxy authentication failed for ", url, statusCode, - reasonPhrase, null ); + return formatMessage("proxy authentication failed for ", url, statusCode, reasonPhrase, null); default: break; } - return formatMessage( "authorization failed for ", url, statusCode, reasonPhrase, proxyInfo ); + return formatMessage("authorization failed for ", url, statusCode, reasonPhrase, proxyInfo); } /** @@ -178,30 +166,23 @@ public static String formatAuthorizationMessage( String url, int statusCode, Str * @param proxyInfo proxy server used during the transfer, may be null if none used * @return a consistent message for a HTTP related {@link ResourceDoesNotExistException} */ - public static String formatResourceDoesNotExistMessage( String url, int statusCode, String reasonPhrase, - ProxyInfo proxyInfo ) - { - return formatMessage( "resource missing at ", url, statusCode, reasonPhrase, proxyInfo ); + public static String formatResourceDoesNotExistMessage( + String url, int statusCode, String reasonPhrase, ProxyInfo proxyInfo) { + return formatMessage("resource missing at ", url, statusCode, reasonPhrase, proxyInfo); } - private static String formatMessage( String message, String url, int statusCode, String reasonPhrase, - ProxyInfo proxyInfo ) - { - Objects.requireNonNull( message, "message cannot be null" ); - Objects.requireNonNull( url, "url cannot be null" ); + private static String formatMessage( + String message, String url, int statusCode, String reasonPhrase, ProxyInfo proxyInfo) { + Objects.requireNonNull(message, "message cannot be null"); + Objects.requireNonNull(url, "url cannot be null"); String msg = message + url; - if ( statusCode != UNKNOWN_STATUS_CODE ) - { + if (statusCode != UNKNOWN_STATUS_CODE) { msg += ", status: " + statusCode; - if ( reasonPhrase != null && !reasonPhrase.isEmpty() ) - { + if (reasonPhrase != null && !reasonPhrase.isEmpty()) { msg += " " + reasonPhrase; - } - else - { - switch ( statusCode ) - { + } else { + switch (statusCode) { case SC_UNAUTHORIZED: msg += " Unauthorized"; break; @@ -227,8 +208,7 @@ private static String formatMessage( String message, String url, int statusCode, } } } - if ( proxyInfo != null ) - { + if (proxyInfo != null) { msg += ", proxy: " + proxyInfo; } return msg; diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMethodConfiguration.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMethodConfiguration.java index cae1e351c..3cae08d6d 100755 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMethodConfiguration.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/HttpMethodConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; + +import java.util.Map; +import java.util.Properties; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.apache.maven.wagon.Wagon; -import java.util.Map; -import java.util.Properties; - /** * */ -public class HttpMethodConfiguration -{ +public class HttpMethodConfiguration { private Boolean useDefaultHeaders; @@ -41,134 +39,112 @@ public class HttpMethodConfiguration private int connectionTimeout = Wagon.DEFAULT_CONNECTION_TIMEOUT; private int readTimeout = - Integer.parseInt( System.getProperty( "maven.wagon.rto", Integer.toString( Wagon.DEFAULT_READ_TIMEOUT ) ) ); + Integer.parseInt(System.getProperty("maven.wagon.rto", Integer.toString(Wagon.DEFAULT_READ_TIMEOUT))); private boolean usePreemptive = false; - public boolean isUseDefaultHeaders() - { + public boolean isUseDefaultHeaders() { return useDefaultHeaders == null || useDefaultHeaders.booleanValue(); } - public HttpMethodConfiguration setUseDefaultHeaders( boolean useDefaultHeaders ) - { - this.useDefaultHeaders = Boolean.valueOf( useDefaultHeaders ); + public HttpMethodConfiguration setUseDefaultHeaders(boolean useDefaultHeaders) { + this.useDefaultHeaders = Boolean.valueOf(useDefaultHeaders); return this; } - public Boolean getUseDefaultHeaders() - { + public Boolean getUseDefaultHeaders() { return useDefaultHeaders; } - public HttpMethodConfiguration addHeader( String header, String value ) - { - headers.setProperty( header, value ); + public HttpMethodConfiguration addHeader(String header, String value) { + headers.setProperty(header, value); return this; } - public Properties getHeaders() - { + public Properties getHeaders() { return headers; } - public HttpMethodConfiguration setHeaders( Properties headers ) - { + public HttpMethodConfiguration setHeaders(Properties headers) { this.headers = headers; return this; } - public HttpMethodConfiguration addParam( String param, String value ) - { - params.setProperty( param, value ); + public HttpMethodConfiguration addParam(String param, String value) { + params.setProperty(param, value); return this; } - public Properties getParams() - { + public Properties getParams() { return params; } - public HttpMethodConfiguration setParams( Properties params ) - { + public HttpMethodConfiguration setParams(Properties params) { this.params = params; return this; } - public int getConnectionTimeout() - { + public int getConnectionTimeout() { return connectionTimeout; } - public HttpMethodConfiguration setConnectionTimeout( int connectionTimeout ) - { + public HttpMethodConfiguration setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } - public int getReadTimeout() - { + public int getReadTimeout() { return readTimeout; } - public HttpMethodConfiguration setReadTimeout( int readTimeout ) - { + public HttpMethodConfiguration setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; return this; } - public boolean isUsePreemptive() - { + public boolean isUsePreemptive() { return usePreemptive; } - public HttpMethodConfiguration setUsePreemptive( boolean usePreemptive ) - { + public HttpMethodConfiguration setUsePreemptive(boolean usePreemptive) { this.usePreemptive = usePreemptive; return this; } - public Header[] asRequestHeaders() - { - if ( headers == null ) - { + public Header[] asRequestHeaders() { + if (headers == null) { return new Header[0]; } Header[] result = new Header[headers.size()]; int index = 0; - for ( Map.Entry entry : headers.entrySet() ) - { + for (Map.Entry entry : headers.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); - Header header = new BasicHeader( key, value ); + Header header = new BasicHeader(key, value); result[index++] = header; } return result; } - HttpMethodConfiguration copy() - { + HttpMethodConfiguration copy() { HttpMethodConfiguration copy = new HttpMethodConfiguration(); - copy.setConnectionTimeout( getConnectionTimeout() ); - copy.setReadTimeout( getReadTimeout() ); - if ( getHeaders() != null ) - { - copy.getHeaders().putAll( getHeaders() ); + copy.setConnectionTimeout(getConnectionTimeout()); + copy.setReadTimeout(getReadTimeout()); + if (getHeaders() != null) { + copy.getHeaders().putAll(getHeaders()); } - if ( getParams() != null ) - { - copy.getParams().putAll( getParams() ); + if (getParams() != null) { + copy.getParams().putAll(getParams()); } - copy.setUseDefaultHeaders( isUseDefaultHeaders() ); + copy.setUseDefaultHeaders(isUseDefaultHeaders()); return copy; } - } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/RelaxedTrustStrategy.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/RelaxedTrustStrategy.java index f611d123c..f56e59709 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/RelaxedTrustStrategy.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/RelaxedTrustStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,62 +16,46 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.http.conn.ssl.TrustStrategy; +package org.apache.maven.wagon.shared.http; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; +import org.apache.http.conn.ssl.TrustStrategy; + /** * Relaxed X509 certificate trust manager: can ignore invalid certificate date. * * @author Olivier Lamy * @since 2.0 */ -public class RelaxedTrustStrategy - implements TrustStrategy -{ +public class RelaxedTrustStrategy implements TrustStrategy { private final boolean ignoreSSLValidityDates; - public RelaxedTrustStrategy( boolean ignoreSSLValidityDates ) - { + public RelaxedTrustStrategy(boolean ignoreSSLValidityDates) { this.ignoreSSLValidityDates = ignoreSSLValidityDates; } - public boolean isTrusted( X509Certificate[] certificates, String authType ) - throws CertificateException - { - if ( ( certificates != null ) && ( certificates.length > 0 ) ) - { - for ( X509Certificate currentCertificate : certificates ) - { - try - { + public boolean isTrusted(X509Certificate[] certificates, String authType) throws CertificateException { + if ((certificates != null) && (certificates.length > 0)) { + for (X509Certificate currentCertificate : certificates) { + try { currentCertificate.checkValidity(); - } - catch ( CertificateExpiredException e ) - { - if ( !ignoreSSLValidityDates ) - { + } catch (CertificateExpiredException e) { + if (!ignoreSSLValidityDates) { throw e; } - } - catch ( CertificateNotYetValidException e ) - { - if ( !ignoreSSLValidityDates ) - { + } catch (CertificateNotYetValidException e) { + if (!ignoreSSLValidityDates) { throw e; } } } return true; - } - else - { + } else { return false; } } - } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/StandardServiceUnavailableRetryStrategy.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/StandardServiceUnavailableRetryStrategy.java index 7f4d485c4..ed6e8fa5d 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/StandardServiceUnavailableRetryStrategy.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/StandardServiceUnavailableRetryStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -32,9 +31,8 @@ * that retries {@code 408} (Request Timeout), {@code 429} (Too Many Requests), * and {@code 500} (Server side error) responses for a fixed number of times at a fixed interval. */ -@Contract( threading = ThreadingBehavior.IMMUTABLE ) -public class StandardServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy -{ +@Contract(threading = ThreadingBehavior.IMMUTABLE) +public class StandardServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy { /** * Maximum number of allowed retries if the server responds with a HTTP code * in our retry code list. @@ -46,18 +44,16 @@ public class StandardServiceUnavailableRetryStrategy implements ServiceUnavailab */ private final long retryInterval; - public StandardServiceUnavailableRetryStrategy( final int maxRetries, final int retryInterval ) - { + public StandardServiceUnavailableRetryStrategy(final int maxRetries, final int retryInterval) { super(); - Args.positive( maxRetries, "Max retries" ); - Args.positive( retryInterval, "Retry interval" ); + Args.positive(maxRetries, "Max retries"); + Args.positive(retryInterval, "Retry interval"); this.maxRetries = maxRetries; this.retryInterval = retryInterval; } @Override - public boolean retryRequest( final HttpResponse response, final int executionCount, final HttpContext context ) - { + public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean retryableStatusCode = statusCode == HttpStatus.SC_REQUEST_TIMEOUT // Too Many Requests ("standard" rate-limiting) @@ -71,9 +67,7 @@ public boolean retryRequest( final HttpResponse response, final int executionCou } @Override - public long getRetryInterval() - { + public long getRetryInterval() { return retryInterval; } - } diff --git a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/WagonRedirectStrategy.java b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/WagonRedirectStrategy.java index 6694a3846..c704d08ce 100644 --- a/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/WagonRedirectStrategy.java +++ b/wagon-providers/wagon-http-shared/src/main/java/org/apache/maven/wagon/shared/http/WagonRedirectStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.shared.http; import java.net.URI; @@ -45,82 +44,74 @@ * @since 3.4.0 * */ -public class WagonRedirectStrategy extends DefaultRedirectStrategy -{ +public class WagonRedirectStrategy extends DefaultRedirectStrategy { - private static final Logger LOGGER = LoggerFactory.getLogger( WagonRedirectStrategy.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(WagonRedirectStrategy.class); private static final int SC_PERMANENT_REDIRECT = 308; - public WagonRedirectStrategy() - { - super( new String[] { - HttpGet.METHOD_NAME, - HttpHead.METHOD_NAME, - HttpPut.METHOD_NAME, - /** - * This covers the most basic case where the redirection relocates to another - * collection which has an existing parent collection. - */ - "MKCOL" } ); + public WagonRedirectStrategy() { + super(new String[] { + HttpGet.METHOD_NAME, + HttpHead.METHOD_NAME, + HttpPut.METHOD_NAME, + /** + * This covers the most basic case where the redirection relocates to another + * collection which has an existing parent collection. + */ + "MKCOL" + }); } @Override - public boolean isRedirected( final HttpRequest request, final HttpResponse response, - final HttpContext context ) throws ProtocolException - { - Args.notNull( request, "HTTP request" ); - Args.notNull( response, "HTTP response" ); + public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) + throws ProtocolException { + Args.notNull(request, "HTTP request"); + Args.notNull(response, "HTTP response"); final int statusCode = response.getStatusLine().getStatusCode(); final String method = request.getRequestLine().getMethod(); - switch ( statusCode ) - { - case HttpStatus.SC_MOVED_TEMPORARILY: - case HttpStatus.SC_MOVED_PERMANENTLY: - case HttpStatus.SC_SEE_OTHER: - case HttpStatus.SC_TEMPORARY_REDIRECT: - case SC_PERMANENT_REDIRECT: - return isRedirectable( method ); - default: - return false; + switch (statusCode) { + case HttpStatus.SC_MOVED_TEMPORARILY: + case HttpStatus.SC_MOVED_PERMANENTLY: + case HttpStatus.SC_SEE_OTHER: + case HttpStatus.SC_TEMPORARY_REDIRECT: + case SC_PERMANENT_REDIRECT: + return isRedirectable(method); + default: + return false; } } @Override - public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, - final HttpContext context ) throws ProtocolException - { - final URI uri = getLocationURI( request, response, context ); - if ( request instanceof HttpEntityEnclosingRequest ) - { + public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) + throws ProtocolException { + final URI uri = getLocationURI(request, response, context); + if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest encRequest = (HttpEntityEnclosingRequest) request; - if ( encRequest.getEntity() instanceof AbstractHttpClientWagon.WagonHttpEntity ) - { + if (encRequest.getEntity() instanceof AbstractHttpClientWagon.WagonHttpEntity) { AbstractHttpClientWagon.WagonHttpEntity whe = (WagonHttpEntity) encRequest.getEntity(); - if ( whe.getWagon() instanceof AbstractHttpClientWagon ) - { + if (whe.getWagon() instanceof AbstractHttpClientWagon) { // Re-execute AbstractWagon#firePutStarted(Resource, File) AbstractHttpClientWagon httpWagon = (AbstractHttpClientWagon) whe.getWagon(); - TransferEvent transferEvent = - new TransferEvent( httpWagon, whe.getResource(), - TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_PUT ); - transferEvent.setTimestamp( System.currentTimeMillis() ); - transferEvent.setLocalFile( whe.getSource() ); - httpWagon.getTransferEventSupport().fireDebug( - String.format( "Following redirect from '%s' to '%s'", - request.getRequestLine().getUri(), uri.toASCIIString() ) ); - httpWagon.getTransferEventSupport().fireTransferStarted( transferEvent ); - } - else - { - LOGGER.warn( "Cannot properly handle redirect transfer event, wagon has unexpected class: {}", - whe.getWagon().getClass() ); + TransferEvent transferEvent = new TransferEvent( + httpWagon, whe.getResource(), TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_PUT); + transferEvent.setTimestamp(System.currentTimeMillis()); + transferEvent.setLocalFile(whe.getSource()); + httpWagon + .getTransferEventSupport() + .fireDebug(String.format( + "Following redirect from '%s' to '%s'", + request.getRequestLine().getUri(), uri.toASCIIString())); + httpWagon.getTransferEventSupport().fireTransferStarted(transferEvent); + } else { + LOGGER.warn( + "Cannot properly handle redirect transfer event, wagon has unexpected class: {}", + whe.getWagon().getClass()); } } } - return RequestBuilder.copy( request ).setUri( uri ).build(); + return RequestBuilder.copy(request).setUri(uri).build(); } - } diff --git a/wagon-providers/wagon-http-shared/src/test/java/org/apache/maven/wagon/shared/http/EncodingUtilTest.java b/wagon-providers/wagon-http-shared/src/test/java/org/apache/maven/wagon/shared/http/EncodingUtilTest.java index 639ad1f86..4093c13e0 100644 --- a/wagon-providers/wagon-http-shared/src/test/java/org/apache/maven/wagon/shared/http/EncodingUtilTest.java +++ b/wagon-providers/wagon-http-shared/src/test/java/org/apache/maven/wagon/shared/http/EncodingUtilTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.shared.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,116 +16,91 @@ * specific language governing permissions and limitations * under the License. */ - -import junit.framework.TestCase; +package org.apache.maven.wagon.shared.http; import java.net.MalformedURLException; import java.net.URISyntaxException; -public class EncodingUtilTest - extends TestCase -{ - public void testEncodeURLWithTrailingSlash() - { - String encodedURL = EncodingUtil.encodeURLToString( "https://host:1234/test", "demo/" ); +import junit.framework.TestCase; + +public class EncodingUtilTest extends TestCase { + public void testEncodeURLWithTrailingSlash() { + String encodedURL = EncodingUtil.encodeURLToString("https://host:1234/test", "demo/"); - assertEquals( "https://host:1234/test/demo/", encodedURL ); + assertEquals("https://host:1234/test/demo/", encodedURL); } - public void testEncodeURLWithSpaces() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/path with spaces" ); + public void testEncodeURLWithSpaces() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/path with spaces"); - assertEquals( "file://host:1/path%20with%20spaces", encodedURL ); + assertEquals("file://host:1/path%20with%20spaces", encodedURL); } - public void testEncodeURLWithSpacesInPath() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1", "path with spaces" ); + public void testEncodeURLWithSpacesInPath() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1", "path with spaces"); - assertEquals( "file://host:1/path%20with%20spaces", encodedURL ); + assertEquals("file://host:1/path%20with%20spaces", encodedURL); } - public void testEncodeURLWithSpacesInBothBaseAndPath() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/with%20a", "path with spaces" ); + public void testEncodeURLWithSpacesInBothBaseAndPath() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/with%20a", "path with spaces"); - assertEquals( "file://host:1/with%20a/path%20with%20spaces", encodedURL ); + assertEquals("file://host:1/with%20a/path%20with%20spaces", encodedURL); } - public void testEncodeURLWithSlashes1() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/basePath", "a", "b", "c" ); + public void testEncodeURLWithSlashes1() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/basePath", "a", "b", "c"); - assertEquals( "file://host:1/basePath/a/b/c", encodedURL ); + assertEquals("file://host:1/basePath/a/b/c", encodedURL); - encodedURL = EncodingUtil.encodeURLToString( "file://host:1/basePath", "a/b/c" ); + encodedURL = EncodingUtil.encodeURLToString("file://host:1/basePath", "a/b/c"); - assertEquals( "file://host:1/basePath/a/b/c", encodedURL ); + assertEquals("file://host:1/basePath/a/b/c", encodedURL); } - public void testEncodeURLWithSlashes2() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/basePath/", "a", "b", "c" ); + public void testEncodeURLWithSlashes2() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/basePath/", "a", "b", "c"); - assertEquals( "file://host:1/basePath/a/b/c", encodedURL ); + assertEquals("file://host:1/basePath/a/b/c", encodedURL); - encodedURL = EncodingUtil.encodeURLToString( "file://host:1/basePath/", "a/b/c" ); + encodedURL = EncodingUtil.encodeURLToString("file://host:1/basePath/", "a/b/c"); - assertEquals( "file://host:1/basePath/a/b/c", encodedURL ); + assertEquals("file://host:1/basePath/a/b/c", encodedURL); } - public void testEncodeURLWithSlashes3() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/basePath/", new String[0] ); + public void testEncodeURLWithSlashes3() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/basePath/", new String[0]); - assertEquals( "file://host:1/basePath/", encodedURL ); + assertEquals("file://host:1/basePath/", encodedURL); } - public void testEncodeURLWithSlashes4() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/basePath", new String[0] ); + public void testEncodeURLWithSlashes4() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/basePath", new String[0]); - assertEquals( "file://host:1/basePath", encodedURL ); + assertEquals("file://host:1/basePath", encodedURL); } - public void testEncodeURLWithSlashes5() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/basePath", - "a/1", "b/1", "c/1" ); + public void testEncodeURLWithSlashes5() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/basePath", "a/1", "b/1", "c/1"); - assertEquals( "file://host:1/basePath/a%2F1/b%2F1/c%2F1", encodedURL ); + assertEquals("file://host:1/basePath/a%2F1/b%2F1/c%2F1", encodedURL); } - public void testEncodeURLWithSlashes6() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1/", new String[0] ); + public void testEncodeURLWithSlashes6() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1/", new String[0]); - assertEquals( "file://host:1/", encodedURL ); + assertEquals("file://host:1/", encodedURL); } - public void testEncodeURLWithSlashes7() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1", new String[0] ); + public void testEncodeURLWithSlashes7() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1", new String[0]); - assertEquals( "file://host:1", encodedURL ); + assertEquals("file://host:1", encodedURL); } - public void testEncodeURLWithNonLatin() - throws URISyntaxException, MalformedURLException - { - String encodedURL = EncodingUtil.encodeURLToString( "file://host:1", "пипец/" ); + public void testEncodeURLWithNonLatin() throws URISyntaxException, MalformedURLException { + String encodedURL = EncodingUtil.encodeURLToString("file://host:1", "пипец/"); - assertEquals( "file://host:1/%D0%BF%D0%B8%D0%BF%D0%B5%D1%86/", encodedURL ); + assertEquals("file://host:1/%D0%BF%D0%B8%D0%BF%D0%B5%D1%86/", encodedURL); } } diff --git a/wagon-providers/wagon-http/src/main/java/org/apache/maven/wagon/providers/http/HttpWagon.java b/wagon-providers/wagon-http/src/main/java/org/apache/maven/wagon/providers/http/HttpWagon.java index ee65c9937..ae5d720f8 100644 --- a/wagon-providers/wagon-http/src/main/java/org/apache/maven/wagon/providers/http/HttpWagon.java +++ b/wagon-providers/wagon-http/src/main/java/org/apache/maven/wagon/providers/http/HttpWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.shared.http.AbstractHttpClientWagon; /** * @author Michal Maczka */ -public class HttpWagon - extends AbstractHttpClientWagon -{ - -} +public class HttpWagon extends AbstractHttpClientWagon {} diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/AbstractHttpClientWagonTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/AbstractHttpClientWagonTest.java index f363361de..6ae9f3b19 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/AbstractHttpClientWagonTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/AbstractHttpClientWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import javax.net.ssl.SSLException; import java.io.File; import java.io.IOException; @@ -40,8 +33,6 @@ import java.util.Collection; import java.util.Set; -import javax.net.ssl.SSLException; - import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; @@ -54,223 +45,192 @@ import org.junit.Ignore; import org.junit.Test; -public class AbstractHttpClientWagonTest -{ +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class AbstractHttpClientWagonTest { @Ignore("This test is validating nothing and require internet connection which we should avoid so ignore it") - public void test() - throws Exception - { - AbstractHttpClientWagon wagon = new AbstractHttpClientWagon() - { - }; + public void test() throws Exception { + AbstractHttpClientWagon wagon = new AbstractHttpClientWagon() {}; - Repository repository = new Repository( "central", "http://repo.maven.apache.org/maven2" ); + Repository repository = new Repository("central", "http://repo.maven.apache.org/maven2"); - wagon.connect( repository ); + wagon.connect(repository); Resource resource = new Resource(); - resource.setName( "junit/junit/maven-metadata.xml" ); + resource.setName("junit/junit/maven-metadata.xml"); InputData inputData = new InputData(); - inputData.setResource( resource ); + inputData.setResource(resource); - wagon.fillInputData( inputData ); + wagon.fillInputData(inputData); wagon.disconnect(); } @Test - public void retryableConfigurationDefaultTest() throws Exception - { - doTestHttpClient( new Runnable() - { + public void retryableConfigurationDefaultTest() throws Exception { + doTestHttpClient(new Runnable() { @Override - public void run() - { + public void run() { final HttpRequestRetryHandler handler = getCurrentHandler(); - assertNotNull( handler ); - assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); + assertNotNull(handler); + assertThat(handler, instanceOf(DefaultHttpRequestRetryHandler.class)); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); - assertEquals( 3, impl.getRetryCount() ); - assertFalse( impl.isRequestSentRetryEnabled() ); + assertEquals(3, impl.getRetryCount()); + assertFalse(impl.isRequestSentRetryEnabled()); } }); } @Test - public void retryableConfigurationCountTest() throws Exception - { - doTestHttpClient( new Runnable() - { + public void retryableConfigurationCountTest() throws Exception { + doTestHttpClient(new Runnable() { @Override - public void run() - { - System.setProperty( "maven.wagon.http.retryHandler.class", "default" ); - System.setProperty( "maven.wagon.http.retryHandler.count", "5" ); + public void run() { + System.setProperty("maven.wagon.http.retryHandler.class", "default"); + System.setProperty("maven.wagon.http.retryHandler.count", "5"); final HttpRequestRetryHandler handler = getCurrentHandler(); - assertNotNull( handler ); - assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); + assertNotNull(handler); + assertThat(handler, instanceOf(DefaultHttpRequestRetryHandler.class)); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); - assertEquals( 5, impl.getRetryCount() ); - assertFalse( impl.isRequestSentRetryEnabled() ); + assertEquals(5, impl.getRetryCount()); + assertFalse(impl.isRequestSentRetryEnabled()); } }); } @Test - public void retryableConfigurationSentTest() throws Exception - { - doTestHttpClient( new Runnable() - { + public void retryableConfigurationSentTest() throws Exception { + doTestHttpClient(new Runnable() { @Override - public void run() - { - System.setProperty( "maven.wagon.http.retryHandler.class", "default" ); - System.setProperty( "maven.wagon.http.retryHandler.requestSentEnabled", "true" ); + public void run() { + System.setProperty("maven.wagon.http.retryHandler.class", "default"); + System.setProperty("maven.wagon.http.retryHandler.requestSentEnabled", "true"); final HttpRequestRetryHandler handler = getCurrentHandler(); - assertNotNull( handler ); - assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); + assertNotNull(handler); + assertThat(handler, instanceOf(DefaultHttpRequestRetryHandler.class)); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); - assertEquals( 3, impl.getRetryCount() ); - assertTrue( impl.isRequestSentRetryEnabled() ); + assertEquals(3, impl.getRetryCount()); + assertTrue(impl.isRequestSentRetryEnabled()); } }); } @Test - public void retryableConfigurationExceptionsTest() throws Exception - { - doTestHttpClient( new Runnable() - { + public void retryableConfigurationExceptionsTest() throws Exception { + doTestHttpClient(new Runnable() { @Override - public void run() - { - System.setProperty( "maven.wagon.http.retryHandler.class", "default" ); - System.setProperty( "maven.wagon.http.retryHandler.nonRetryableClasses", IOException.class.getName() ); + public void run() { + System.setProperty("maven.wagon.http.retryHandler.class", "default"); + System.setProperty("maven.wagon.http.retryHandler.nonRetryableClasses", IOException.class.getName()); final HttpRequestRetryHandler handler = getCurrentHandler(); - assertNotNull( handler ); - assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); + assertNotNull(handler); + assertThat(handler, instanceOf(DefaultHttpRequestRetryHandler.class)); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); - assertEquals( 3, impl.getRetryCount() ); - assertFalse( impl.isRequestSentRetryEnabled() ); + assertEquals(3, impl.getRetryCount()); + assertFalse(impl.isRequestSentRetryEnabled()); - try - { - final Field nonRetriableClasses = handler.getClass().getSuperclass() - .getDeclaredField( "nonRetriableClasses" ); - if ( !nonRetriableClasses.isAccessible() ) - { + try { + final Field nonRetriableClasses = + handler.getClass().getSuperclass().getDeclaredField("nonRetriableClasses"); + if (!nonRetriableClasses.isAccessible()) { nonRetriableClasses.setAccessible(true); } - final Set exceptions = Set.class.cast( nonRetriableClasses.get(handler) ); - assertEquals( 1, exceptions.size() ); - assertTrue( exceptions.contains( IOException.class ) ); - } - catch ( final Exception e ) - { - fail( e.getMessage() ); + final Set exceptions = Set.class.cast(nonRetriableClasses.get(handler)); + assertEquals(1, exceptions.size()); + assertTrue(exceptions.contains(IOException.class)); + } catch (final Exception e) { + fail(e.getMessage()); } } }); } - private HttpRequestRetryHandler getCurrentHandler() - { - try - { - final Class impl = Thread.currentThread().getContextClassLoader().loadClass( - "org.apache.maven.wagon.shared.http.AbstractHttpClientWagon" ); + private HttpRequestRetryHandler getCurrentHandler() { + try { + final Class impl = Thread.currentThread() + .getContextClassLoader() + .loadClass("org.apache.maven.wagon.shared.http.AbstractHttpClientWagon"); final CloseableHttpClient httpClient = CloseableHttpClient.class.cast( - impl.getMethod("getHttpClient").invoke(null) ); + impl.getMethod("getHttpClient").invoke(null)); - final Field redirectExec = httpClient.getClass().getDeclaredField( "execChain" ); - if ( !redirectExec.isAccessible() ) - { - redirectExec.setAccessible( true ); + final Field redirectExec = httpClient.getClass().getDeclaredField("execChain"); + if (!redirectExec.isAccessible()) { + redirectExec.setAccessible(true); } - final RedirectExec redirectExecInstance = RedirectExec.class.cast( - redirectExec.get( httpClient ) ); + final RedirectExec redirectExecInstance = RedirectExec.class.cast(redirectExec.get(httpClient)); - final Field requestExecutor = redirectExecInstance.getClass().getDeclaredField( "requestExecutor" ); - if ( !requestExecutor.isAccessible() ) - { - requestExecutor.setAccessible( true ); + final Field requestExecutor = redirectExecInstance.getClass().getDeclaredField("requestExecutor"); + if (!requestExecutor.isAccessible()) { + requestExecutor.setAccessible(true); } - final RetryExec requestExecutorInstance = RetryExec.class.cast( - requestExecutor.get( redirectExecInstance ) ); + final RetryExec requestExecutorInstance = RetryExec.class.cast(requestExecutor.get(redirectExecInstance)); - final Field retryHandler = requestExecutorInstance.getClass().getDeclaredField( "retryHandler" ); - if ( !retryHandler.isAccessible() ) - { - retryHandler.setAccessible( true ); + final Field retryHandler = requestExecutorInstance.getClass().getDeclaredField("retryHandler"); + if (!retryHandler.isAccessible()) { + retryHandler.setAccessible(true); } - return HttpRequestRetryHandler.class.cast( retryHandler.get( requestExecutorInstance ) ); - } - catch ( final Exception e ) - { + return HttpRequestRetryHandler.class.cast(retryHandler.get(requestExecutorInstance)); + } catch (final Exception e) { throw new IllegalStateException(e); } } - private void doTestHttpClient( final Runnable test ) throws Exception - { - final String classpath = System.getProperty( "java.class.path" ); - final String[] paths = classpath.split( File.pathSeparator ); - final Collection urls = new ArrayList<>( paths.length ); - for ( final String path : paths ) - { - try - { - urls.add( new File( path ).toURI().toURL() ); - } - catch ( final MalformedURLException e ) - { - fail( e.getMessage() ); + private void doTestHttpClient(final Runnable test) throws Exception { + final String classpath = System.getProperty("java.class.path"); + final String[] paths = classpath.split(File.pathSeparator); + final Collection urls = new ArrayList<>(paths.length); + for (final String path : paths) { + try { + urls.add(new File(path).toURI().toURL()); + } catch (final MalformedURLException e) { + fail(e.getMessage()); } } - final URLClassLoader loader = new URLClassLoader( urls.toArray( new URL[ paths.length ] ) , new ClassLoader() - { + final URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[paths.length]), new ClassLoader() { @Override - protected Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException - { - if ( name.startsWith( "org.apache.maven.wagon.shared.http" ) ) - { - throw new ClassNotFoundException( name ); + protected Class loadClass(final String name, final boolean resolve) throws ClassNotFoundException { + if (name.startsWith("org.apache.maven.wagon.shared.http")) { + throw new ClassNotFoundException(name); } - return super.loadClass( name, resolve ); + return super.loadClass(name, resolve); } }); final Thread thread = Thread.currentThread(); final ClassLoader contextClassLoader = thread.getContextClassLoader(); - thread.setContextClassLoader( loader ); - - final String originalClass = System.getProperty( "maven.wagon.http.retryHandler.class", "default" ); - final String originalSentEnabled = System.getProperty( - "maven.wagon.http.retryHandler.requestSentEnabled", "false" ); - final String originalCount = System.getProperty( "maven.wagon.http.retryHandler.count", "3" ); - final String originalExceptions = System.getProperty( "maven.wagon.http.retryHandler.nonRetryableClasses", + thread.setContextClassLoader(loader); + + final String originalClass = System.getProperty("maven.wagon.http.retryHandler.class", "default"); + final String originalSentEnabled = + System.getProperty("maven.wagon.http.retryHandler.requestSentEnabled", "false"); + final String originalCount = System.getProperty("maven.wagon.http.retryHandler.count", "3"); + final String originalExceptions = System.getProperty( + "maven.wagon.http.retryHandler.nonRetryableClasses", InterruptedIOException.class.getName() + "," - + UnknownHostException.class.getName() + "," - + ConnectException.class.getName() + "," - + SSLException.class.getName()); - try - { + + UnknownHostException.class.getName() + "," + + ConnectException.class.getName() + "," + + SSLException.class.getName()); + try { test.run(); - } - finally - { + } finally { loader.close(); - thread.setContextClassLoader( contextClassLoader ); - System.setProperty( "maven.wagon.http.retryHandler.class", originalClass ); - System.setProperty( "maven.wagon.http.retryHandler.requestSentEnabled", originalSentEnabled ); - System.setProperty( "maven.wagon.http.retryHandler.count", originalCount ); - System.setProperty( "maven.wagon.http.retryHandler.nonRetryableClasses", originalExceptions ); + thread.setContextClassLoader(contextClassLoader); + System.setProperty("maven.wagon.http.retryHandler.class", originalClass); + System.setProperty("maven.wagon.http.retryHandler.requestSentEnabled", originalSentEnabled); + System.setProperty("maven.wagon.http.retryHandler.count", originalCount); + System.setProperty("maven.wagon.http.retryHandler.nonRetryableClasses", originalExceptions); } } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/BasicAuthScopeTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/BasicAuthScopeTest.java index 708278c12..0ce431a61 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/BasicAuthScopeTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/BasicAuthScopeTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,84 +16,79 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.http.auth.AuthScope; import org.apache.maven.wagon.shared.http.BasicAuthScope; import org.junit.Assert; import org.junit.Test; -public class BasicAuthScopeTest -{ +public class BasicAuthScopeTest { /** * Test AuthScope override with no overriding values set. Nothing should * change in original host/port. */ @Test - public void testGetScopeNothingOverridden() - { + public void testGetScopeNothingOverridden() { BasicAuthScope scope = new BasicAuthScope(); - AuthScope authScope = scope.getScope( "original.host.com", 3456 ); - Assert.assertEquals( "original.host.com", authScope.getHost() ); - Assert.assertEquals( 3456, authScope.getPort() ); - Assert.assertEquals( AuthScope.ANY_REALM, authScope.getRealm() ); + AuthScope authScope = scope.getScope("original.host.com", 3456); + Assert.assertEquals("original.host.com", authScope.getHost()); + Assert.assertEquals(3456, authScope.getPort()); + Assert.assertEquals(AuthScope.ANY_REALM, authScope.getRealm()); } /** * Test AuthScope override for all values overridden */ @Test - public void testGetScopeAllOverridden() - { + public void testGetScopeAllOverridden() { BasicAuthScope scope = new BasicAuthScope(); - scope.setHost( "override.host.com" ); - scope.setPort( "1234" ); - scope.setRealm( "override-realm" ); - AuthScope authScope = scope.getScope( "original.host.com", 3456 ); - Assert.assertEquals( "override.host.com", authScope.getHost() ); - Assert.assertEquals( 1234, authScope.getPort() ); - Assert.assertEquals( "override-realm", authScope.getRealm() ); + scope.setHost("override.host.com"); + scope.setPort("1234"); + scope.setRealm("override-realm"); + AuthScope authScope = scope.getScope("original.host.com", 3456); + Assert.assertEquals("override.host.com", authScope.getHost()); + Assert.assertEquals(1234, authScope.getPort()); + Assert.assertEquals("override-realm", authScope.getRealm()); } /** * Test AuthScope override for all values overridden with "ANY" */ @Test - public void testGetScopeAllAny() - { + public void testGetScopeAllAny() { BasicAuthScope scope = new BasicAuthScope(); - scope.setHost( "ANY" ); - scope.setPort( "ANY" ); - scope.setRealm( "ANY" ); - AuthScope authScope = scope.getScope( "original.host.com", 3456 ); - Assert.assertEquals( AuthScope.ANY_HOST, authScope.getHost() ); - Assert.assertEquals( AuthScope.ANY_PORT, authScope.getPort() ); - Assert.assertEquals( AuthScope.ANY_REALM, authScope.getRealm() ); + scope.setHost("ANY"); + scope.setPort("ANY"); + scope.setRealm("ANY"); + AuthScope authScope = scope.getScope("original.host.com", 3456); + Assert.assertEquals(AuthScope.ANY_HOST, authScope.getHost()); + Assert.assertEquals(AuthScope.ANY_PORT, authScope.getPort()); + Assert.assertEquals(AuthScope.ANY_REALM, authScope.getRealm()); } /** * Test AuthScope override for realm value overridden */ @Test - public void testGetScopeRealmOverridden() - { + public void testGetScopeRealmOverridden() { BasicAuthScope scope = new BasicAuthScope(); - scope.setRealm( "override-realm" ); - AuthScope authScope = scope.getScope( "original.host.com", 3456 ); - Assert.assertEquals( "original.host.com", authScope.getHost() ); - Assert.assertEquals( 3456, authScope.getPort() ); - Assert.assertEquals( "override-realm", authScope.getRealm() ); + scope.setRealm("override-realm"); + AuthScope authScope = scope.getScope("original.host.com", 3456); + Assert.assertEquals("original.host.com", authScope.getHost()); + Assert.assertEquals(3456, authScope.getPort()); + Assert.assertEquals("override-realm", authScope.getRealm()); } /** * Test AuthScope where original port is -1, which should result in ANY */ @Test - public void testGetScopeOriginalPortIsNegativeOne() - { + public void testGetScopeOriginalPortIsNegativeOne() { BasicAuthScope scope = new BasicAuthScope(); - AuthScope authScope = scope.getScope( "original.host.com", -1 ); - Assert.assertEquals( AuthScope.ANY_PORT, authScope.getPort() ); + AuthScope authScope = scope.getScope("original.host.com", -1); + Assert.assertEquals(AuthScope.ANY_PORT, authScope.getPort()); } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/ErrorWithMessageServlet.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/ErrorWithMessageServlet.java index 1d7641298..4eadd309b 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/ErrorWithMessageServlet.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/ErrorWithMessageServlet.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.wagon.providers.http; /* @@ -23,6 +41,7 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; /** @@ -30,36 +49,22 @@ * Date: 24/01/2008 * Time: 17:25:27 */ -public class ErrorWithMessageServlet - extends HttpServlet -{ +public class ErrorWithMessageServlet extends HttpServlet { private static final long serialVersionUID = -1419714266724471393L; public static final String MESSAGE = "it sucks!"; - public void service( HttpServletRequest request, HttpServletResponse response ) - throws ServletException, IOException - { - if ( request.getPathInfo().endsWith( "/401" ) ) - { - response.sendError( 401, MESSAGE ); - } - else if ( request.getPathInfo().endsWith( "/403" ) ) - { - response.sendError( 403, MESSAGE ); - } - else if ( request.getPathInfo().endsWith( "/404" ) ) - { - response.sendError( 404, MESSAGE ); + public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (request.getPathInfo().endsWith("/401")) { + response.sendError(401, MESSAGE); + } else if (request.getPathInfo().endsWith("/403")) { + response.sendError(403, MESSAGE); + } else if (request.getPathInfo().endsWith("/404")) { + response.sendError(404, MESSAGE); + } else if (request.getPathInfo().endsWith("/407")) { + response.sendError(407, MESSAGE); + } else if (request.getPathInfo().endsWith("/500")) { + response.sendError(500, MESSAGE); } - else if ( request.getPathInfo().endsWith( "/407" ) ) - { - response.sendError( 407, MESSAGE ); - } - else if ( request.getPathInfo().endsWith( "/500" ) ) - { - response.sendError( 500, MESSAGE ); - } - } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpClientWagonTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpClientWagonTest.java index 6ea7da681..f7d484798 100755 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpClientWagonTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpClientWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.wagon.providers.http; import junit.framework.TestCase; - import org.apache.http.Header; - - import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpHead; import org.apache.maven.wagon.OutputData; @@ -34,83 +29,71 @@ import org.apache.maven.wagon.shared.http.HttpConfiguration; import org.apache.maven.wagon.shared.http.HttpMethodConfiguration; -public class HttpClientWagonTest - extends TestCase -{ +public class HttpClientWagonTest extends TestCase { - public void testSetMaxRedirectsParamViaConfig() - { + public void testSetMaxRedirectsParamViaConfig() { HttpMethodConfiguration methodConfig = new HttpMethodConfiguration(); int maxRedirects = 2; methodConfig.addParam("http.protocol.max-redirects", "%i," + maxRedirects); HttpConfiguration config = new HttpConfiguration(); - config.setAll( methodConfig ); + config.setAll(methodConfig); HttpHead method = new HttpHead(); RequestConfig.Builder builder = RequestConfig.custom(); - ConfigurationUtils.copyConfig( config.getMethodConfiguration( method ), builder ); + ConfigurationUtils.copyConfig(config.getMethodConfiguration(method), builder); RequestConfig requestConfig = builder.build(); assertEquals(2, requestConfig.getMaxRedirects()); } - public void testDefaultHeadersUsedByDefault() - { + public void testDefaultHeadersUsedByDefault() { HttpConfiguration config = new HttpConfiguration(); - config.setAll( new HttpMethodConfiguration() ); + config.setAll(new HttpMethodConfiguration()); TestWagon wagon = new TestWagon(); - wagon.setHttpConfiguration( config ); + wagon.setHttpConfiguration(config); HttpHead method = new HttpHead(); - wagon.setHeaders( method ); + wagon.setHeaders(method); // these are the default headers. // method.addRequestHeader( "Cache-control", "no-cache" ); // method.addRequestHeader( "Pragma", "no-cache" ); // "Accept-Encoding" is automatically set by HttpClient at runtime - Header header = method.getFirstHeader( "Cache-control" ); - assertNotNull( header ); - assertEquals( "no-cache", header.getValue() ); + Header header = method.getFirstHeader("Cache-control"); + assertNotNull(header); + assertEquals("no-cache", header.getValue()); - header = method.getFirstHeader( "Pragma" ); - assertNotNull( header ); - assertEquals( "no-cache", header.getValue() ); + header = method.getFirstHeader("Pragma"); + assertNotNull(header); + assertEquals("no-cache", header.getValue()); } - public void testTurnOffDefaultHeaders() - { + public void testTurnOffDefaultHeaders() { HttpConfiguration config = new HttpConfiguration(); - config.setAll( new HttpMethodConfiguration().setUseDefaultHeaders( false ) ); + config.setAll(new HttpMethodConfiguration().setUseDefaultHeaders(false)); TestWagon wagon = new TestWagon(); - wagon.setHttpConfiguration( config ); + wagon.setHttpConfiguration(config); HttpHead method = new HttpHead(); - wagon.setHeaders( method ); + wagon.setHeaders(method); // these are the default headers. // method.addRequestHeader( "Cache-control", "no-cache" ); // method.addRequestHeader( "Pragma", "no-cache" ); - Header header = method.getFirstHeader( "Cache-control" ); - assertNull( header ); + Header header = method.getFirstHeader("Cache-control"); + assertNull(header); - header = method.getFirstHeader( "Pragma" ); - assertNull( header ); + header = method.getFirstHeader("Pragma"); + assertNull(header); } - private static final class TestWagon - extends AbstractHttpClientWagon - { + private static final class TestWagon extends AbstractHttpClientWagon { @Override - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - - } + public void fillOutputData(OutputData outputData) throws TransferFailedException {} } - } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonErrorTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonErrorTest.java index 17b4e5ac3..ca518018c 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonErrorTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonErrorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; + +import java.io.File; import org.apache.maven.wagon.FileTestUtils; import org.apache.maven.wagon.ResourceDoesNotExistException; @@ -27,203 +28,172 @@ import org.apache.maven.wagon.repository.Repository; import org.eclipse.jetty.servlet.ServletHolder; -import java.io.File; - /** * User: jdumay Date: 24/01/2008 Time: 17:17:34 */ -public class HttpWagonErrorTest - extends HttpWagonHttpServerTestCase -{ +public class HttpWagonErrorTest extends HttpWagonHttpServerTestCase { private int serverPort; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - ServletHolder servlets = new ServletHolder( new ErrorWithMessageServlet() ); - context.addServlet( servlets, "/*" ); + ServletHolder servlets = new ServletHolder(new ErrorWithMessageServlet()); + context.addServlet(servlets, "/*"); startServer(); serverPort = getPort(); } - public void testGet401() - throws Exception - { + public void testGet401() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + serverPort ); + testRepository.setUrl("http://localhost:" + serverPort); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + File destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "401", destFile ); + wagon.get("401", destFile); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( AuthorizationException.class, thrown.getClass() ); - assertEquals( "authentication failed for http://localhost:" + serverPort + "/401, status: 401 " - + ErrorWithMessageServlet.MESSAGE, thrown.getMessage() ); + assertNotNull(thrown); + assertEquals(AuthorizationException.class, thrown.getClass()); + assertEquals( + "authentication failed for http://localhost:" + serverPort + "/401, status: 401 " + + ErrorWithMessageServlet.MESSAGE, + thrown.getMessage()); } - public void testGet403() - throws Exception - { + public void testGet403() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + serverPort ); + testRepository.setUrl("http://localhost:" + serverPort); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + File destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "403", destFile ); + wagon.get("403", destFile); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( AuthorizationException.class, thrown.getClass() ); - assertEquals( "authorization failed for http://localhost:" + serverPort + "/403, status: 403 " - + ErrorWithMessageServlet.MESSAGE, thrown.getMessage() ); + assertNotNull(thrown); + assertEquals(AuthorizationException.class, thrown.getClass()); + assertEquals( + "authorization failed for http://localhost:" + serverPort + "/403, status: 403 " + + ErrorWithMessageServlet.MESSAGE, + thrown.getMessage()); } - public void testGet404() - throws Exception - { + public void testGet404() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + serverPort ); + testRepository.setUrl("http://localhost:" + serverPort); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + File destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "404", destFile ); + wagon.get("404", destFile); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( ResourceDoesNotExistException.class, thrown.getClass() ); - assertEquals( "resource missing at http://localhost:" + serverPort + "/404, status: 404 " - + ErrorWithMessageServlet.MESSAGE, thrown.getMessage() ); + assertNotNull(thrown); + assertEquals(ResourceDoesNotExistException.class, thrown.getClass()); + assertEquals( + "resource missing at http://localhost:" + serverPort + "/404, status: 404 " + + ErrorWithMessageServlet.MESSAGE, + thrown.getMessage()); } - public void testGet407() - throws Exception - { + public void testGet407() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + getPort() ); + testRepository.setUrl("http://localhost:" + getPort()); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + File destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "407", destFile ); + wagon.get("407", destFile); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( AuthorizationException.class, thrown.getClass() ); - assertEquals( "proxy authentication failed for http://localhost:" + serverPort + "/407, status: 407 " - + ErrorWithMessageServlet.MESSAGE, thrown.getMessage() ); + assertNotNull(thrown); + assertEquals(AuthorizationException.class, thrown.getClass()); + assertEquals( + "proxy authentication failed for http://localhost:" + serverPort + "/407, status: 407 " + + ErrorWithMessageServlet.MESSAGE, + thrown.getMessage()); } - public void testGet500() - throws Exception - { + public void testGet500() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + serverPort ); + testRepository.setUrl("http://localhost:" + serverPort); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + File destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "500", destFile ); + wagon.get("500", destFile); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( TransferFailedException.class, thrown.getClass() ); - assertEquals( "transfer failed for http://localhost:" + serverPort + "/500, status: 500 " - + ErrorWithMessageServlet.MESSAGE, thrown.getMessage() ); + assertNotNull(thrown); + assertEquals(TransferFailedException.class, thrown.getClass()); + assertEquals( + "transfer failed for http://localhost:" + serverPort + "/500, status: 500 " + + ErrorWithMessageServlet.MESSAGE, + thrown.getMessage()); } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonHttpServerTestCase.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonHttpServerTestCase.java index 38cd7e185..b04c6cd03 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonHttpServerTestCase.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonHttpServerTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.Wagon; import org.codehaus.plexus.PlexusTestCase; @@ -29,48 +28,36 @@ /** * User: jdumay Date: 24/01/2008 Time: 18:15:53 */ -public abstract class HttpWagonHttpServerTestCase - extends PlexusTestCase -{ +public abstract class HttpWagonHttpServerTestCase extends PlexusTestCase { private Server server; protected ResourceHandler resourceHandler; protected ServletContextHandler context; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - server = new Server( 0 ); + server = new Server(0); - context = new ServletContextHandler( ServletContextHandler.SESSIONS ); + context = new ServletContextHandler(ServletContextHandler.SESSIONS); resourceHandler = new ResourceHandler(); - context.setHandler( resourceHandler ); - server.setHandler( context ); + context.setHandler(resourceHandler); + server.setHandler(context); } - protected Wagon getWagon() - throws Exception - { - return (Wagon) lookup( HttpWagon.ROLE ); + protected Wagon getWagon() throws Exception { + return (Wagon) lookup(HttpWagon.ROLE); } - protected void startServer() - throws Exception - { + protected void startServer() throws Exception { server.start(); } - protected void stopServer() - throws Exception - { + protected void stopServer() throws Exception { server.stop(); } - - protected final int getPort() - { + + protected final int getPort() { return ((ServerConnector) server.getConnectors()[0]).getLocalPort(); } - } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonPreemptiveTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonPreemptiveTest.java index cd1223270..e911c8af7 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonPreemptiveTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonPreemptiveTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.shared.http.HttpConfiguration; @@ -27,34 +26,27 @@ * @author Michal Maczka * */ -public class HttpWagonPreemptiveTest - extends HttpWagonTest -{ +public class HttpWagonPreemptiveTest extends HttpWagonTest { @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { HttpWagon wagon = (HttpWagon) super.getWagon(); wagon.setHttpConfiguration( - new HttpConfiguration().setAll( new HttpMethodConfiguration().setUsePreemptive( true ) ) ); + new HttpConfiguration().setAll(new HttpMethodConfiguration().setUsePreemptive(true))); return wagon; } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return true; } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return true; } @Override - protected boolean supportProxyPreemptiveAuthentication() - { + protected boolean supportProxyPreemptiveAuthentication() { return true; } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTest.java index 2aeb3a0a4..e900d4598 100755 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import java.util.Properties; @@ -29,45 +28,37 @@ /** * @author Michal Maczka */ -public class HttpWagonTest - extends HttpWagonTestCase -{ - protected String getProtocol() - { +public class HttpWagonTest extends HttpWagonTestCase { + protected String getProtocol() { return "http"; } - protected String getTestRepositoryUrl() - { + protected String getTestRepositoryUrl() { return getProtocol() + "://localhost:" + getTestRepositoryPort(); } - protected void setHttpConfiguration( StreamingWagon wagon, Properties headers, Properties params ) - { + protected void setHttpConfiguration(StreamingWagon wagon, Properties headers, Properties params) { HttpConfiguration config = new HttpConfiguration(); HttpMethodConfiguration methodConfiguration = new HttpMethodConfiguration(); - methodConfiguration.setHeaders( headers ); - methodConfiguration.setParams( params ); - config.setAll( methodConfiguration ); - ( (HttpWagon) wagon ).setHttpConfiguration( config ); + methodConfiguration.setHeaders(headers); + methodConfiguration.setParams(params); + config.setAll(methodConfiguration); + ((HttpWagon) wagon).setHttpConfiguration(config); } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return true; } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return false; } @Override - protected boolean supportProxyPreemptiveAuthentication() - { + protected boolean supportProxyPreemptiveAuthentication() { return true; } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTimeoutTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTimeoutTest.java index 71a8c9ad4..a148421d3 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTimeoutTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpWagonTimeoutTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; + +import java.io.File; +import java.util.Random; import org.apache.maven.wagon.FileTestUtils; import org.apache.maven.wagon.TransferFailedException; @@ -27,164 +29,128 @@ import org.apache.maven.wagon.shared.http.HttpMethodConfiguration; import org.eclipse.jetty.servlet.ServletHolder; -import java.io.File; -import java.util.Random; - /** * User: jdumay Date: 24/01/2008 Time: 17:17:34 */ -public class HttpWagonTimeoutTest - extends HttpWagonHttpServerTestCase -{ - protected void setUp() - throws Exception - { +public class HttpWagonTimeoutTest extends HttpWagonHttpServerTestCase { + protected void setUp() throws Exception { super.setUp(); - ServletHolder servlets = new ServletHolder( new WaitForeverServlet() ); - context.addServlet( servlets, "/*" ); + ServletHolder servlets = new ServletHolder(new WaitForeverServlet()); + context.addServlet(servlets, "/*"); startServer(); } - public void testGetTimeout() - throws Exception - { + public void testGetTimeout() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); - wagon.setReadTimeout( 1000 ); + wagon.setReadTimeout(1000); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + getPort() ); + testRepository.setUrl("http://localhost:" + getPort()); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = FileTestUtils.createUniqueFile( getName(), getName() ); + File destFile = FileTestUtils.createUniqueFile(getName(), getName()); destFile.deleteOnExit(); - wagon.get( "/timeoutfile", destFile ); + wagon.get("/timeoutfile", destFile); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( TransferFailedException.class, thrown.getClass() ); + assertNotNull(thrown); + assertEquals(TransferFailedException.class, thrown.getClass()); } - public void testResourceExits() - throws Exception - { + public void testResourceExits() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); - wagon.setReadTimeout( 1000 ); + wagon.setReadTimeout(1000); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + getPort() ); + testRepository.setUrl("http://localhost:" + getPort()); - wagon.connect( testRepository ); + wagon.connect(testRepository); - wagon.resourceExists( "/timeoutfile" ); + wagon.resourceExists("/timeoutfile"); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( TransferFailedException.class, thrown.getClass() ); + assertNotNull(thrown); + assertEquals(TransferFailedException.class, thrown.getClass()); } - public void testPutTimeout() - throws Exception - { + public void testPutTimeout() throws Exception { Exception thrown = null; - try - { + try { Wagon wagon = getWagon(); - wagon.setReadTimeout( 1000 ); + wagon.setReadTimeout(1000); Repository testRepository = new Repository(); - testRepository.setUrl( "http://localhost:" + getPort() ); + testRepository.setUrl("http://localhost:" + getPort()); - wagon.connect( testRepository ); + wagon.connect(testRepository); - File destFile = File.createTempFile( "Hello", null ); + File destFile = File.createTempFile("Hello", null); destFile.deleteOnExit(); - wagon.put( destFile, "/timeoutfile" ); + wagon.put(destFile, "/timeoutfile"); wagon.disconnect(); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( TransferFailedException.class, thrown.getClass() ); + assertNotNull(thrown); + assertEquals(TransferFailedException.class, thrown.getClass()); } - public void testConnectionTimeout() - throws Exception - { + public void testConnectionTimeout() throws Exception { Exception thrown = null; - try - { + try { HttpWagon wagon = (HttpWagon) getWagon(); wagon.setHttpConfiguration( - new HttpConfiguration().setAll( new HttpMethodConfiguration().setConnectionTimeout( 500 ) ) ); + new HttpConfiguration().setAll(new HttpMethodConfiguration().setConnectionTimeout(500))); Repository testRepository = new Repository(); - Random random = new Random( ); - testRepository.setUrl( "http://localhost:" + random.nextInt( 2048 )); + Random random = new Random(); + testRepository.setUrl("http://localhost:" + random.nextInt(2048)); - wagon.connect( testRepository ); + wagon.connect(testRepository); long start = System.currentTimeMillis(); - wagon.resourceExists( "/foobar" ); + wagon.resourceExists("/foobar"); long end = System.currentTimeMillis(); wagon.disconnect(); // validate we have a default time out 60000 - assertTrue( (end - start) >= 500 && (end - start) < 1000 ); + assertTrue((end - start) >= 500 && (end - start) < 1000); - } - catch ( Exception e ) - { + } catch (Exception e) { thrown = e; - } - finally - { + } finally { stopServer(); } - assertNotNull( thrown ); - assertEquals( TransferFailedException.class, thrown.getClass() ); + assertNotNull(thrown); + assertEquals(TransferFailedException.class, thrown.getClass()); } - } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonPreemptiveTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonPreemptiveTest.java index c4740a2ba..9a5704704 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonPreemptiveTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonPreemptiveTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.shared.http.HttpConfiguration; @@ -26,60 +25,51 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; -public class HttpsWagonPreemptiveTest - extends HttpWagonTest -{ - protected String getProtocol() - { +public class HttpsWagonPreemptiveTest extends HttpWagonTest { + protected String getProtocol() { return "https"; } - protected ServerConnector addConnector( Server server ) - { - System.setProperty( "javax.net.ssl.trustStore", - getTestFile( "src/test/resources/ssl/keystore" ).getAbsolutePath() ); + protected ServerConnector addConnector(Server server) { + System.setProperty( + "javax.net.ssl.trustStore", + getTestFile("src/test/resources/ssl/keystore").getAbsolutePath()); SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setKeyStorePassword( "wagonhttp" ); - sslContextFactory.setKeyManagerPassword( "wagonhttp" ); - sslContextFactory.setTrustStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setTrustStorePassword( "wagonhttp" ); - ServerConnector serverConnector = new ServerConnector( server, sslContextFactory ); - server.addConnector( serverConnector ); + sslContextFactory.setKeyStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setKeyStorePassword("wagonhttp"); + sslContextFactory.setKeyManagerPassword("wagonhttp"); + sslContextFactory.setTrustStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setTrustStorePassword("wagonhttp"); + ServerConnector serverConnector = new ServerConnector(server, sslContextFactory); + server.addConnector(serverConnector); return serverConnector; } @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { HttpWagon wagon = (HttpWagon) super.getWagon(); wagon.setHttpConfiguration( - new HttpConfiguration().setAll( new HttpMethodConfiguration().setUsePreemptive( true ) ) ); + new HttpConfiguration().setAll(new HttpMethodConfiguration().setUsePreemptive(true))); return wagon; } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return true; } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return true; } @Override - protected boolean supportProxyPreemptiveAuthentication() - { + protected boolean supportProxyPreemptiveAuthentication() { return true; } @Override - protected boolean assertOnTransferProgress() - { + protected boolean assertOnTransferProgress() { return false; } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonTest.java index b34733fca..00928f704 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HttpsWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,37 +16,34 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; -public class HttpsWagonTest - extends HttpWagonTest -{ - protected String getProtocol() - { +public class HttpsWagonTest extends HttpWagonTest { + protected String getProtocol() { return "https"; } - protected boolean assertOnTransferProgress() - { + protected boolean assertOnTransferProgress() { return false; } - protected ServerConnector addConnector( Server server ) - { - System.setProperty( "javax.net.ssl.trustStore", - getTestFile( "src/test/resources/ssl/keystore" ).getAbsolutePath() ); + protected ServerConnector addConnector(Server server) { + System.setProperty( + "javax.net.ssl.trustStore", + getTestFile("src/test/resources/ssl/keystore").getAbsolutePath()); SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setKeyStorePassword( "wagonhttp" ); - sslContextFactory.setKeyManagerPassword( "wagonhttp" ); - sslContextFactory.setTrustStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setTrustStorePassword( "wagonhttp" ); - ServerConnector serverConnector = new ServerConnector( server, sslContextFactory ); - server.addConnector( serverConnector ); + sslContextFactory.setKeyStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setKeyStorePassword("wagonhttp"); + sslContextFactory.setKeyManagerPassword("wagonhttp"); + sslContextFactory.setTrustStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setTrustStorePassword("wagonhttp"); + ServerConnector serverConnector = new ServerConnector(server, sslContextFactory); + server.addConnector(serverConnector); return serverConnector; } } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HugeFileDownloadTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HugeFileDownloadTest.java index ce75714bb..7b68d6efb 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HugeFileDownloadTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/HugeFileDownloadTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.observers.Debug; @@ -33,177 +46,138 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.SeekableByteChannel; -import java.nio.file.Files; -import java.nio.file.OpenOption; -import java.nio.file.StandardOpenOption; - /** * @author Olivier Lamy */ -public class HugeFileDownloadTest - extends PlexusTestCase -{ +public class HugeFileDownloadTest extends PlexusTestCase { - private static final Logger LOGGER = LoggerFactory.getLogger( HugeFileDownloadTest.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(HugeFileDownloadTest.class); - private static long HUGE_FILE_SIZE = - Integer.valueOf( Integer.MAX_VALUE ).longValue() + Integer.valueOf( Integer.MAX_VALUE ).longValue(); + private static long HUGE_FILE_SIZE = Integer.valueOf(Integer.MAX_VALUE).longValue() + + Integer.valueOf(Integer.MAX_VALUE).longValue(); private Server server; private ServerConnector connector; - public void testDownloadHugeFileWithContentLength() - throws Exception - { - final File hugeFile = new File( getBasedir(), "target/hugefile.txt" ); - if ( !hugeFile.exists() || hugeFile.length() < HUGE_FILE_SIZE ) - { - makeHugeFile( hugeFile ); + public void testDownloadHugeFileWithContentLength() throws Exception { + final File hugeFile = new File(getBasedir(), "target/hugefile.txt"); + if (!hugeFile.exists() || hugeFile.length() < HUGE_FILE_SIZE) { + makeHugeFile(hugeFile); } - server = new Server( ); - connector = new ServerConnector( server, new HttpConnectionFactory( new HttpConfiguration() ) ); - server.addConnector( connector ); + server = new Server(); + connector = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration())); + server.addConnector(connector); - ServletContextHandler root = new ServletContextHandler( ServletContextHandler.SESSIONS ); - root.setResourceBase( new File( getBasedir(), "target" ).getAbsolutePath() ); - ServletHolder servletHolder = new ServletHolder( new HttpServlet() - { + ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS); + root.setResourceBase(new File(getBasedir(), "target").getAbsolutePath()); + ServletHolder servletHolder = new ServletHolder(new HttpServlet() { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) - throws ServletException, IOException - { - FileInputStream fis = new FileInputStream( hugeFile ); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + FileInputStream fis = new FileInputStream(hugeFile); - resp.addHeader( "Content-Length", String.valueOf( hugeFile.length() ) ); - IOUtil.copy( fis, resp.getOutputStream() ); + resp.addHeader("Content-Length", String.valueOf(hugeFile.length())); + IOUtil.copy(fis, resp.getOutputStream()); fis.close(); } - } ); - root.addServlet( servletHolder, "/*" ); - server.setHandler( root ); + }); + root.addServlet(servletHolder, "/*"); + server.setHandler(root); server.start(); File dest = null; - try - { + try { Wagon wagon = getWagon(); - wagon.connect( new Repository( "id", "http://localhost:" + connector.getLocalPort() ) ); + wagon.connect(new Repository("id", "http://localhost:" + connector.getLocalPort())); - dest = File.createTempFile( "huge", "txt" ); + dest = File.createTempFile("huge", "txt"); - LOGGER.info( "Fetching 'hugefile.txt' with content length" ); - wagon.get( "hugefile.txt", dest ); + LOGGER.info("Fetching 'hugefile.txt' with content length"); + wagon.get("hugefile.txt", dest); - assertTrue( dest.length() >= HUGE_FILE_SIZE ); - LOGGER.info( "The file was successfully fetched" ); + assertTrue(dest.length() >= HUGE_FILE_SIZE); + LOGGER.info("The file was successfully fetched"); wagon.disconnect(); - } - finally - { + } finally { server.stop(); dest.delete(); hugeFile.delete(); } - } - public void testDownloadHugeFileWithChunked() - throws Exception - { - final File hugeFile = new File( getBasedir(), "target/hugefile.txt" ); - if ( !hugeFile.exists() || hugeFile.length() < HUGE_FILE_SIZE ) - { - makeHugeFile( hugeFile ); + public void testDownloadHugeFileWithChunked() throws Exception { + final File hugeFile = new File(getBasedir(), "target/hugefile.txt"); + if (!hugeFile.exists() || hugeFile.length() < HUGE_FILE_SIZE) { + makeHugeFile(hugeFile); } - server = new Server( ); - connector = new ServerConnector( server, new HttpConnectionFactory( new HttpConfiguration() ) ); - server.addConnector( connector ); + server = new Server(); + connector = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration())); + server.addConnector(connector); - ServletContextHandler root = new ServletContextHandler( ServletContextHandler.SESSIONS ); - root.setResourceBase( new File( getBasedir(), "target" ).getAbsolutePath() ); - ServletHolder servletHolder = new ServletHolder( new HttpServlet() - { + ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS); + root.setResourceBase(new File(getBasedir(), "target").getAbsolutePath()); + ServletHolder servletHolder = new ServletHolder(new HttpServlet() { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) - throws ServletException, IOException - { - FileInputStream fis = new FileInputStream( hugeFile ); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + FileInputStream fis = new FileInputStream(hugeFile); - IOUtil.copy( fis, resp.getOutputStream() ); + IOUtil.copy(fis, resp.getOutputStream()); fis.close(); } - } ); - root.addServlet( servletHolder, "/*" ); - server.setHandler( root ); + }); + root.addServlet(servletHolder, "/*"); + server.setHandler(root); server.start(); File dest = null; - try - { + try { Wagon wagon = getWagon(); - wagon.connect( new Repository( "id", "http://localhost:" + connector.getLocalPort() ) ); + wagon.connect(new Repository("id", "http://localhost:" + connector.getLocalPort())); - dest = File.createTempFile( "huge", "txt" ); + dest = File.createTempFile("huge", "txt"); - LOGGER.info( "Fetching 'hugefile.txt' in chunks" ); - wagon.get( "hugefile.txt", dest ); + LOGGER.info("Fetching 'hugefile.txt' in chunks"); + wagon.get("hugefile.txt", dest); - assertTrue( dest.length() >= HUGE_FILE_SIZE ); - LOGGER.info( "The file was successfully fetched" ); + assertTrue(dest.length() >= HUGE_FILE_SIZE); + LOGGER.info("The file was successfully fetched"); wagon.disconnect(); - } - finally - { + } finally { server.stop(); dest.delete(); hugeFile.delete(); } - } - protected Wagon getWagon() - throws Exception - { - Wagon wagon = (Wagon) lookup( Wagon.ROLE, "http" ); + protected Wagon getWagon() throws Exception { + Wagon wagon = (Wagon) lookup(Wagon.ROLE, "http"); Debug debug = new Debug(); - wagon.addSessionListener( debug ); + wagon.addSessionListener(debug); return wagon; } - private void makeHugeFile( File hugeFile ) - throws Exception - { - LOGGER.info( "Creating test file" ); - final ByteBuffer buf = ByteBuffer.allocate( 4 ).putInt( 2 ); + private void makeHugeFile(File hugeFile) throws Exception { + LOGGER.info("Creating test file"); + final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2); buf.rewind(); - final OpenOption[] options = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW, - StandardOpenOption.SPARSE }; + final OpenOption[] options = {StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW, StandardOpenOption.SPARSE + }; - try ( final SeekableByteChannel channel = Files.newByteChannel( hugeFile.toPath(), options ) ) - { - channel.position( HUGE_FILE_SIZE ); - channel.write( buf ); + try (final SeekableByteChannel channel = Files.newByteChannel(hugeFile.toPath(), options)) { + channel.position(HUGE_FILE_SIZE); + channel.write(buf); } - LOGGER.info( "Test file created" ); + LOGGER.info("Test file created"); } - } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java index dc56e314b..2de4cc338 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/TckTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import org.apache.maven.wagon.tck.http.GetWagonTests; import org.apache.maven.wagon.tck.http.HttpsGetWagonTests; @@ -27,9 +26,8 @@ /** * This test will run the TCK suite on wagon-http-lightweight */ -@RunWith( Suite.class ) -@Suite.SuiteClasses( { GetWagonTests.class, HttpsGetWagonTests.class } ) -public class TckTest -{ +@RunWith(Suite.class) +@Suite.SuiteClasses({GetWagonTests.class, HttpsGetWagonTests.class}) +public class TckTest { // no op } diff --git a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/WaitForeverServlet.java b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/WaitForeverServlet.java index 290047827..e00595769 100644 --- a/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/WaitForeverServlet.java +++ b/wagon-providers/wagon-http/src/test/java/org/apache/maven/wagon/providers/http/WaitForeverServlet.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.http; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; import org.slf4j.Logger; @@ -33,23 +33,16 @@ * Date: 24/01/2008 * Time: 17:25:27 */ -public class WaitForeverServlet - extends HttpServlet -{ +public class WaitForeverServlet extends HttpServlet { - private Logger logger = LoggerFactory.getLogger( WaitForeverServlet.class ); + private Logger logger = LoggerFactory.getLogger(WaitForeverServlet.class); - public void service( HttpServletRequest request, HttpServletResponse response ) - throws ServletException, IOException - { - logger.info( "Calling WaitForeverServlet" ); - try - { - Thread.sleep( 2000 ); - } - catch ( InterruptedException e ) - { - //eat + public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + logger.info("Calling WaitForeverServlet"); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + // eat } } } diff --git a/wagon-providers/wagon-scm/src/main/java/org/apache/maven/wagon/providers/scm/ScmWagon.java b/wagon-providers/wagon-scm/src/main/java/org/apache/maven/wagon/providers/scm/ScmWagon.java index b2fd43e88..5883ac05f 100644 --- a/wagon-providers/wagon-scm/src/main/java/org/apache/maven/wagon/providers/scm/ScmWagon.java +++ b/wagon-providers/wagon-scm/src/main/java/org/apache/maven/wagon/providers/scm/ScmWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import java.io.File; import java.io.IOException; @@ -73,9 +72,7 @@ * * @plexus.component role="org.apache.maven.wagon.Wagon" role-hint="scm" instantiation-strategy="per-lookup" */ -public class ScmWagon - extends AbstractWagon -{ +public class ScmWagon extends AbstractWagon { /** * @plexus.requirement */ @@ -109,8 +106,7 @@ public class ScmWagon * * @return the {@link ScmManager} */ - public ScmManager getScmManager() - { + public ScmManager getScmManager() { return scmManager; } @@ -119,8 +115,7 @@ public ScmManager getScmManager() * * @param scmManager */ - public void setScmManager( ScmManager scmManager ) - { + public void setScmManager(ScmManager scmManager) { this.scmManager = scmManager; } @@ -129,8 +124,7 @@ public void setScmManager( ScmManager scmManager ) * * @return the scmVersion */ - public String getScmVersion() - { + public String getScmVersion() { return scmVersion; } @@ -139,8 +133,7 @@ public String getScmVersion() * * @param scmVersion the scmVersion to set */ - public void setScmVersion( String scmVersion ) - { + public void setScmVersion(String scmVersion) { this.scmVersion = scmVersion; } @@ -149,8 +142,7 @@ public void setScmVersion( String scmVersion ) * * @return the scmVersionType */ - public String getScmVersionType() - { + public String getScmVersionType() { return scmVersionType; } @@ -159,8 +151,7 @@ public String getScmVersionType() * * @param scmVersionType the scmVersionType to set */ - public void setScmVersionType( String scmVersionType ) - { + public void setScmVersionType(String scmVersionType) { this.scmVersionType = scmVersionType; } @@ -169,8 +160,7 @@ public void setScmVersionType( String scmVersionType ) * * @return directory */ - public File getCheckoutDirectory() - { + public File getCheckoutDirectory() { return checkoutDirectory; } @@ -179,8 +169,7 @@ public File getCheckoutDirectory() * * @param checkoutDirectory */ - public void setCheckoutDirectory( File checkoutDirectory ) - { + public void setCheckoutDirectory(File checkoutDirectory) { this.checkoutDirectory = checkoutDirectory; } @@ -191,68 +180,53 @@ public void setCheckoutDirectory( File checkoutDirectory ) * @return the {@link ScmProvider} that will handle provided SCM type * @throws NoSuchScmProviderException if there is no {@link ScmProvider} able to handle that SCM type */ - public ScmProvider getScmProvider( String scmType ) - throws NoSuchScmProviderException - { - return getScmManager().getProviderByType( scmType ); + public ScmProvider getScmProvider(String scmType) throws NoSuchScmProviderException { + return getScmManager().getProviderByType(scmType); } /** * This will cleanup the checkout directory */ - public void openConnectionInternal() - throws ConnectionException - { - if ( checkoutDirectory == null ) - { + public void openConnectionInternal() throws ConnectionException { + if (checkoutDirectory == null) { checkoutDirectory = createCheckoutDirectory(); } - if ( checkoutDirectory.exists() ) - { + if (checkoutDirectory.exists()) { removeCheckoutDirectory(); } checkoutDirectory.mkdirs(); } - private File createCheckoutDirectory() - { + private File createCheckoutDirectory() { File checkoutDirectory; - DecimalFormat fmt = new DecimalFormat( "#####" ); + DecimalFormat fmt = new DecimalFormat("#####"); - Random rand = new Random( System.currentTimeMillis() + Runtime.getRuntime().freeMemory() ); + Random rand = + new Random(System.currentTimeMillis() + Runtime.getRuntime().freeMemory()); - synchronized ( rand ) - { - do - { - checkoutDirectory = new File( System.getProperty( "java.io.tmpdir" ), - "wagon-scm" + fmt.format( Math.abs( rand.nextInt() ) ) + ".checkout" ); - } - while ( checkoutDirectory.exists() ); + synchronized (rand) { + do { + checkoutDirectory = new File( + System.getProperty("java.io.tmpdir"), + "wagon-scm" + fmt.format(Math.abs(rand.nextInt())) + ".checkout"); + } while (checkoutDirectory.exists()); } return checkoutDirectory; } - - private void removeCheckoutDirectory() - throws ConnectionException - { - if ( checkoutDirectory == null ) - { + private void removeCheckoutDirectory() throws ConnectionException { + if (checkoutDirectory == null) { return; // Silently return. } - try - { + try { deleteCheckoutDirectory(); - } - catch ( IOException e ) - { - throw new ConnectionException( "Unable to cleanup checkout directory", e ); + } catch (IOException e) { + throw new ConnectionException("Unable to cleanup checkout directory", e); } } @@ -262,34 +236,24 @@ private void removeCheckoutDirectory() *

If scmVersion is supplied, scmVersionType must also be supplied to * take effect.

*/ - private ScmVersion makeScmVersion() - { - if ( StringUtils.isBlank( scmVersion ) ) - { + private ScmVersion makeScmVersion() { + if (StringUtils.isBlank(scmVersion)) { return null; } - if ( scmVersion.length() > 0 ) - { - if ( "revision".equals( scmVersionType ) ) - { - return new ScmRevision( scmVersion ); - } - else if ( "tag".equals( scmVersionType ) ) - { - return new ScmTag( scmVersion ); - } - else if ( "branch".equals( scmVersionType ) ) - { - return new ScmBranch( scmVersion ); + if (scmVersion.length() > 0) { + if ("revision".equals(scmVersionType)) { + return new ScmRevision(scmVersion); + } else if ("tag".equals(scmVersionType)) { + return new ScmTag(scmVersion); + } else if ("branch".equals(scmVersionType)) { + return new ScmBranch(scmVersion); } } return null; } - private ScmRepository getScmRepository( String url ) - throws ScmRepositoryException, NoSuchScmProviderException - { + private ScmRepository getScmRepository(String url) throws ScmRepositoryException, NoSuchScmProviderException { String username = null; String password = null; @@ -298,8 +262,7 @@ private ScmRepository getScmRepository( String url ) String passphrase = null; - if ( authenticationInfo != null ) - { + if (authenticationInfo != null) { username = authenticationInfo.getUserName(); password = authenticationInfo.getPassword(); @@ -309,46 +272,39 @@ private ScmRepository getScmRepository( String url ) passphrase = authenticationInfo.getPassphrase(); } - ScmRepository scmRepository = getScmManager().makeScmRepository( url ); + ScmRepository scmRepository = getScmManager().makeScmRepository(url); ScmProviderRepository providerRepository = scmRepository.getProviderRepository(); - if ( username != null && !username.isEmpty() ) - { - providerRepository.setUser( username ); + if (username != null && !username.isEmpty()) { + providerRepository.setUser(username); } - if ( password != null && !password.isEmpty() ) - { - providerRepository.setPassword( password ); + if (password != null && !password.isEmpty()) { + providerRepository.setPassword(password); } - if ( providerRepository instanceof ScmProviderRepositoryWithHost ) - { + if (providerRepository instanceof ScmProviderRepositoryWithHost) { ScmProviderRepositoryWithHost providerRepo = (ScmProviderRepositoryWithHost) providerRepository; - if ( privateKey != null && !privateKey.isEmpty() ) - { - providerRepo.setPrivateKey( privateKey ); + if (privateKey != null && !privateKey.isEmpty()) { + providerRepo.setPrivateKey(privateKey); } - if ( passphrase != null && !passphrase.isEmpty() ) - { - providerRepo.setPassphrase( passphrase ); + if (passphrase != null && !passphrase.isEmpty()) { + providerRepo.setPassphrase(passphrase); } } return scmRepository; } - public void put( File source, String targetName ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( source.isDirectory() ) - { - throw new IllegalArgumentException( "Source is a directory: " + source ); + public void put(File source, String targetName) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (source.isDirectory()) { + throw new IllegalArgumentException("Source is a directory: " + source); } - putInternal( source, targetName ); + putInternal(source, targetName); } /** @@ -358,97 +314,80 @@ public void put( File source, String targetName ) * @param targetName * @throws TransferFailedException */ - private void putInternal( File source, String targetName ) - throws TransferFailedException - { - Resource target = new Resource( targetName ); + private void putInternal(File source, String targetName) throws TransferFailedException { + Resource target = new Resource(targetName); - firePutInitiated( target, source ); + firePutInitiated(target, source); - try - { - ScmRepository scmRepository = getScmRepository( getRepository().getUrl() ); + try { + ScmRepository scmRepository = getScmRepository(getRepository().getUrl()); - target.setContentLength( source.length() ); - target.setLastModified( source.lastModified() ); + target.setContentLength(source.length()); + target.setLastModified(source.lastModified()); - firePutStarted( target, source ); + firePutStarted(target, source); String msg = "Wagon: Adding " + source.getName() + " to repository"; - ScmProvider scmProvider = getScmProvider( scmRepository.getProvider() ); + ScmProvider scmProvider = getScmProvider(scmRepository.getProvider()); boolean isDirectory = source.isDirectory(); - String checkoutTargetName = isDirectory ? targetName : getDirname( targetName ); + String checkoutTargetName = isDirectory ? targetName : getDirname(targetName); boolean recursive = false; - if ( isDirectory ) - { - for ( File f : source.listFiles() ) - { - if ( f.isDirectory() ) - { + if (isDirectory) { + for (File f : source.listFiles()) { + if (f.isDirectory()) { recursive = true; break; } } } - String relPath = ensureDirs( scmProvider, scmRepository, checkoutTargetName, target, recursive ); + String relPath = ensureDirs(scmProvider, scmRepository, checkoutTargetName, target, recursive); - File newCheckoutDirectory = new File( checkoutDirectory, relPath ); + File newCheckoutDirectory = new File(checkoutDirectory, relPath); - File scmFile = new File( newCheckoutDirectory, isDirectory ? "" : FileUtils.removePath( targetName, '/' ) ); + File scmFile = new File(newCheckoutDirectory, isDirectory ? "" : FileUtils.removePath(targetName, '/')); boolean fileAlreadyInScm = scmFile.exists(); - if ( !scmFile.equals( source ) ) - { - if ( isDirectory ) - { - FileUtils.copyDirectoryStructure( source, scmFile ); - } - else - { - FileUtils.copyFile( source, scmFile ); + if (!scmFile.equals(source)) { + if (isDirectory) { + FileUtils.copyDirectoryStructure(source, scmFile); + } else { + FileUtils.copyFile(source, scmFile); } } - if ( !fileAlreadyInScm || scmFile.isDirectory() ) - { - int addedFiles = addFiles( scmProvider, scmRepository, newCheckoutDirectory, - isDirectory ? "" : scmFile.getName() ); + if (!fileAlreadyInScm || scmFile.isDirectory()) { + int addedFiles = addFiles( + scmProvider, scmRepository, newCheckoutDirectory, isDirectory ? "" : scmFile.getName()); - if ( !fileAlreadyInScm && addedFiles == 0 ) - { - throw new ScmException( - "Unable to add file to SCM: " + scmFile + "; see error messages above for more information" ); + if (!fileAlreadyInScm && addedFiles == 0) { + throw new ScmException("Unable to add file to SCM: " + scmFile + + "; see error messages above for more information"); } } ScmResult result = - scmProvider.checkIn( scmRepository, new ScmFileSet( checkoutDirectory ), makeScmVersion(), msg ); + scmProvider.checkIn(scmRepository, new ScmFileSet(checkoutDirectory), makeScmVersion(), msg); - checkScmResult( result ); - } - catch ( ScmException e ) - { - fireTransferError( target, e, TransferEvent.REQUEST_PUT ); + checkScmResult(result); + } catch (ScmException e) { + fireTransferError(target, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( "Error interacting with SCM: " + e.getMessage(), e ); - } - catch ( IOException e ) - { - fireTransferError( target, e, TransferEvent.REQUEST_PUT ); + throw new TransferFailedException("Error interacting with SCM: " + e.getMessage(), e); + } catch (IOException e) { + fireTransferError(target, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( "Error interacting with SCM: " + e.getMessage(), e ); + throw new TransferFailedException("Error interacting with SCM: " + e.getMessage(), e); } - if ( source.isFile() ) - { - postProcessListeners( target, source, TransferEvent.REQUEST_PUT ); + if (source.isFile()) { + postProcessListeners(target, source, TransferEvent.REQUEST_PUT); } - firePutCompleted( target, source ); + firePutCompleted(target, source); } /** @@ -462,12 +401,14 @@ private void putInternal( File source, String targetName ) * @throws TransferFailedException * @throws IOException */ - private String ensureDirs( ScmProvider scmProvider, ScmRepository scmRepository, String targetName, - Resource resource, boolean recursiveArg ) - throws TransferFailedException, IOException - { - if ( checkoutDirectory == null ) - { + private String ensureDirs( + ScmProvider scmProvider, + ScmRepository scmRepository, + String targetName, + Resource resource, + boolean recursiveArg) + throws TransferFailedException, IOException { + if (checkoutDirectory == null) { checkoutDirectory = createCheckoutDirectory(); } @@ -480,82 +421,67 @@ private String ensureDirs( ScmProvider scmProvider, ScmRepository scmRepository, boolean recursive = recursiveArg; - for ( ;; ) - { - try - { - ScmResult res = tryPartialCheckout( target, recursive ); - if ( !res.isSuccess() ) - { - throw new ScmException( "command failed: " + res.getCommandOutput().trim() ); + for (; ; ) { + try { + ScmResult res = tryPartialCheckout(target, recursive); + if (!res.isSuccess()) { + throw new ScmException( + "command failed: " + res.getCommandOutput().trim()); } break; - } - catch ( ScmException e ) - { + } catch (ScmException e) { recursive = false; - if ( partCOSubdir.length() == 0 ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + if (partCOSubdir.length() == 0) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); - throw new TransferFailedException( "Error checking out: " + e.getMessage(), e ); + throw new TransferFailedException("Error checking out: " + e.getMessage(), e); } - target = getDirname( target ); + target = getDirname(target); } } // now create the subdirs in target, if it's a parent of targetName String res = - partCOSubdir.length() >= targetName.length() ? "" : targetName.substring( partCOSubdir.length() ) + '/'; + partCOSubdir.length() >= targetName.length() ? "" : targetName.substring(partCOSubdir.length()) + '/'; ArrayList createdDirs = new ArrayList<>(); - File deepDir = new File( checkoutDirectory, res ); + File deepDir = new File(checkoutDirectory, res); boolean added = false; - try - { - mkdirsThrow( deepDir, createdDirs ); - if ( createdDirs.size() != 0 ) - { - File topNewDir = createdDirs.get( 0 ); - String relTopNewDir = - topNewDir.getPath().substring( checkoutDirectory.getPath().length() + 1 ).replace( '\\', '/' ); - - addFiles( scmProvider, scmRepository, checkoutDirectory, relTopNewDir ); + try { + mkdirsThrow(deepDir, createdDirs); + if (createdDirs.size() != 0) { + File topNewDir = createdDirs.get(0); + String relTopNewDir = topNewDir + .getPath() + .substring(checkoutDirectory.getPath().length() + 1) + .replace('\\', '/'); + + addFiles(scmProvider, scmRepository, checkoutDirectory, relTopNewDir); added = true; } - } - catch ( ScmException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + } catch (ScmException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( "Failed to add directory " + createdDirs.get( 0 ) + " to working copy", - e ); - } - finally - { - if ( !added && createdDirs.size() != 0 ) - { - FileUtils.deleteDirectory( createdDirs.get( 0 ) ); + throw new TransferFailedException("Failed to add directory " + createdDirs.get(0) + " to working copy", e); + } finally { + if (!added && createdDirs.size() != 0) { + FileUtils.deleteDirectory(createdDirs.get(0)); } } return res; } - private static void mkdirsThrow( File f, List createdDirs ) - throws IOException - { - if ( !f.isDirectory() ) - { + private static void mkdirsThrow(File f, List createdDirs) throws IOException { + if (!f.isDirectory()) { File parent = f.getParentFile(); - mkdirsThrow( parent, createdDirs ); - if ( !f.mkdir() ) - { - throw new IOException( "Failed to create directory " + f.getAbsolutePath() ); + mkdirsThrow(parent, createdDirs); + if (!f.mkdir()) { + throw new IOException("Failed to create directory " + f.getAbsolutePath()); } - createdDirs.add( f ); + createdDirs.add(f); } } @@ -571,28 +497,23 @@ private static void mkdirsThrow( File f, List createdDirs ) * @return the number of files added. * @throws ScmException */ - private int addFiles( ScmProvider scmProvider, ScmRepository scmRepository, File basedir, String scmFilePath ) - throws ScmException - { + private int addFiles(ScmProvider scmProvider, ScmRepository scmRepository, File basedir, String scmFilePath) + throws ScmException { int addedFiles = 0; - File scmFile = new File( basedir, scmFilePath ); + File scmFile = new File(basedir, scmFilePath); - if ( scmFilePath.length() != 0 ) - { + if (scmFilePath.length() != 0) { AddScmResult result = - scmProvider.add( scmRepository, new ScmFileSet( basedir, new File( scmFilePath ) ), mkBinaryFlag() ); + scmProvider.add(scmRepository, new ScmFileSet(basedir, new File(scmFilePath)), mkBinaryFlag()); /* * TODO dirty fix to work around files with property svn:eol-style=native if a file has that property, first * time file is added it fails, second time it succeeds the solution is check if the scm provider is svn and * unset that property when the SCM API allows it */ - if ( !result.isSuccess() ) - { - result = - scmProvider.add( scmRepository, new ScmFileSet( basedir, new File( scmFilePath ) ), - mkBinaryFlag() ); + if (!result.isSuccess()) { + result = scmProvider.add(scmRepository, new ScmFileSet(basedir, new File(scmFilePath)), mkBinaryFlag()); } addedFiles = result.getAddedFiles().size(); @@ -600,15 +521,14 @@ private int addFiles( ScmProvider scmProvider, ScmRepository scmRepository, File String reservedScmFile = scmProvider.getScmSpecificFilename(); - if ( scmFile.isDirectory() ) - { - for ( File file : scmFile.listFiles() ) - { - if ( reservedScmFile != null && !reservedScmFile.equals( file.getName() ) ) - { - addedFiles += addFiles( scmProvider, scmRepository, basedir, - ( scmFilePath.length() == 0 ? "" : scmFilePath + "/" ) - + file.getName() ); + if (scmFile.isDirectory()) { + for (File file : scmFile.listFiles()) { + if (reservedScmFile != null && !reservedScmFile.equals(file.getName())) { + addedFiles += addFiles( + scmProvider, + scmRepository, + basedir, + (scmFilePath.length() == 0 ? "" : scmFilePath + "/") + file.getName()); } } } @@ -616,56 +536,49 @@ private int addFiles( ScmProvider scmProvider, ScmRepository scmRepository, File return addedFiles; } - private CheckOutScmResult checkOut( ScmProvider scmProvider, ScmRepository scmRepository, ScmFileSet fileSet, - boolean recursive ) - throws ScmException - { + private CheckOutScmResult checkOut( + ScmProvider scmProvider, ScmRepository scmRepository, ScmFileSet fileSet, boolean recursive) + throws ScmException { ScmVersion ver = makeScmVersion(); CommandParameters parameters = mkBinaryFlag(); // TODO: AbstractScmProvider 6f7dd0c ignores checkOut() parameter "version" - parameters.setScmVersion( CommandParameter.SCM_VERSION, ver ); - parameters.setString( CommandParameter.RECURSIVE, Boolean.toString( recursive ) ); - parameters.setString( CommandParameter.SHALLOW, Boolean.toString( true ) ); + parameters.setScmVersion(CommandParameter.SCM_VERSION, ver); + parameters.setString(CommandParameter.RECURSIVE, Boolean.toString(recursive)); + parameters.setString(CommandParameter.SHALLOW, Boolean.toString(true)); - return scmProvider.checkOut( scmRepository, fileSet, ver, parameters ); + return scmProvider.checkOut(scmRepository, fileSet, ver, parameters); } - private CommandParameters mkBinaryFlag() throws ScmException - { + private CommandParameters mkBinaryFlag() throws ScmException { CommandParameters parameters = new CommandParameters(); - parameters.setString( CommandParameter.BINARY, Boolean.toString( true ) ); + parameters.setString(CommandParameter.BINARY, Boolean.toString(true)); return parameters; } /** * @return true */ - public boolean supportsDirectoryCopy() - { + public boolean supportsDirectoryCopy() { return true; } - private boolean supportsPartialCheckout( ScmProvider scmProvider ) - { + private boolean supportsPartialCheckout(ScmProvider scmProvider) { String scmType = scmProvider.getScmType(); - return "svn".equals( scmType ) || "cvs".equals( scmType ); + return "svn".equals(scmType) || "cvs".equals(scmType); } - private boolean isAlwaysRecursive( ScmProvider scmProvider ) - { + private boolean isAlwaysRecursive(ScmProvider scmProvider) { String scmType = scmProvider.getScmType(); - return "git".equals( scmType ) || "cvs".equals( scmType ); + return "git".equals(scmType) || "cvs".equals(scmType); } - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( !sourceDirectory.isDirectory() ) - { - throw new IllegalArgumentException( "Source is not a directory: " + sourceDirectory ); + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (!sourceDirectory.isDirectory()) { + throw new IllegalArgumentException("Source is not a directory: " + sourceDirectory); } - putInternal( sourceDirectory, destinationDirectory ); + putInternal(sourceDirectory, destinationDirectory); } /** @@ -675,21 +588,14 @@ public void putDirectory( File sourceDirectory, String destinationDirectory ) * @throws TransferFailedException if result was not a successful operation * @throws ScmException */ - private void checkScmResult( ScmResult result ) - throws ScmException - { - if ( !result.isSuccess() ) - { - throw new ScmException( - "Unable to commit file. " + result.getProviderMessage() + " " + ( result.getCommandOutput() == null - ? "" - : result.getCommandOutput() ) ); + private void checkScmResult(ScmResult result) throws ScmException { + if (!result.isSuccess()) { + throw new ScmException("Unable to commit file. " + result.getProviderMessage() + " " + + (result.getCommandOutput() == null ? "" : result.getCommandOutput())); } } - public void closeConnection() - throws ConnectionException - { + public void closeConnection() throws ConnectionException { removeCheckoutDirectory(); } @@ -698,32 +604,29 @@ public void closeConnection() * * @throws UnsupportedOperationException always */ - public boolean getIfNewer( String resourceName, File destination, long timestamp ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - throw new UnsupportedOperationException( "Not currently supported: getIfNewer" ); + public boolean getIfNewer(String resourceName, File destination, long timestamp) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + throw new UnsupportedOperationException("Not currently supported: getIfNewer"); } - public void get( String resourceName, File destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( resourceName ); + public void get(String resourceName, File destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(resourceName); - fireGetInitiated( resource, destination ); + fireGetInitiated(resource, destination); - fireGetStarted( resource, destination ); + fireGetStarted(resource, destination); - try - { - String subdir = getDirname( resourceName ); - ScmResult res = tryPartialCheckout( subdir, false ); - if ( !res.isSuccess() && ( partCOSubdir.length() == 0 || res instanceof UpdateScmResult ) ) - { + try { + String subdir = getDirname(resourceName); + ScmResult res = tryPartialCheckout(subdir, false); + if (!res.isSuccess() && (partCOSubdir.length() == 0 || res instanceof UpdateScmResult)) { // inability to checkout SVN or CVS subdir is not fatal. We just assume it doesn't exist // inability to update existing subdir or checkout root is fatal - throw new ScmException( "command failed: " + res.getCommandOutput().trim() ); + throw new ScmException( + "command failed: " + res.getCommandOutput().trim()); } - resourceName = resourceName.substring( partCOSubdir.length() ); + resourceName = resourceName.substring(partCOSubdir.length()); // TODO: limitations: // - destination filename must match that in the repository - should allow the "-d" CVS equiv to be passed @@ -732,91 +635,74 @@ public void get( String resourceName, File destination ) // - need to make it non-recursive to save time // - exists() check doesn't test if it is in SCM already - File scmFile = new File( checkoutDirectory, resourceName ); + File scmFile = new File(checkoutDirectory, resourceName); - if ( !scmFile.exists() ) - { - throw new ResourceDoesNotExistException( "Unable to find resource " + destination + " after checkout" ); + if (!scmFile.exists()) { + throw new ResourceDoesNotExistException("Unable to find resource " + destination + " after checkout"); } - if ( !scmFile.equals( destination ) ) - { - FileUtils.copyFile( scmFile, destination ); + if (!scmFile.equals(destination)) { + FileUtils.copyFile(scmFile, destination); } - } - catch ( ScmException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + } catch (ScmException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); - throw new TransferFailedException( "Error getting file from SCM", e ); - } - catch ( IOException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + throw new TransferFailedException("Error getting file from SCM", e); + } catch (IOException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); - throw new TransferFailedException( "Error getting file from SCM", e ); + throw new TransferFailedException("Error getting file from SCM", e); } - postProcessListeners( resource, destination, TransferEvent.REQUEST_GET ); + postProcessListeners(resource, destination, TransferEvent.REQUEST_GET); - fireGetCompleted( resource, destination ); + fireGetCompleted(resource, destination); } - private ScmResult tryPartialCheckout( String subdir, boolean recursiveArg ) - throws ScmException, IOException - { + private ScmResult tryPartialCheckout(String subdir, boolean recursiveArg) throws ScmException, IOException { String url = getRepository().getUrl(); String desiredPartCOSubdir = ""; - ScmRepository scmRepository = getScmRepository( url ); - ScmProvider scmProvider = getScmProvider( scmRepository.getProvider() ); - if ( subdir.length() != 0 && supportsPartialCheckout( scmProvider ) ) - { - url += ( url.endsWith( "/" ) ? "" : "/" ) + subdir; + ScmRepository scmRepository = getScmRepository(url); + ScmProvider scmProvider = getScmProvider(scmRepository.getProvider()); + if (subdir.length() != 0 && supportsPartialCheckout(scmProvider)) { + url += (url.endsWith("/") ? "" : "/") + subdir; desiredPartCOSubdir = subdir + "/"; - scmRepository = getScmRepository( url ); + scmRepository = getScmRepository(url); } - boolean recursive = recursiveArg | isAlwaysRecursive( scmProvider ); + boolean recursive = recursiveArg | isAlwaysRecursive(scmProvider); - if ( !desiredPartCOSubdir.equals( partCOSubdir ) ) - { + if (!desiredPartCOSubdir.equals(partCOSubdir)) { deleteCheckoutDirectory(); partCOSubdir = desiredPartCOSubdir; } - if ( recursive && !haveRecursiveCO ) - { + if (recursive && !haveRecursiveCO) { deleteCheckoutDirectory(); } ScmResult res; - if ( checkoutDirExists( scmProvider ) ) - { - res = scmProvider.update( scmRepository, new ScmFileSet( checkoutDirectory ), makeScmVersion() ); - } - else - { - res = checkOut( scmProvider, scmRepository, new ScmFileSet( checkoutDirectory ), recursive ); + if (checkoutDirExists(scmProvider)) { + res = scmProvider.update(scmRepository, new ScmFileSet(checkoutDirectory), makeScmVersion()); + } else { + res = checkOut(scmProvider, scmRepository, new ScmFileSet(checkoutDirectory), recursive); haveRecursiveCO = recursive && res.isSuccess(); } return res; } - private void deleteCheckoutDirectory() - throws IOException - { + private void deleteCheckoutDirectory() throws IOException { haveRecursiveCO = false; - FileUtils.deleteDirectory( checkoutDirectory ); + FileUtils.deleteDirectory(checkoutDirectory); } - private boolean checkoutDirExists( ScmProvider scmProvider ) - { + private boolean checkoutDirExists(ScmProvider scmProvider) { String reservedScmFile = scmProvider.getScmSpecificFilename(); - File pathToCheck = reservedScmFile == null ? checkoutDirectory : new File( checkoutDirectory, reservedScmFile ); + File pathToCheck = reservedScmFile == null ? checkoutDirectory : new File(checkoutDirectory, reservedScmFile); return pathToCheck.exists(); } @@ -824,56 +710,43 @@ private boolean checkoutDirExists( ScmProvider scmProvider ) * @return a List<String> with filenames/directories at the resourcepath. * @see org.apache.maven.wagon.AbstractWagon#getFileList(java.lang.String) */ - public List getFileList( String resourcePath ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - try - { - ScmRepository repository = getScmRepository( getRepository().getUrl() ); - - ScmProvider provider = getScmProvider( repository.getProvider() ); - - ListScmResult result = - provider.list( repository, new ScmFileSet( new File( "." ), new File( resourcePath ) ), false, - makeScmVersion() ); - - if ( !result.isSuccess() ) - { - throw new ResourceDoesNotExistException( result.getProviderMessage() ); + public List getFileList(String resourcePath) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + try { + ScmRepository repository = getScmRepository(getRepository().getUrl()); + + ScmProvider provider = getScmProvider(repository.getProvider()); + + ListScmResult result = provider.list( + repository, new ScmFileSet(new File("."), new File(resourcePath)), false, makeScmVersion()); + + if (!result.isSuccess()) { + throw new ResourceDoesNotExistException(result.getProviderMessage()); } List files = new ArrayList<>(); - for ( ScmFile f : result.getFiles() ) - { - files.add( f.getPath() ); + for (ScmFile f : result.getFiles()) { + files.add(f.getPath()); } return files; - } - catch ( ScmException e ) - { - throw new TransferFailedException( "Error getting filelist from SCM", e ); + } catch (ScmException e) { + throw new TransferFailedException("Error getting filelist from SCM", e); } } - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - try - { - getFileList( resourceName ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + try { + getFileList(resourceName); return true; - } - catch ( ResourceDoesNotExistException e ) - { + } catch (ResourceDoesNotExistException e) { return false; } } - private String getDirname( String resourceName ) - { - return FileUtils.getPath( resourceName, '/' ); + private String getDirname(String resourceName) { + return FileUtils.getPath(resourceName, '/'); } } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmCvsWagonTest.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmCvsWagonTest.java index 26d3d6dbd..c59bd86d1 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmCvsWagonTest.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmCvsWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import java.io.File; import java.io.IOException; @@ -26,41 +25,33 @@ /** * Test for ScmWagon using CVS as underlying SCM - * + * * @author Brett Porter * */ -public abstract class AbstractScmCvsWagonTest - extends AbstractScmWagonTest -{ +public abstract class AbstractScmCvsWagonTest extends AbstractScmWagonTest { private String repository; @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - File origRepo = getTestFile( "target/test-classes/test-repo-cvs" ); + File origRepo = getTestFile("target/test-classes/test-repo-cvs"); - File testRepo = getTestFile( "target/test-classes/test-repo-cvs-test" ); + File testRepo = getTestFile("target/test-classes/test-repo-cvs-test"); - FileUtils.deleteDirectory( testRepo ); + FileUtils.deleteDirectory(testRepo); - FileUtils.copyDirectoryStructure( origRepo, testRepo ); + FileUtils.copyDirectoryStructure(origRepo, testRepo); repository = "scm:cvs|local|" + testRepo.getAbsolutePath() + "|repository"; - } - protected String getScmId() - { + protected String getScmId() { return "cvs"; } - protected String getTestRepositoryUrl() - throws IOException - { + protected String getTestRepositoryUrl() throws IOException { return repository; } } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmGitWagonTest.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmGitWagonTest.java index 93f0dfd5e..98d0f3491 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmGitWagonTest.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmGitWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import java.io.File; @@ -26,41 +25,34 @@ /** * Test for ScmWagon using Git as underlying SCM */ -public abstract class AbstractScmGitWagonTest - extends AbstractScmWagonTest -{ +public abstract class AbstractScmGitWagonTest extends AbstractScmWagonTest { private String repository; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); // copy the repo for the test - File origRepo = getTestFile( "target/test-classes/test-repo-git" ); + File origRepo = getTestFile("target/test-classes/test-repo-git"); - File testRepo = getTestFile( "target/test-classes/test-repo-git-test" ); + File testRepo = getTestFile("target/test-classes/test-repo-git-test"); - FileUtils.deleteDirectory( testRepo ); + FileUtils.deleteDirectory(testRepo); - FileUtils.copyDirectoryStructure( origRepo, testRepo ); + FileUtils.copyDirectoryStructure(origRepo, testRepo); repository = "scm:git:" + testRepo.getAbsoluteFile().toPath().toUri().toASCIIString(); } - protected String getScmId() - { + protected String getScmId() { return "git"; } - protected String getTestRepositoryUrl() - { + protected String getTestRepositoryUrl() { return repository; } - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return false; } } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmSvnWagonTest.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmSvnWagonTest.java index b17f09d05..b606bab24 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmSvnWagonTest.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmSvnWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import java.io.File; @@ -29,41 +28,34 @@ * @author Brett Porter * */ -public abstract class AbstractScmSvnWagonTest - extends AbstractScmWagonTest -{ +public abstract class AbstractScmSvnWagonTest extends AbstractScmWagonTest { private String repository; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); // copy the repo for the test - File origRepo = getTestFile( "target/test-classes/test-repo-svn" ); + File origRepo = getTestFile("target/test-classes/test-repo-svn"); - File testRepo = getTestFile( "target/test-classes/test-repo-svn-test" ); + File testRepo = getTestFile("target/test-classes/test-repo-svn-test"); - FileUtils.deleteDirectory( testRepo ); + FileUtils.deleteDirectory(testRepo); - FileUtils.copyDirectoryStructure( origRepo, testRepo ); + FileUtils.copyDirectoryStructure(origRepo, testRepo); repository = "scm:svn:" + testRepo.getAbsoluteFile().toPath().toUri().toASCIIString(); } - protected String getScmId() - { + protected String getScmId() { return "svn"; } - protected String getTestRepositoryUrl() - { + protected String getTestRepositoryUrl() { return repository; } - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return false; } } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmWagonTest.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmWagonTest.java index 9b4d44816..c0d8bd28c 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmWagonTest.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/AbstractScmWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; + +import java.io.File; +import java.io.IOException; +import java.util.List; import org.apache.maven.scm.manager.plexus.DefaultScmManager; import org.apache.maven.scm.provider.ScmProvider; @@ -32,23 +35,16 @@ import org.apache.maven.wagon.resource.Resource; import org.codehaus.plexus.util.FileUtils; -import java.io.File; -import java.io.IOException; -import java.util.List; - /** * Test for {@link ScmWagon}. You need a subclass for each SCM provider you want to test. * * @author Carlos Sanchez * */ -public abstract class AbstractScmWagonTest - extends WagonTestCase -{ +public abstract class AbstractScmWagonTest extends WagonTestCase { @Override - public void testWagonPutDirectory() throws Exception - { + public void testWagonPutDirectory() throws Exception { super.testWagonPutDirectory(); // repeat the test on a non-empty repo // ScmWagon should checkout all involved subdirs before calling @@ -60,31 +56,26 @@ public void testWagonPutDirectory() throws Exception private String providerClassName; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - FileUtils.deleteDirectory( getCheckoutDirectory() ); + FileUtils.deleteDirectory(getCheckoutDirectory()); - if ( wagon == null ) - { + if (wagon == null) { wagon = (ScmWagon) super.getWagon(); DefaultScmManager scmManager = (DefaultScmManager) wagon.getScmManager(); - if ( getScmProvider() != null ) - { - scmManager.setScmProvider( getScmId(), getScmProvider() ); + if (getScmProvider() != null) { + scmManager.setScmProvider(getScmId(), getScmProvider()); providerClassName = getScmProvider().getClass().getName(); - } - else - { - providerClassName = scmManager.getProviderByType( getScmId() ).getClass().getName(); + } else { + providerClassName = + scmManager.getProviderByType(getScmId()).getClass().getName(); } - wagon.setCheckoutDirectory( getCheckoutDirectory() ); + wagon.setCheckoutDirectory(getCheckoutDirectory()); } } @@ -95,29 +86,23 @@ protected void setUp() * * @return the {@link ScmProvider} to use in the {@link ScmWagon} */ - protected ScmProvider getScmProvider() - { + protected ScmProvider getScmProvider() { return null; } - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { return wagon; } - private File getCheckoutDirectory() - { - return new File( FileTestUtils.getTestOutputDir(), "/checkout-" + providerClassName ); + private File getCheckoutDirectory() { + return new File(FileTestUtils.getTestOutputDir(), "/checkout-" + providerClassName); } - protected int getExpectedContentLengthOnGet( int expectedSize ) - { + protected int getExpectedContentLengthOnGet(int expectedSize) { return WagonConstants.UNKNOWN_LENGTH; } - - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { + + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { return 0; } @@ -128,22 +113,18 @@ protected long getExpectedLastModifiedOnGet( Repository repository, Resource res */ protected abstract String getScmId(); - protected String getProtocol() - { + protected String getProtocol() { return "scm"; } - protected void createDirectory( Wagon wagon, String resourceToCreate, String dirName ) - throws Exception - { - super.createDirectory( wagon, resourceToCreate, dirName ); - FileUtils.deleteDirectory( getCheckoutDirectory() ); + protected void createDirectory(Wagon wagon, String resourceToCreate, String dirName) throws Exception { + super.createDirectory(wagon, resourceToCreate, dirName); + FileUtils.deleteDirectory(getCheckoutDirectory()); } - protected void assertResourcesAreInRemoteSide( Wagon wagon, List resourceNames ) - throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - FileUtils.deleteDirectory( getCheckoutDirectory() ); - super.assertResourcesAreInRemoteSide( wagon, resourceNames ); + protected void assertResourcesAreInRemoteSide(Wagon wagon, List resourceNames) + throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + FileUtils.deleteDirectory(getCheckoutDirectory()); + super.assertResourcesAreInRemoteSide(wagon, resourceNames); } } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmCvsExeWagonTest.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmCvsExeWagonTest.java index 574f9fa9b..ca9b99d92 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmCvsExeWagonTest.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmCvsExeWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import org.apache.maven.scm.provider.ScmProvider; import org.apache.maven.scm.provider.cvslib.cvsexe.CvsExeScmProvider; @@ -28,60 +27,45 @@ * @author Carlos Sanchez * */ -public class ScmCvsExeWagonTest - extends AbstractScmCvsWagonTest -{ +public class ScmCvsExeWagonTest extends AbstractScmCvsWagonTest { @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { assumeHaveCvsBinary(); - if ( !testSkipped ) - { + if (!testSkipped) { super.setUp(); } } - protected ScmProvider getScmProvider() - { + protected ScmProvider getScmProvider() { return new CvsExeScmProvider(); } @Override - public void testWagonGetFileList() - throws Exception - { + public void testWagonGetFileList() throws Exception { // cvs rls is rare } @Override - public void testWagonResourceExists() - throws Exception - { + public void testWagonResourceExists() throws Exception { // cvs rls is rare } @Override - public void testWagonResourceNotExists() - throws Exception - { + public void testWagonResourceNotExists() throws Exception { // cvs rls is rare } @Override - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return false; } /** Optionally set the testSkipped flag */ - protected void assumeHaveCvsBinary() - { - if ( !isSystemCmd( CVS_COMMAND_LINE ) ) - { + protected void assumeHaveCvsBinary() { + if (!isSystemCmd(CVS_COMMAND_LINE)) { testSkipped = true; - System.err.println( "'" + CVS_COMMAND_LINE + "' is not a system command. Ignored " + getName() + "." ); + System.err.println("'" + CVS_COMMAND_LINE + "' is not a system command. Ignored " + getName() + "."); } } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmGitExeWagonTest.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmGitExeWagonTest.java index 78e11b216..dcedd79b0 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmGitExeWagonTest.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmGitExeWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,25 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import org.apache.maven.scm.provider.ScmProvider; /** * Test for ScmWagon using Git Exe as underlying SCM */ -public class ScmGitExeWagonTest - extends AbstractScmGitWagonTest -{ +public class ScmGitExeWagonTest extends AbstractScmGitWagonTest { - protected ScmProvider getScmProvider() - { + protected ScmProvider getScmProvider() { return new UserSafeGitExeScmProvider(); } @Override - public void testWagonGetFileList() - throws Exception - { + public void testWagonGetFileList() throws Exception { // remote list unsupported // When a command is unsupported, SCM throws NoSuchCommandScmException. // However, there's no equivalent exception in the Wagon API. @@ -46,29 +40,22 @@ public void testWagonGetFileList() } @Override - public void testWagonGetFileListWhenDirectoryDoesNotExist() - throws Exception - { + public void testWagonGetFileListWhenDirectoryDoesNotExist() throws Exception { // remote list unsupported } @Override - public void testWagonResourceExists() - throws Exception - { + public void testWagonResourceExists() throws Exception { // remote list unsupported } @Override - public void testWagonResourceNotExists() - throws Exception - { + public void testWagonResourceNotExists() throws Exception { // remote list unsupported } @Override - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return false; } } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmSvnExeWagonTest.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmSvnExeWagonTest.java index d7b9e7fc3..a0099aac8 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmSvnExeWagonTest.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/ScmSvnExeWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,23 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import org.apache.maven.scm.provider.ScmProvider; import org.apache.maven.scm.provider.svn.svnexe.SvnExeScmProvider; /** * Test for ScmWagon using SVN Exe as underlying SCM - * + * * @author Carlos Sanchez * */ -public class ScmSvnExeWagonTest - extends AbstractScmSvnWagonTest -{ +public class ScmSvnExeWagonTest extends AbstractScmSvnWagonTest { - protected ScmProvider getScmProvider() - { + protected ScmProvider getScmProvider() { return new SvnExeScmProvider(); } - } diff --git a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/UserSafeGitExeScmProvider.java b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/UserSafeGitExeScmProvider.java index aca3b0dcd..fe4114a76 100644 --- a/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/UserSafeGitExeScmProvider.java +++ b/wagon-providers/wagon-scm/src/test/java/org/apache/maven/wagon/providers/scm/UserSafeGitExeScmProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.scm; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.ScmFileSet; @@ -33,12 +32,10 @@ public class UserSafeGitExeScmProvider extends GitExeScmProvider { @Override - public CheckInScmResult checkIn( ScmRepository repository, ScmFileSet fileSet, - ScmVersion scmVersion, String message ) - throws ScmException - { - GitScmTestUtils.setDefaultUser( fileSet.getBasedir() ); + public CheckInScmResult checkIn(ScmRepository repository, ScmFileSet fileSet, ScmVersion scmVersion, String message) + throws ScmException { + GitScmTestUtils.setDefaultUser(fileSet.getBasedir()); - return super.checkIn( repository, fileSet, scmVersion, message ); + return super.checkIn(repository, fileSet, scmVersion, message); } } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonTest.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonTest.java index 8593d87e0..b81288508 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonTest.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,82 +16,71 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; + +import java.io.File; +import java.util.Arrays; import org.apache.maven.wagon.StreamingWagonTestCase; import org.apache.maven.wagon.authentication.AuthenticationInfo; import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; -import java.io.File; -import java.util.Arrays; - /** * @author Michal Maczka * */ -public abstract class AbstractEmbeddedScpWagonTest - extends StreamingWagonTestCase -{ +public abstract class AbstractEmbeddedScpWagonTest extends StreamingWagonTestCase { SshServerEmbedded sshServer; @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); String sshKeyResource = "ssh-keys/id_rsa"; - sshServer = new SshServerEmbedded( getProtocol(), Arrays.asList( sshKeyResource ), false ); + sshServer = new SshServerEmbedded(getProtocol(), Arrays.asList(sshKeyResource), false); sshServer.start(); - System.out.println( "sshd on port " + sshServer.getPort() ); + System.out.println("sshd on port " + sshServer.getPort()); } @Override - @SuppressWarnings( "checkstyle:linelength" ) - protected void tearDownWagonTestingFixtures() - throws Exception - { - - for ( TestPasswordAuthenticator.PasswordAuthenticatorRequest request : sshServer.passwordAuthenticator.requests ) - { - assertEquals( TestData.getUserName(), request.getUsername() ); - assertEquals( TestData.getUserPassword(), request.getPassword() ); + @SuppressWarnings("checkstyle:linelength") + protected void tearDownWagonTestingFixtures() throws Exception { + + for (TestPasswordAuthenticator.PasswordAuthenticatorRequest request : + sshServer.passwordAuthenticator.requests) { + assertEquals(TestData.getUserName(), request.getUsername()); + assertEquals(TestData.getUserPassword(), request.getPassword()); } sshServer.stop(); } protected abstract String getProtocol(); - protected int getTestRepositoryPort() - { + protected int getTestRepositoryPort() { return sshServer.getPort(); } - public String getTestRepositoryUrl() - { - return TestData.getTestRepositoryUrl( sshServer.getPort() ); + public String getTestRepositoryUrl() { + return TestData.getTestRepositoryUrl(sshServer.getPort()); } - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = super.getAuthInfo(); - authInfo.setUserName( TestData.getUserName() ); - authInfo.setPassword( TestData.getUserPassword() ); + authInfo.setUserName(TestData.getUserName()); + authInfo.setPassword(TestData.getUserPassword()); return authInfo; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - return new File( repository.getBasedir(), resource.getName() ).lastModified(); + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + return new File(repository.getBasedir(), resource.getName()).lastModified(); } - @Override protected abstract boolean supportsGetIfNewer(); - } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java index f35ffbc7b..6bd0fdee4 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; + +import java.io.File; +import java.util.Arrays; +import java.util.List; import org.apache.maven.wagon.StreamingWagonTestCase; import org.apache.maven.wagon.Wagon; @@ -26,141 +29,116 @@ import org.apache.maven.wagon.resource.Resource; import org.codehaus.plexus.util.FileUtils; -import java.io.File; -import java.util.Arrays; -import java.util.List; - /** * @author Michal Maczka * */ -public abstract class AbstractEmbeddedScpWagonWithKeyTest - extends StreamingWagonTestCase -{ +public abstract class AbstractEmbeddedScpWagonWithKeyTest extends StreamingWagonTestCase { SshServerEmbedded sshServerEmbedded; - @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); String sshKeyResource = "ssh-keys/id_rsa.pub"; - sshServerEmbedded = new SshServerEmbedded( getProtocol(), Arrays.asList( sshKeyResource ), true ); + sshServerEmbedded = new SshServerEmbedded(getProtocol(), Arrays.asList(sshKeyResource), true); sshServerEmbedded.start(); - System.out.println( "sshd on port " + sshServerEmbedded.getPort() ); + System.out.println("sshd on port " + sshServerEmbedded.getPort()); } @Override - protected void tearDownWagonTestingFixtures() - throws Exception - { + protected void tearDownWagonTestingFixtures() throws Exception { sshServerEmbedded.stop(); } protected abstract String getProtocol(); - protected int getTestRepositoryPort() - { + protected int getTestRepositoryPort() { return sshServerEmbedded.getPort(); } - public String getTestRepositoryUrl() - { - return TestData.getTestRepositoryUrl( sshServerEmbedded.getPort() ); + public String getTestRepositoryUrl() { + return TestData.getTestRepositoryUrl(sshServerEmbedded.getPort()); } - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = super.getAuthInfo(); // user : guest/guest123 - passphrase : toto01 - authInfo.setUserName( "guest" ); - //authInfo.setPassword( TestData.getUserPassword() ); - authInfo.setPrivateKey( new File( "src/test/ssh-keys/id_rsa" ).getPath() ); + authInfo.setUserName("guest"); + // authInfo.setPassword( TestData.getUserPassword() ); + authInfo.setPrivateKey(new File("src/test/ssh-keys/id_rsa").getPath()); return authInfo; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - return new File( repository.getBasedir(), resource.getName() ).lastModified(); + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + return new File(repository.getBasedir(), resource.getName()).lastModified(); } - public void testConnect() - throws Exception - { - getWagon().connect( new Repository( "foo", getTestRepositoryUrl() ), getAuthInfo() ); - assertTrue( true ); + public void testConnect() throws Exception { + getWagon().connect(new Repository("foo", getTestRepositoryUrl()), getAuthInfo()); + assertTrue(true); } - @Override - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return false; } - public void testWithSpaces() - throws Exception - { + public void testWithSpaces() throws Exception { String dir = "foo test"; - File spaceDirectory = new File( TestData.getRepoPath(), dir ); - if ( spaceDirectory.exists() ) - { - FileUtils.deleteDirectory( spaceDirectory ); + File spaceDirectory = new File(TestData.getRepoPath(), dir); + if (spaceDirectory.exists()) { + FileUtils.deleteDirectory(spaceDirectory); } spaceDirectory.mkdirs(); String subDir = "foo bar"; - File sub = new File( spaceDirectory, subDir ); - if ( sub.exists() ) - { - FileUtils.deleteDirectory( sub ); + File sub = new File(spaceDirectory, subDir); + if (sub.exists()) { + FileUtils.deleteDirectory(sub); } sub.mkdirs(); - File dummy = new File( "src/test/resources/dummy.txt" ); - FileUtils.copyFileToDirectory( dummy, sub ); + File dummy = new File("src/test/resources/dummy.txt"); + FileUtils.copyFileToDirectory(dummy, sub); String url = getTestRepositoryUrl() + "/" + dir; - Repository repo = new Repository( "foo", url ); + Repository repo = new Repository("foo", url); Wagon wagon = getWagon(); - wagon.connect( repo, getAuthInfo() ); - List files = wagon.getFileList( subDir ); - assertNotNull( files ); - assertEquals( 1, files.size() ); - assertTrue( files.contains( "dummy.txt" ) ); - - wagon.put( new File( "src/test/resources/dummy.txt" ), subDir + "/newdummy.txt" ); - - files = wagon.getFileList( subDir ); - assertNotNull( files ); - assertEquals( 2, files.size() ); - assertTrue( files.contains( "dummy.txt" ) ); - assertTrue( files.contains( "newdummy.txt" ) ); - - File sourceWithSpace = new File( "target/directory with spaces" ); - if ( sourceWithSpace.exists() ) - { - FileUtils.deleteDirectory( sourceWithSpace ); + wagon.connect(repo, getAuthInfo()); + List files = wagon.getFileList(subDir); + assertNotNull(files); + assertEquals(1, files.size()); + assertTrue(files.contains("dummy.txt")); + + wagon.put(new File("src/test/resources/dummy.txt"), subDir + "/newdummy.txt"); + + files = wagon.getFileList(subDir); + assertNotNull(files); + assertEquals(2, files.size()); + assertTrue(files.contains("dummy.txt")); + assertTrue(files.contains("newdummy.txt")); + + File sourceWithSpace = new File("target/directory with spaces"); + if (sourceWithSpace.exists()) { + FileUtils.deleteDirectory(sourceWithSpace); } - File resources = new File( "src/test/resources" ); + File resources = new File("src/test/resources"); - FileUtils.copyDirectory( resources, sourceWithSpace ); + FileUtils.copyDirectory(resources, sourceWithSpace); - wagon.putDirectory( sourceWithSpace, "target with spaces" ); + wagon.putDirectory(sourceWithSpace, "target with spaces"); - files = wagon.getFileList( "target with spaces" ); + files = wagon.getFileList("target with spaces"); - assertNotNull( files ); - assertTrue( files.contains( "dummy.txt" ) ); - assertFalse( files.contains( "newdummy.txt" ) ); - assertTrue( files.contains( "log4j.xml" ) ); + assertNotNull(files); + assertTrue(files.contains("dummy.txt")); + assertFalse(files.contains("newdummy.txt")); + assertTrue(files.contains("log4j.xml")); } - } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommand.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommand.java index bdd80f543..4142e2935 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommand.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommand.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; + +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; import org.apache.sshd.common.util.DirectoryScanner; import org.apache.sshd.server.Command; @@ -29,13 +35,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; - /** * This commands provide SCP support on both server and client side. * Permissions and preservation of access / modification times on files @@ -44,11 +43,9 @@ * * @author Apache MINA SSHD Project */ -public class ScpCommand - implements Command, Runnable, FileSystemAware -{ +public class ScpCommand implements Command, Runnable, FileSystemAware { - protected static final Logger LOG = LoggerFactory.getLogger( ScpCommand.class ); + protected static final Logger LOG = LoggerFactory.getLogger(ScpCommand.class); protected static final int OK = 0; @@ -84,22 +81,16 @@ public class ScpCommand protected IOException error; - public ScpCommand( String[] args ) - { - name = Arrays.asList( args ).toString(); - if ( LOG.isDebugEnabled() ) - { - LOG.debug( "Executing command {}", name ); + public ScpCommand(String[] args) { + name = Arrays.asList(args).toString(); + if (LOG.isDebugEnabled()) { + LOG.debug("Executing command {}", name); } path = "."; - for ( int i = 1; i < args.length; i++ ) - { - if ( args[i].charAt( 0 ) == '-' ) - { - for ( int j = 1; j < args[i].length(); j++ ) - { - switch ( args[i].charAt( j ) ) - { + for (int i = 1; i < args.length; i++) { + if (args[i].charAt(0) == '-') { + for (int j = 1; j < args[i].length(); j++) { + switch (args[i].charAt(j)) { case 'f': optF = true; break; @@ -119,470 +110,351 @@ public ScpCommand( String[] args ) optD = true; break; default: -// error = new IOException("Unsupported option: " + args[i].charAt(j)); -// return; + // error = new IOException("Unsupported option: " + + // args[i].charAt(j)); + // return; } } - } - else if ( i == args.length - 1 ) - { + } else if (i == args.length - 1) { path = args[args.length - 1]; } } - if ( !optF && !optT ) - { - error = new IOException( "Either -f or -t option should be set" ); + if (!optF && !optT) { + error = new IOException("Either -f or -t option should be set"); } } - public void setInputStream( InputStream in ) - { + public void setInputStream(InputStream in) { this.in = in; } - public void setOutputStream( OutputStream out ) - { + public void setOutputStream(OutputStream out) { this.out = out; } - public void setErrorStream( OutputStream err ) - { + public void setErrorStream(OutputStream err) { this.err = err; } - public void setExitCallback( ExitCallback callback ) - { + public void setExitCallback(ExitCallback callback) { this.callback = callback; } - public void start( Environment env ) - throws IOException - { - if ( error != null ) - { + public void start(Environment env) throws IOException { + if (error != null) { throw error; } - new Thread( this, "ScpCommand: " + name ).start(); + new Thread(this, "ScpCommand: " + name).start(); } - public void destroy() - { - } + public void destroy() {} - public void run() - { + public void run() { int exitValue = OK; String exitMessage = null; - try - { - if ( optT ) - { + try { + if (optT) { ack(); - for (; ; ) - { + for (; ; ) { String line; boolean isDir = false; - int c = readAck( true ); - switch ( c ) - { + int c = readAck(true); + switch (c) { case -1: return; case 'D': isDir = true; case 'C': - line = ( (char) c ) + readLine(); + line = ((char) c) + readLine(); break; case 'E': readLine(); return; default: - //a real ack that has been acted upon already + // a real ack that has been acted upon already continue; } - if ( optR && isDir ) - { - writeDir( line, root.getFile( path ) ); - } - else - { - writeFile( line, root.getFile( path ) ); + if (optR && isDir) { + writeDir(line, root.getFile(path)); + } else { + writeFile(line, root.getFile(path)); } } - } - else if ( optF ) - { + } else if (optF) { String pattern = path; - int idx = pattern.indexOf( '*' ); - if ( idx >= 0 ) - { + int idx = pattern.indexOf('*'); + if (idx >= 0) { String basedir = ""; - int lastSep = pattern.substring( 0, idx ).lastIndexOf( '/' ); - if ( lastSep >= 0 ) - { - basedir = pattern.substring( 0, lastSep ); - pattern = pattern.substring( lastSep + 1 ); + int lastSep = pattern.substring(0, idx).lastIndexOf('/'); + if (lastSep >= 0) { + basedir = pattern.substring(0, lastSep); + pattern = pattern.substring(lastSep + 1); } - String[] included = new DirectoryScanner( basedir, pattern ).scan(); - for ( String path : included ) - { - SshFile file = root.getFile( basedir + "/" + path ); - if ( file.isFile() ) - { - readFile( file ); - } - else if ( file.isDirectory() ) - { - if ( !optR ) - { - out.write( WARNING ); - out.write( ( path + " not a regular file\n" ).getBytes() ); - } - else - { - readDir( file ); + String[] included = new DirectoryScanner(basedir, pattern).scan(); + for (String path : included) { + SshFile file = root.getFile(basedir + "/" + path); + if (file.isFile()) { + readFile(file); + } else if (file.isDirectory()) { + if (!optR) { + out.write(WARNING); + out.write((path + " not a regular file\n").getBytes()); + } else { + readDir(file); } - } - else - { - out.write( WARNING ); - out.write( ( path + " unknown file type\n" ).getBytes() ); + } else { + out.write(WARNING); + out.write((path + " unknown file type\n").getBytes()); } } - } - else - { + } else { String basedir = ""; - int lastSep = pattern.lastIndexOf( '/' ); - if ( lastSep >= 0 ) - { - basedir = pattern.substring( 0, lastSep ); - pattern = pattern.substring( lastSep + 1 ); + int lastSep = pattern.lastIndexOf('/'); + if (lastSep >= 0) { + basedir = pattern.substring(0, lastSep); + pattern = pattern.substring(lastSep + 1); } - SshFile file = root.getFile( basedir + "/" + pattern ); - if ( !file.doesExist() ) - { + SshFile file = root.getFile(basedir + "/" + pattern); + if (!file.doesExist()) { exitValue = WARNING; - throw new IOException( file + ": no such file or directory" ); - } - if ( file.isFile() ) - { - readFile( file ); + throw new IOException(file + ": no such file or directory"); } - else if ( file.isDirectory() ) - { - if ( !optR ) - { - throw new IOException( file + " not a regular file" ); - } - else - { - readDir( file ); + if (file.isFile()) { + readFile(file); + } else if (file.isDirectory()) { + if (!optR) { + throw new IOException(file + " not a regular file"); + } else { + readDir(file); } - } - else - { - throw new IOException( file + ": unknown file type" ); + } else { + throw new IOException(file + ": unknown file type"); } } + } else { + throw new IOException("Unsupported mode"); } - else - { - throw new IOException( "Unsupported mode" ); - } - } - catch ( IOException e ) - { - try - { - exitValue = ( exitValue != OK ? exitValue : ERROR ); + } catch (IOException e) { + try { + exitValue = (exitValue != OK ? exitValue : ERROR); exitMessage = e.getMessage(); - out.write( exitValue ); - out.write( exitMessage.getBytes() ); - out.write( '\n' ); + out.write(exitValue); + out.write(exitMessage.getBytes()); + out.write('\n'); out.flush(); - } - catch ( IOException e2 ) - { + } catch (IOException e2) { // Ignore } - LOG.info( "Error in scp command", e ); - } - finally - { - if ( callback != null ) - { - callback.onExit( exitValue, exitMessage ); + LOG.info("Error in scp command", e); + } finally { + if (callback != null) { + callback.onExit(exitValue, exitMessage); } } } - protected void writeDir( String header, SshFile path ) - throws IOException - { - if ( LOG.isDebugEnabled() ) - { - LOG.debug( "Writing dir {}", path ); + protected void writeDir(String header, SshFile path) throws IOException { + if (LOG.isDebugEnabled()) { + LOG.debug("Writing dir {}", path); } - if ( !header.startsWith( "D" ) ) - { - throw new IOException( "Expected a D message but got '" + header + "'" ); + if (!header.startsWith("D")) { + throw new IOException("Expected a D message but got '" + header + "'"); } - String perms = header.substring( 1, 5 ); - int length = Integer.parseInt( header.substring( 6, header.indexOf( ' ', 6 ) ) ); - String name = header.substring( header.indexOf( ' ', 6 ) + 1 ); + String perms = header.substring(1, 5); + int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6))); + String name = header.substring(header.indexOf(' ', 6) + 1); - if ( length != 0 ) - { - throw new IOException( "Expected 0 length for directory but got " + length ); + if (length != 0) { + throw new IOException("Expected 0 length for directory but got " + length); } SshFile file; - if ( path.doesExist() && path.isDirectory() ) - { - file = root.getFile( path, name ); - } - else if ( !path.doesExist() && path.getParentFile().doesExist() && path.getParentFile().isDirectory() ) - { + if (path.doesExist() && path.isDirectory()) { + file = root.getFile(path, name); + } else if (!path.doesExist() + && path.getParentFile().doesExist() + && path.getParentFile().isDirectory()) { file = path; + } else { + throw new IOException("Can not write to " + path); } - else - { - throw new IOException( "Can not write to " + path ); - } - if ( !( file.doesExist() && file.isDirectory() ) && !file.mkdir() ) - { - throw new IOException( "Could not create directory " + file ); + if (!(file.doesExist() && file.isDirectory()) && !file.mkdir()) { + throw new IOException("Could not create directory " + file); } ack(); - for (; ; ) - { + for (; ; ) { header = readLine(); - if ( header.startsWith( "C" ) ) - { - writeFile( header, file ); - } - else if ( header.startsWith( "D" ) ) - { - writeDir( header, file ); - } - else if ( header.equals( "E" ) ) - { + if (header.startsWith("C")) { + writeFile(header, file); + } else if (header.startsWith("D")) { + writeDir(header, file); + } else if (header.equals("E")) { ack(); break; - } - else - { - throw new IOException( "Unexpected message: '" + header + "'" ); + } else { + throw new IOException("Unexpected message: '" + header + "'"); } } - } - protected void writeFile( String header, SshFile path ) - throws IOException - { - if ( LOG.isDebugEnabled() ) - { - LOG.debug( "Writing file {}", path ); + protected void writeFile(String header, SshFile path) throws IOException { + if (LOG.isDebugEnabled()) { + LOG.debug("Writing file {}", path); } - if ( !header.startsWith( "C" ) ) - { - throw new IOException( "Expected a C message but got '" + header + "'" ); + if (!header.startsWith("C")) { + throw new IOException("Expected a C message but got '" + header + "'"); } - String perms = header.substring( 1, 5 ); - long length = Long.parseLong( header.substring( 6, header.indexOf( ' ', 6 ) ) ); - String name = header.substring( header.indexOf( ' ', 6 ) + 1 ); + String perms = header.substring(1, 5); + long length = Long.parseLong(header.substring(6, header.indexOf(' ', 6))); + String name = header.substring(header.indexOf(' ', 6) + 1); SshFile file; - if ( path.doesExist() && path.isDirectory() ) - { - file = root.getFile( path, name ); - } - else if ( path.doesExist() && path.isFile() ) - { + if (path.doesExist() && path.isDirectory()) { + file = root.getFile(path, name); + } else if (path.doesExist() && path.isFile()) { file = path; - } - else if ( !path.doesExist() && path.getParentFile().doesExist() && path.getParentFile().isDirectory() ) - { + } else if (!path.doesExist() + && path.getParentFile().doesExist() + && path.getParentFile().isDirectory()) { file = path; + } else { + throw new IOException("Can not write to " + path); } - else - { - throw new IOException( "Can not write to " + path ); - } - if ( file.doesExist() && file.isDirectory() ) - { - throw new IOException( "File is a directory: " + file ); - } - else if ( file.doesExist() && !file.isWritable() ) - { - throw new IOException( "Can not write to file: " + file ); + if (file.doesExist() && file.isDirectory()) { + throw new IOException("File is a directory: " + file); + } else if (file.doesExist() && !file.isWritable()) { + throw new IOException("Can not write to file: " + file); } - OutputStream os = file.createOutputStream( 0 ); - try - { + OutputStream os = file.createOutputStream(0); + try { ack(); byte[] buffer = new byte[8 * 1024]; - while ( length > 0 ) - { - int len = (int) Math.min( length, buffer.length ); - len = in.read( buffer, 0, len ); - if ( len <= 0 ) - { - throw new IOException( "End of stream reached" ); + while (length > 0) { + int len = (int) Math.min(length, buffer.length); + len = in.read(buffer, 0, len); + if (len <= 0) { + throw new IOException("End of stream reached"); } - os.write( buffer, 0, len ); + os.write(buffer, 0, len); length -= len; } - } - finally - { + } finally { os.close(); } ack(); - readAck( false ); + readAck(false); } - protected String readLine() - throws IOException - { + protected String readLine() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - for (; ; ) - { + for (; ; ) { int c = in.read(); - if ( c == '\n' ) - { + if (c == '\n') { return baos.toString(); - } - else if ( c == -1 ) - { - throw new IOException( "End of stream" ); - } - else - { - baos.write( c ); + } else if (c == -1) { + throw new IOException("End of stream"); + } else { + baos.write(c); } } } - protected void readFile( SshFile path ) - throws IOException - { - if ( LOG.isDebugEnabled() ) - { - LOG.debug( "Reading file {}", path ); + protected void readFile(SshFile path) throws IOException { + if (LOG.isDebugEnabled()) { + LOG.debug("Reading file {}", path); } StringBuilder buf = new StringBuilder(); - buf.append( "C" ); - buf.append( "0644" ); // what about perms - buf.append( " " ); - buf.append( path.getSize() ); // length - buf.append( " " ); - buf.append( path.getName() ); - buf.append( "\n" ); - out.write( buf.toString().getBytes() ); + buf.append("C"); + buf.append("0644"); // what about perms + buf.append(" "); + buf.append(path.getSize()); // length + buf.append(" "); + buf.append(path.getName()); + buf.append("\n"); + out.write(buf.toString().getBytes()); out.flush(); - readAck( false ); + readAck(false); - InputStream is = path.createInputStream( 0 ); - try - { + InputStream is = path.createInputStream(0); + try { byte[] buffer = new byte[8 * 1024]; - for (; ; ) - { - int len = is.read( buffer, 0, buffer.length ); - if ( len == -1 ) - { + for (; ; ) { + int len = is.read(buffer, 0, buffer.length); + if (len == -1) { break; } - out.write( buffer, 0, len ); + out.write(buffer, 0, len); } - } - finally - { + } finally { is.close(); } ack(); - readAck( false ); + readAck(false); } - protected void readDir( SshFile path ) - throws IOException - { - if ( LOG.isDebugEnabled() ) - { - LOG.debug( "Reading directory {}", path ); + protected void readDir(SshFile path) throws IOException { + if (LOG.isDebugEnabled()) { + LOG.debug("Reading directory {}", path); } StringBuilder buf = new StringBuilder(); - buf.append( "D" ); - buf.append( "0755" ); // what about perms - buf.append( " " ); - buf.append( "0" ); // length - buf.append( " " ); - buf.append( path.getName() ); - buf.append( "\n" ); - out.write( buf.toString().getBytes() ); + buf.append("D"); + buf.append("0755"); // what about perms + buf.append(" "); + buf.append("0"); // length + buf.append(" "); + buf.append(path.getName()); + buf.append("\n"); + out.write(buf.toString().getBytes()); out.flush(); - readAck( false ); + readAck(false); - for ( SshFile child : path.listSshFiles() ) - { - if ( child.isFile() ) - { - readFile( child ); - } - else if ( child.isDirectory() ) - { - readDir( child ); + for (SshFile child : path.listSshFiles()) { + if (child.isFile()) { + readFile(child); + } else if (child.isDirectory()) { + readDir(child); } } - out.write( "E\n".getBytes() ); + out.write("E\n".getBytes()); out.flush(); - readAck( false ); + readAck(false); } - protected void ack() - throws IOException - { - out.write( 0 ); + protected void ack() throws IOException { + out.write(0); out.flush(); } - protected int readAck( boolean canEof ) - throws IOException - { + protected int readAck(boolean canEof) throws IOException { int c = in.read(); - switch ( c ) - { + switch (c) { case -1: - if ( !canEof ) - { + if (!canEof) { throw new EOFException(); } break; case OK: break; case WARNING: - LOG.warn( "Received warning: " + readLine() ); + LOG.warn("Received warning: " + readLine()); break; case ERROR: - throw new IOException( "Received nack: " + readLine() ); + throw new IOException("Received nack: " + readLine()); default: break; } return c; } - public void setFileSystemView( FileSystemView view ) - { + public void setFileSystemView(FileSystemView view) { this.root = view; } } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommandFactory.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommandFactory.java index 0b52d7b79..02f022d97 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommandFactory.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ScpCommandFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.sshd.server.Command; -import org.apache.sshd.server.CommandFactory; +package org.apache.maven.wagon.providers.ssh; import java.util.ArrayList; import java.util.List; +import org.apache.sshd.server.Command; +import org.apache.sshd.server.CommandFactory; + /** * This CommandFactory can be used as a standalone command factory * or can be used to augment another CommandFactory and provides @@ -34,18 +33,13 @@ * * @author Apache MINA SSHD Project */ -public class ScpCommandFactory - implements CommandFactory -{ +public class ScpCommandFactory implements CommandFactory { private CommandFactory delegate; - public ScpCommandFactory() - { - } + public ScpCommandFactory() {} - public ScpCommandFactory( CommandFactory delegate ) - { + public ScpCommandFactory(CommandFactory delegate) { this.delegate = delegate; } @@ -58,54 +52,41 @@ public ScpCommandFactory( CommandFactory delegate ) * @return configured {@link org.apache.sshd.server.Command} instance * @throws IllegalArgumentException */ - public Command createCommand( String command ) - { - try - { - return new ScpCommand( splitCommandString( command ) ); - } - catch ( IllegalArgumentException iae ) - { - if ( delegate != null ) - { - return delegate.createCommand( command ); + public Command createCommand(String command) { + try { + return new ScpCommand(splitCommandString(command)); + } catch (IllegalArgumentException iae) { + if (delegate != null) { + return delegate.createCommand(command); } throw iae; } } - private String[] splitCommandString( String command ) - { - if ( !command.trim().startsWith( "scp" ) ) - { - throw new IllegalArgumentException( "Unknown command, does not begin with 'scp'" ); + private String[] splitCommandString(String command) { + if (!command.trim().startsWith("scp")) { + throw new IllegalArgumentException("Unknown command, does not begin with 'scp'"); } - String[] args = command.split( " " ); + String[] args = command.split(" "); List parts = new ArrayList<>(); - parts.add( args[0] ); - for ( int i = 1; i < args.length; i++ ) - { - if ( !args[i].trim().startsWith( "-" ) ) - { - parts.add( concatenateWithSpace( args, i ) ); + parts.add(args[0]); + for (int i = 1; i < args.length; i++) { + if (!args[i].trim().startsWith("-")) { + parts.add(concatenateWithSpace(args, i)); break; - } - else - { - parts.add( args[i] ); + } else { + parts.add(args[i]); } } - return parts.toArray( new String[parts.size()] ); + return parts.toArray(new String[parts.size()]); } - private String concatenateWithSpace( String[] args, int from ) - { + private String concatenateWithSpace(String[] args, int from) { StringBuilder sb = new StringBuilder(); - for ( int i = from; i < args.length; i++ ) - { - sb.append( args[i] + " " ); + for (int i = from; i < args.length; i++) { + sb.append(args[i] + " "); } return sb.toString().trim(); } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ShellCommand.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ShellCommand.java index 1783829a7..c91e5767c 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ShellCommand.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/ShellCommand.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import org.apache.sshd.server.Command; import org.apache.sshd.server.Environment; @@ -26,146 +30,117 @@ import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - /** * @author Olivier Lamy */ -public class ShellCommand implements Command -{ -protected static final int OK = 0; +public class ShellCommand implements Command { + protected static final int OK = 0; - protected static final int WARNING = 1; + protected static final int WARNING = 1; - protected static final int ERROR = 2; + protected static final int ERROR = 2; - private InputStream in; + private InputStream in; - private OutputStream out; + private OutputStream out; - private OutputStream err; + private OutputStream err; - private ExitCallback callback; + private ExitCallback callback; - private Thread thread; + private Thread thread; - private String commandLine; + private String commandLine; - public ShellCommand( String commandLine ) - { - this.commandLine = commandLine; - } + public ShellCommand(String commandLine) { + this.commandLine = commandLine; + } - public void setInputStream( InputStream in ) - { - this.in = in; - } + public void setInputStream(InputStream in) { + this.in = in; + } - public void setOutputStream( OutputStream out ) - { - this.out = out; - } + public void setOutputStream(OutputStream out) { + this.out = out; + } - public void setErrorStream( OutputStream err ) - { - this.err = err; - } + public void setErrorStream(OutputStream err) { + this.err = err; + } - public void setExitCallback( ExitCallback callback ) - { - this.callback = callback; - } + public void setExitCallback(ExitCallback callback) { + this.callback = callback; + } - public void start( Environment env ) - throws IOException - { - File tmpFile = File.createTempFile( "wagon", "test-sh" ); - tmpFile.deleteOnExit(); - int exitValue = 0; - CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer(); - CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer(); - try - { + public void start(Environment env) throws IOException { + File tmpFile = File.createTempFile("wagon", "test-sh"); + tmpFile.deleteOnExit(); + int exitValue = 0; + CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer(); + CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer(); + try { - // hackhish defaut commandline tools not support ; or && so write a file with the script - // and "/bin/sh -e " + tmpFile.getPath(); - FileUtils.fileWrite( tmpFile, commandLine ); - - Commandline cl = new Commandline(); - cl.setExecutable( "/bin/sh" ); - //cl.createArg().setValue( "-e" ); - //cl.createArg().setValue( tmpFile.getPath() ); - cl.createArg().setFile( tmpFile ); - - exitValue = CommandLineUtils.executeCommandLine( cl, stdout, stderr ); - System.out.println( "exit value " + exitValue ); - /* - if ( exitValue == 0 ) - { - out.write( stdout.getOutput().getBytes() ); - out.write( '\n' ); - out.flush(); - - } - else - { - out.write( stderr.getOutput().getBytes() ); - out.write( '\n' ); - out.flush(); - - }*/ + // hackhish defaut commandline tools not support ; or && so write a file with the script + // and "/bin/sh -e " + tmpFile.getPath(); + FileUtils.fileWrite(tmpFile, commandLine); - } - catch ( Exception e ) + Commandline cl = new Commandline(); + cl.setExecutable("/bin/sh"); + // cl.createArg().setValue( "-e" ); + // cl.createArg().setValue( tmpFile.getPath() ); + cl.createArg().setFile(tmpFile); + + exitValue = CommandLineUtils.executeCommandLine(cl, stdout, stderr); + System.out.println("exit value " + exitValue); + /* + if ( exitValue == 0 ) { - exitValue = ERROR; - e.printStackTrace(); + out.write( stdout.getOutput().getBytes() ); + out.write( '\n' ); + out.flush(); + } - finally + else { - deleteQuietly( tmpFile ); - if ( exitValue != 0 ) - { - err.write( stderr.getOutput().getBytes() ); - err.write( '\n' ); - err.flush(); - callback.onExit( exitValue, stderr.getOutput() ); - } - else - { - out.write( stdout.getOutput().getBytes() ); - out.write( '\n' ); - out.flush(); - callback.onExit( exitValue, stdout.getOutput() ); - } - + out.write( stderr.getOutput().getBytes() ); + out.write( '\n' ); + out.flush(); + + }*/ + + } catch (Exception e) { + exitValue = ERROR; + e.printStackTrace(); + } finally { + deleteQuietly(tmpFile); + if (exitValue != 0) { + err.write(stderr.getOutput().getBytes()); + err.write('\n'); + err.flush(); + callback.onExit(exitValue, stderr.getOutput()); + } else { + out.write(stdout.getOutput().getBytes()); + out.write('\n'); + out.flush(); + callback.onExit(exitValue, stdout.getOutput()); } - /* - out.write( exitValue ); - out.write( '\n' ); - - */ - out.flush(); } + /* + out.write( exitValue ); + out.write( '\n' ); - public void destroy() - { + */ + out.flush(); + } - } + public void destroy() {} - private void deleteQuietly( File f ) - { + private void deleteQuietly(File f) { - try - { - f.delete(); - } - catch ( Exception e ) - { - // ignore - } + try { + f.delete(); + } catch (Exception e) { + // ignore } + } } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/SshServerEmbedded.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/SshServerEmbedded.java index 47334025d..b0334cc37 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/SshServerEmbedded.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/SshServerEmbedded.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.apache.mina.core.session.IoSession; import org.apache.sshd.SshServer; @@ -37,17 +42,10 @@ import org.apache.sshd.server.shell.ProcessShellFactory; import org.codehaus.plexus.util.FileUtils; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - /** * @author Olivier Lamy */ -public class SshServerEmbedded -{ +public class SshServerEmbedded { private String wagonProtocol; private int port; @@ -62,147 +60,122 @@ public class SshServerEmbedded private boolean keyAuthz; - /** * @param wagonProtocol scp scpexe * @param sshKeysResources paths in the classlaoder with ssh keys */ - public SshServerEmbedded( String wagonProtocol, List sshKeysResources, boolean keyAuthz ) - { + public SshServerEmbedded(String wagonProtocol, List sshKeysResources, boolean keyAuthz) { this.wagonProtocol = wagonProtocol; this.sshKeysResources = sshKeysResources; this.sshd = SshServer.setUpDefaultServer(); - //this.sshd.setKeyExchangeFactories( ); + // this.sshd.setKeyExchangeFactories( ); this.keyAuthz = keyAuthz; - publickeyAuthenticator = new TestPublickeyAuthenticator( this.keyAuthz ); + publickeyAuthenticator = new TestPublickeyAuthenticator(this.keyAuthz); } /** * @return random port used */ - public int start() - throws IOException - { - sshd.setPort( 0 ); + public int start() throws IOException { + sshd.setPort(0); - sshd.setUserAuthFactories( Arrays.asList( new UserAuthPublicKey.Factory(), new UserAuthPassword.Factory() ) ); + sshd.setUserAuthFactories(Arrays.asList(new UserAuthPublicKey.Factory(), new UserAuthPassword.Factory())); - sshd.setPublickeyAuthenticator( this.publickeyAuthenticator ); + sshd.setPublickeyAuthenticator(this.publickeyAuthenticator); - sshd.setPasswordAuthenticator( this.passwordAuthenticator ); + sshd.setPasswordAuthenticator(this.passwordAuthenticator); - sshd.setUserAuthFactories( Arrays.asList( new UserAuthPublicKey.Factory(), new UserAuthPassword.Factory() ) ); + sshd.setUserAuthFactories(Arrays.asList(new UserAuthPublicKey.Factory(), new UserAuthPassword.Factory())); - //ResourceKeyPairProvider resourceKeyPairProvider = + // ResourceKeyPairProvider resourceKeyPairProvider = // new ResourceKeyPairProvider( sshKeysResources.toArray( new String[sshKeysResources.size()] ) ); - File path = new File( "target/keys" ); + File path = new File("target/keys"); path.mkdirs(); - path = new File( path, "simple.key" ); + path = new File(path, "simple.key"); path.delete(); PEMGeneratorHostKeyProvider provider = new PEMGeneratorHostKeyProvider(); - provider.setAlgorithm( "RSA" ); - provider.setKeySize( 1024 ); - provider.setPath( path.getPath() ); + provider.setAlgorithm("RSA"); + provider.setKeySize(1024); + provider.setPath(path.getPath()); - sshd.setKeyPairProvider( provider ); - SessionFactory sessionFactory = new SessionFactory() - { + sshd.setKeyPairProvider(provider); + SessionFactory sessionFactory = new SessionFactory() { @Override - protected AbstractSession doCreateSession( IoSession ioSession ) - throws Exception - { - return super.doCreateSession( ioSession ); + protected AbstractSession doCreateSession(IoSession ioSession) throws Exception { + return super.doCreateSession(ioSession); } }; - sshd.setSessionFactory( sessionFactory ); + sshd.setSessionFactory(sessionFactory); - //sshd.setFileSystemFactory( ); + // sshd.setFileSystemFactory( ); - final ProcessShellFactory processShellFactory = - new ProcessShellFactory( new String[]{ "/bin/sh", "-i", "-l" } ); - sshd.setShellFactory( processShellFactory ); + final ProcessShellFactory processShellFactory = new ProcessShellFactory(new String[] {"/bin/sh", "-i", "-l"}); + sshd.setShellFactory(processShellFactory); - CommandFactory delegateCommandFactory = new CommandFactory() - { - public Command createCommand( String command ) - { - return new ShellCommand( command ); + CommandFactory delegateCommandFactory = new CommandFactory() { + public Command createCommand(String command) { + return new ShellCommand(command); } }; - ScpCommandFactory commandFactory = new ScpCommandFactory( delegateCommandFactory ); - sshd.setCommandFactory( commandFactory ); - - FileSystemFactory fileSystemFactory = new FileSystemFactory() - { - public FileSystemView createFileSystemView( Session session ) - throws IOException - { - return new FileSystemView() - { - public SshFile getFile( String file ) - { - file = file.replace( "\\", "" ); - file = file.replace( "\"", "" ); - File f = new File( FileUtils.normalize( file ) ); - - return new SshServerEmbedded.TestSshFile( f.getAbsolutePath(), f, - System.getProperty( "user.name" ) ); + ScpCommandFactory commandFactory = new ScpCommandFactory(delegateCommandFactory); + sshd.setCommandFactory(commandFactory); + + FileSystemFactory fileSystemFactory = new FileSystemFactory() { + public FileSystemView createFileSystemView(Session session) throws IOException { + return new FileSystemView() { + public SshFile getFile(String file) { + file = file.replace("\\", ""); + file = file.replace("\"", ""); + File f = new File(FileUtils.normalize(file)); + + return new SshServerEmbedded.TestSshFile( + f.getAbsolutePath(), f, System.getProperty("user.name")); } - public SshFile getFile( SshFile baseDir, String file ) - { - file = file.replace( "\\", "" ); - file = file.replace( "\"", "" ); - File f = new File( FileUtils.normalize( file ) ); - return new SshServerEmbedded.TestSshFile( f.getAbsolutePath(), f, - System.getProperty( "user.name" ) ); + public SshFile getFile(SshFile baseDir, String file) { + file = file.replace("\\", ""); + file = file.replace("\"", ""); + File f = new File(FileUtils.normalize(file)); + return new SshServerEmbedded.TestSshFile( + f.getAbsolutePath(), f, System.getProperty("user.name")); } }; } }; - sshd.setNioWorkers( 0 ); - //sshd.setScheduledExecutorService( ); - sshd.setFileSystemFactory( fileSystemFactory ); + sshd.setNioWorkers(0); + // sshd.setScheduledExecutorService( ); + sshd.setFileSystemFactory(fileSystemFactory); sshd.start(); this.port = sshd.getPort(); return this.port; } - - public void stop() - throws InterruptedException - { - sshd.stop( Boolean.getBoolean( "sshd.stopImmediatly" ) ); + public void stop() throws InterruptedException { + sshd.stop(Boolean.getBoolean("sshd.stopImmediatly")); } - public int getPort() - { + public int getPort() { return port; } - public PasswordAuthenticator getPasswordAuthenticator() - { + public PasswordAuthenticator getPasswordAuthenticator() { return passwordAuthenticator; } /** - * + * */ - public static class TestSshFile - extends NativeSshFile - { - public TestSshFile( String fileName, File file, String userName ) - { + public static class TestSshFile extends NativeSshFile { + public TestSshFile(String fileName, File file, String userName) { - super( FileUtils.normalize( fileName ), file, userName ); + super(FileUtils.normalize(fileName), file, userName); } } - } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestData.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestData.java index 71b36c05f..72bd93020 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestData.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestData.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,68 +16,56 @@ * specific language governing permissions and limitations * under the License. */ - -import org.codehaus.plexus.util.FileUtils; +package org.apache.maven.wagon.providers.ssh; import java.io.File; import java.io.IOException; +import org.codehaus.plexus.util.FileUtils; + /** * @author Michal Maczka * */ -public class TestData -{ - public static String getTempDirectory() - { - return System.getProperty( "java.io.tmpdir", "target" ); +public class TestData { + public static String getTempDirectory() { + return System.getProperty("java.io.tmpdir", "target"); } - public static String getTestRepositoryUrl( int port ) - { + public static String getTestRepositoryUrl(int port) { return "scp://" + getHostname() + ":" + port + getRepoPath(); } - public static String getTestRepositoryUrl() - { + public static String getTestRepositoryUrl() { return "scp://" + getHostname() + getRepoPath(); } - public static String getRepoPath() - { + public static String getRepoPath() { return getTempDirectory() + "/wagon-ssh-test/" + getUserName(); } - public static String getUserName() - { - return System.getProperty( "test.user", System.getProperty( "user.name" ) ); + public static String getUserName() { + return System.getProperty("test.user", System.getProperty("user.name")); } - public static String getUserPassword() - { + public static String getUserPassword() { return "comeonFrance!:-)"; } - public static File getPrivateKey() - { - return new File( System.getProperty( "sshKeysPath", "src/test/ssh-keys" ), "id_rsa" ); + public static File getPrivateKey() { + return new File(System.getProperty("sshKeysPath", "src/test/ssh-keys"), "id_rsa"); } - public static String getHostname() - { - return System.getProperty( "test.host", "localhost" ); + public static String getHostname() { + return System.getProperty("test.host", "localhost"); } - public static String getHostKey() - { - try - { - return FileUtils.fileRead( - new File( System.getProperty( "sshKeysPath" ), "id_rsa.pub" ).getPath() ).substring( - "ssh-rsa".length() ).trim(); - } - catch ( IOException e ) - { + public static String getHostKey() { + try { + return FileUtils.fileRead(new File(System.getProperty("sshKeysPath"), "id_rsa.pub").getPath()) + .substring("ssh-rsa".length()) + .trim(); + } catch (IOException e) { return null; } } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPasswordAuthenticator.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPasswordAuthenticator.java index 0f12410f5..b25f64f41 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPasswordAuthenticator.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPasswordAuthenticator.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,63 +16,55 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; + +import java.util.ArrayList; +import java.util.List; import org.apache.sshd.server.PasswordAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.codehaus.plexus.util.StringUtils; -import java.util.ArrayList; -import java.util.List; - /** * @author Olivier Lamy */ -public class TestPasswordAuthenticator - implements PasswordAuthenticator -{ - List requests = - new ArrayList<>(); +public class TestPasswordAuthenticator implements PasswordAuthenticator { + List requests = new ArrayList<>(); - public boolean authenticate( String username, String password, ServerSession session ) - { - requests.add( new PasswordAuthenticatorRequest( username, password ) ); - return StringUtils.equals( username, TestData.getUserName() ) - && StringUtils.equals( password, TestData.getUserPassword() ); + public boolean authenticate(String username, String password, ServerSession session) { + requests.add(new PasswordAuthenticatorRequest(username, password)); + return StringUtils.equals(username, TestData.getUserName()) + && StringUtils.equals(password, TestData.getUserPassword()); } /** - * + * */ - public static class PasswordAuthenticatorRequest - { + public static class PasswordAuthenticatorRequest { private String username; private String password; - public PasswordAuthenticatorRequest( String username, String password ) - { + public PasswordAuthenticatorRequest(String username, String password) { this.username = username; this.password = password; } @Override - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder(); - sb.append( "PasswordAuthenticatorRequest" ); - sb.append( "{username='" ).append( username ).append( '\'' ); - sb.append( ", password='" ).append( password ).append( '\'' ); - sb.append( '}' ); + sb.append("PasswordAuthenticatorRequest"); + sb.append("{username='").append(username).append('\''); + sb.append(", password='").append(password).append('\''); + sb.append('}'); return sb.toString(); } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPublickeyAuthenticator.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPublickeyAuthenticator.java index 98c3e78ba..e77bef72e 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPublickeyAuthenticator.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/TestPublickeyAuthenticator.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.mina.util.Base64; -import org.apache.sshd.server.PublickeyAuthenticator; -import org.apache.sshd.server.session.ServerSession; -import org.codehaus.plexus.util.IOUtil; +package org.apache.maven.wagon.providers.ssh; import javax.crypto.Cipher; + import java.io.InputStream; import java.math.BigInteger; import java.security.KeyFactory; @@ -36,83 +31,72 @@ import java.util.ArrayList; import java.util.List; +import org.apache.mina.util.Base64; +import org.apache.sshd.server.PublickeyAuthenticator; +import org.apache.sshd.server.session.ServerSession; +import org.codehaus.plexus.util.IOUtil; + /** * @author Olivier Lamy */ -public class TestPublickeyAuthenticator - implements PublickeyAuthenticator -{ - private List publickeyAuthenticatorRequests = - new ArrayList<>(); +public class TestPublickeyAuthenticator implements PublickeyAuthenticator { + private List publickeyAuthenticatorRequests = new ArrayList<>(); private boolean keyAuthz; - public TestPublickeyAuthenticator( boolean keyAuthz ) - { + public TestPublickeyAuthenticator(boolean keyAuthz) { this.keyAuthz = keyAuthz; } - public boolean authenticate( String username, PublicKey key, ServerSession session ) - { - if ( !keyAuthz ) - { + public boolean authenticate(String username, PublicKey key, ServerSession session) { + if (!keyAuthz) { return false; } InputStream in = null; - try - { - in = Thread.currentThread().getContextClassLoader().getResourceAsStream( "ssh-keys/id_rsa.pub" ); - PublicKey publicKey = decodePublicKey( IOUtil.toString( in ) ); + try { + in = Thread.currentThread().getContextClassLoader().getResourceAsStream("ssh-keys/id_rsa.pub"); + PublicKey publicKey = decodePublicKey(IOUtil.toString(in)); in.close(); in = null; - publickeyAuthenticatorRequests.add( new PublickeyAuthenticatorRequest( username, key ) ); + publickeyAuthenticatorRequests.add(new PublickeyAuthenticatorRequest(username, key)); - return ( (RSAPublicKey) publicKey ).getModulus().equals( ( (RSAPublicKey) publicKey ).getModulus() ); - } - catch ( Exception e ) - { - throw new RuntimeException( e.getMessage(), e ); - } - finally - { - IOUtil.close( in ); + return ((RSAPublicKey) publicKey).getModulus().equals(((RSAPublicKey) publicKey).getModulus()); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } finally { + IOUtil.close(in); } } - public static byte[] decrypt( byte[] text, PrivateKey key ) - throws Exception - { + public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception { byte[] dectyptedText = null; - Cipher cipher = Cipher.getInstance( "RSA/ECB/PKCS1Padding" ); - cipher.init( Cipher.DECRYPT_MODE, key ); - dectyptedText = cipher.doFinal( text ); + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.DECRYPT_MODE, key); + dectyptedText = cipher.doFinal(text); return dectyptedText; } /** - * + * */ - public static class PublickeyAuthenticatorRequest - { + public static class PublickeyAuthenticatorRequest { private String username; private PublicKey publicKey; - public PublickeyAuthenticatorRequest( String username, PublicKey publicKey ) - { + public PublickeyAuthenticatorRequest(String username, PublicKey publicKey) { this.username = username; this.publicKey = publicKey; } @Override - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder(); - sb.append( "PublickeyAuthenticatorRequest" ); - sb.append( "{username='" ).append( username ).append( '\'' ); - sb.append( ", publicKey=" ).append( publicKey ); - sb.append( '}' ); + sb.append("PublickeyAuthenticatorRequest"); + sb.append("{username='").append(username).append('\''); + sb.append(", publicKey=").append(publicKey); + sb.append('}'); return sb.toString(); } } @@ -121,71 +105,59 @@ public String toString() private int pos; - public PublicKey decodePublicKey( String keyLine ) - throws Exception - { + public PublicKey decodePublicKey(String keyLine) throws Exception { bytes = null; pos = 0; - for ( String part : keyLine.split( " " ) ) - { - if ( part.startsWith( "AAAA" ) ) - { - bytes = Base64.decodeBase64( part.getBytes() ); + for (String part : keyLine.split(" ")) { + if (part.startsWith("AAAA")) { + bytes = Base64.decodeBase64(part.getBytes()); break; } } - if ( bytes == null ) - { - throw new IllegalArgumentException( "no Base64 part to decode" ); + if (bytes == null) { + throw new IllegalArgumentException("no Base64 part to decode"); } String type = decodeType(); - if ( type.equals( "ssh-rsa" ) ) - { + if (type.equals("ssh-rsa")) { BigInteger e = decodeBigInt(); BigInteger m = decodeBigInt(); - RSAPublicKeySpec spec = new RSAPublicKeySpec( m, e ); - return KeyFactory.getInstance( "RSA" ).generatePublic( spec ); - } - else if ( type.equals( "ssh-dss" ) ) - { + RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e); + return KeyFactory.getInstance("RSA").generatePublic(spec); + } else if (type.equals("ssh-dss")) { BigInteger p = decodeBigInt(); BigInteger q = decodeBigInt(); BigInteger g = decodeBigInt(); BigInteger y = decodeBigInt(); - DSAPublicKeySpec spec = new DSAPublicKeySpec( y, p, q, g ); - return KeyFactory.getInstance( "DSA" ).generatePublic( spec ); - } - else - { - throw new IllegalArgumentException( "unknown type " + type ); + DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g); + return KeyFactory.getInstance("DSA").generatePublic(spec); + } else { + throw new IllegalArgumentException("unknown type " + type); } } - private String decodeType() - { + private String decodeType() { int len = decodeInt(); - String type = new String( bytes, pos, len ); + String type = new String(bytes, pos, len); pos += len; return type; } - private int decodeInt() - { + private int decodeInt() { // CHECKSTYLE_OFF: MagicNumber - return ( ( bytes[pos++] & 0xFF ) << 24 ) | ( ( bytes[pos++] & 0xFF ) << 16 ) | ( ( bytes[pos++] & 0xFF ) << 8 ) - | ( bytes[pos++] & 0xFF ); + return ((bytes[pos++] & 0xFF) << 24) + | ((bytes[pos++] & 0xFF) << 16) + | ((bytes[pos++] & 0xFF) << 8) + | (bytes[pos++] & 0xFF); // CHECKSTYLE_ON: MagicNumber } - private BigInteger decodeBigInt() - { + private BigInteger decodeBigInt() { int len = decodeInt(); byte[] bigIntBytes = new byte[len]; - System.arraycopy( bytes, pos, bigIntBytes, 0, len ); + System.arraycopy(bytes, pos, bigIntBytes, 0, len); pos += len; - return new BigInteger( bigIntBytes ); + return new BigInteger(bigIntBytes); } - } diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProviderTestCase.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProviderTestCase.java index 77bb06731..8616a1872 100644 --- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProviderTestCase.java +++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProviderTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.providers.ssh.SshWagon; @@ -26,11 +25,9 @@ import org.codehaus.plexus.PlexusTestCase; /** - * + * */ -public class KnownHostsProviderTestCase - extends PlexusTestCase -{ +public class KnownHostsProviderTestCase extends PlexusTestCase { protected KnownHostsProvider okHostsProvider; protected KnownHostsProvider failHostsProvider; @@ -44,10 +41,10 @@ public class KnownHostsProviderTestCase private static final String CORRECT_KEY = TestData.getHostKey(); private static final String CHANGED_KEY = - "AAAAB3NzaC1yc2EAAAABIwAAAQEA8VLKkfHl2CNqW+m0603z07dyweWzzdVGQlMPUX4z1264E7M/h+6lPKiOo+u49CL7eQVA+FtW" - + "TZoJ3oBAMABcKnHx41TnSpQUkbdR6rzyC6IG1lXiVtEjG2w7DUnxpCtVo5PaQuJobwoXv5NNL3vx03THPgcDJquLPWvGnDWhnXoEh" - + "3/6c7rprwT+PrjZ6LIT35ZCUGajoehhF151oNbFMQHllfR6EAiZIP0z0nIVI+Jiv6g+XZapumVPVYjdOfxvLKQope1H9HJamT3bDI" - + "m8mkebUB10DzQJYxFt4/0wiNH3L4jsIFn+CiW1/IQm5yyff1CUO87OqVbtp9BlaXZNmw=="; + "AAAAB3NzaC1yc2EAAAABIwAAAQEA8VLKkfHl2CNqW+m0603z07dyweWzzdVGQlMPUX4z1264E7M/h+6lPKiOo+u49CL7eQVA+FtW" + + "TZoJ3oBAMABcKnHx41TnSpQUkbdR6rzyC6IG1lXiVtEjG2w7DUnxpCtVo5PaQuJobwoXv5NNL3vx03THPgcDJquLPWvGnDWhnXoEh" + + "3/6c7rprwT+PrjZ6LIT35ZCUGajoehhF151oNbFMQHllfR6EAiZIP0z0nIVI+Jiv6g+XZapumVPVYjdOfxvLKQope1H9HJamT3bDI" + + "m8mkebUB10DzQJYxFt4/0wiNH3L4jsIFn+CiW1/IQm5yyff1CUO87OqVbtp9BlaXZNmw=="; /** * tests what happens if the remote host has a different key than the one @@ -55,19 +52,14 @@ public class KnownHostsProviderTestCase * * @throws Exception on error */ - public void testIncorrectKey() - throws Exception - { - wagon.setKnownHostsProvider( failHostsProvider ); + public void testIncorrectKey() throws Exception { + wagon.setKnownHostsProvider(failHostsProvider); - try - { - wagon.connect( source ); + try { + wagon.connect(source); - fail( "Should not have successfully connected - host is not known" ); - } - catch ( UnknownHostException e ) - { + fail("Should not have successfully connected - host is not known"); + } catch (UnknownHostException e) { // ok } } @@ -77,19 +69,14 @@ public void testIncorrectKey() * * @throws Exception on error */ - public void testChangedKey() - throws Exception - { - wagon.setKnownHostsProvider( changedHostsProvider ); + public void testChangedKey() throws Exception { + wagon.setKnownHostsProvider(changedHostsProvider); - try - { - wagon.connect( source ); + try { + wagon.connect(source); - fail( "Should not have successfully connected - host is changed" ); - } - catch ( KnownHostChangedException e ) - { + fail("Should not have successfully connected - host is changed"); + } catch (KnownHostChangedException e) { // ok } } @@ -99,28 +86,23 @@ public void testChangedKey() * * @throws Exception on error */ - public void testCorrectKey() - throws Exception - { - wagon.setKnownHostsProvider( okHostsProvider ); + public void testCorrectKey() throws Exception { + wagon.setKnownHostsProvider(okHostsProvider); - wagon.connect( source ); + wagon.connect(source); - assertTrue( true ); + assertTrue(true); } - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - source = - new Repository( "test", "scp://" + TestData.getUserName() + "@" + TestData.getHostname() + "/tmp/foo" ); + source = new Repository("test", "scp://" + TestData.getUserName() + "@" + TestData.getHostname() + "/tmp/foo"); - wagon = (SshWagon) lookup( Wagon.ROLE, "scp" ); - wagon.setInteractive( false ); + wagon = (SshWagon) lookup(Wagon.ROLE, "scp"); + wagon.setInteractive(false); - this.okHostsProvider = new SingleKnownHostProvider( TestData.getHostname(), CORRECT_KEY ); - this.failHostsProvider = new SingleKnownHostProvider( "beaver.codehaus.org", CORRECT_KEY ); - this.changedHostsProvider = new SingleKnownHostProvider( TestData.getHostname(), CHANGED_KEY ); + this.okHostsProvider = new SingleKnownHostProvider(TestData.getHostname(), CORRECT_KEY); + this.failHostsProvider = new SingleKnownHostProvider("beaver.codehaus.org", CORRECT_KEY); + this.changedHostsProvider = new SingleKnownHostProvider(TestData.getHostname(), CHANGED_KEY); } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/CommandExecutorStreamProcessor.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/CommandExecutorStreamProcessor.java index ebd596738..94f8d431d 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/CommandExecutorStreamProcessor.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/CommandExecutorStreamProcessor.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.wagon.providers.ssh; /* @@ -19,68 +37,59 @@ * under the License. */ -import org.apache.maven.wagon.Streams; - import java.io.BufferedReader; import java.io.IOException; +import org.apache.maven.wagon.Streams; + /** * CommandExecutorStreamProcessor * * @author Joakim Erdfelt * */ -public class CommandExecutorStreamProcessor -{ - private CommandExecutorStreamProcessor() - { +public class CommandExecutorStreamProcessor { + private CommandExecutorStreamProcessor() { // shoo! } - public static Streams processStreams( BufferedReader stderrReader, BufferedReader stdoutReader ) - throws IOException - { + public static Streams processStreams(BufferedReader stderrReader, BufferedReader stdoutReader) throws IOException { Streams streams = new Streams(); - while ( true ) - { + while (true) { String line = stdoutReader.readLine(); - if ( line == null ) - { + if (line == null) { break; } - streams.setOut( streams.getOut() + line + "\n" ); + streams.setOut(streams.getOut() + line + "\n"); } // drain the output stream. // TODO: we'll save this for the 1.0-alpha-8 line, so we can test it more. the -q arg in the // unzip command should keep us until then... -// int avail = in.available(); -// byte[] trashcan = new byte[1024]; -// -// while( ( avail = in.available() ) > 0 ) -// { -// in.read( trashcan, 0, avail ); -// } + // int avail = in.available(); + // byte[] trashcan = new byte[1024]; + // + // while( ( avail = in.available() ) > 0 ) + // { + // in.read( trashcan, 0, avail ); + // } // drain stderr next, if stream size is more than the allowed buffer size // ( ie jsch has a hardcoded 32K size), the remote shell may be blocked. See WAGON-431 - while ( true ) - { + while (true) { String line = stderrReader.readLine(); - if ( line == null ) - { + if (line == null) { break; } // TODO: I think we need to deal with exit codes instead, but IIRC there are some cases of errors that // don't have exit codes ignore this error. TODO: output a warning - if ( !line.startsWith( "Could not chdir to home directory" ) - && !line.endsWith( "ttyname: Operation not supported" ) ) - { - streams.setErr( streams.getErr() + line + "\n" ); + if (!line.startsWith("Could not chdir to home directory") + && !line.endsWith("ttyname: Operation not supported")) { + streams.setErr(streams.getErr() + line + "\n"); } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/LSParser.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/LSParser.java index 3c189a36b..1c194aea3 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/LSParser.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/LSParser.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.TransferFailedException; +package org.apache.maven.wagon.providers.ssh; import java.io.BufferedReader; import java.io.IOException; @@ -29,14 +26,15 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.maven.wagon.TransferFailedException; + /** * Parser for the output of ls command from any ssh server on any OS. * * @author Joakim Erdfelt * */ -public class LSParser -{ +public class LSParser { /** * output samples see LSParserTest: *
    @@ -46,15 +44,15 @@ public class LSParser *
  • linux : "-rw-r--r-- 1 joakim joakim 1194 2006-12-11 09:25 pom.xml"
  • * */ - private static final Pattern PATTERN = Pattern.compile( ".+\\s+[0-9]+\\s+.+\\s+.+\\s+[0-9]+\\s+" - //2006-12-11 - + "([0-9]{4}-[0-9]{2}-[0-9]{2}" - // Dec 11 - + "|.+\\s+[0-9]+" - // 21 sep - + "|.+\\s+.+)" - // 09:25 pom.xml - + "\\s+[0-9:]+\\s+(.+?)" ); + private static final Pattern PATTERN = Pattern.compile(".+\\s+[0-9]+\\s+.+\\s+.+\\s+[0-9]+\\s+" + // 2006-12-11 + + "([0-9]{4}-[0-9]{2}-[0-9]{2}" + // Dec 11 + + "|.+\\s+[0-9]+" + // 21 sep + + "|.+\\s+.+)" + // 09:25 pom.xml + + "\\s+[0-9:]+\\s+(.+?)"); /** * Parse a raw "ls -FlA", and obtain the list of files. @@ -64,31 +62,24 @@ public class LSParser * @throws TransferFailedException * @todo use ls -1a and do away with the method all together */ - public List parseFiles( String rawLS ) - throws TransferFailedException - { + public List parseFiles(String rawLS) throws TransferFailedException { List ret = new ArrayList<>(); - try - { - BufferedReader br = new BufferedReader( new StringReader( rawLS ) ); + try { + BufferedReader br = new BufferedReader(new StringReader(rawLS)); String line = br.readLine(); - while ( line != null ) - { + while (line != null) { line = line.trim(); - Matcher m = PATTERN.matcher( line ); - if ( m.matches() ) - { - ret.add( m.group( 2 ) ); + Matcher m = PATTERN.matcher(line); + if (m.matches()) { + ret.add(m.group(2)); } line = br.readLine(); } - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error parsing file listing.", e ); + } catch (IOException e) { + throw new TransferFailedException("Error parsing file listing.", e); } return ret; diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/ScpHelper.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/ScpHelper.java index 4deaae62b..7d691cbcb 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/ScpHelper.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/ScpHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import org.apache.maven.wagon.CommandExecutionException; import org.apache.maven.wagon.CommandExecutor; @@ -36,107 +44,77 @@ import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - /** * Scp helper for general algorithms on ssh server. * See {@link #putDirectory(Wagon, File, String) putDirectory(...)} for more info on bulk directory upload. */ -public class ScpHelper -{ +public class ScpHelper { public static final char PATH_SEPARATOR = '/'; public static final int DEFAULT_SSH_PORT = 22; private final CommandExecutor executor; - public ScpHelper( CommandExecutor executor ) - { + public ScpHelper(CommandExecutor executor) { this.executor = executor; } - public static String getResourceDirectory( String resourceName ) - { - String dir = PathUtils.dirname( resourceName ); - dir = StringUtils.replace( dir, "\\", "/" ); + public static String getResourceDirectory(String resourceName) { + String dir = PathUtils.dirname(resourceName); + dir = StringUtils.replace(dir, "\\", "/"); return dir; } - public static String getResourceFilename( String r ) - { + public static String getResourceFilename(String r) { String filename; - if ( r.lastIndexOf( PATH_SEPARATOR ) > 0 ) - { - filename = r.substring( r.lastIndexOf( PATH_SEPARATOR ) + 1 ); - } - else - { + if (r.lastIndexOf(PATH_SEPARATOR) > 0) { + filename = r.substring(r.lastIndexOf(PATH_SEPARATOR) + 1); + } else { filename = r; } return filename; } - public static Resource getResource( String resourceName ) - { - String r = StringUtils.replace( resourceName, "\\", "/" ); - return new Resource( r ); + public static Resource getResource(String resourceName) { + String r = StringUtils.replace(resourceName, "\\", "/"); + return new Resource(r); } - public static File getPrivateKey( AuthenticationInfo authenticationInfo ) - throws FileNotFoundException - { + public static File getPrivateKey(AuthenticationInfo authenticationInfo) throws FileNotFoundException { // If user don't define a password, he want to use a private key File privateKey = null; - if ( authenticationInfo.getPassword() == null ) - { - - if ( authenticationInfo.getPrivateKey() != null ) - { - privateKey = new File( authenticationInfo.getPrivateKey() ); - if ( !privateKey.exists() ) - { - throw new FileNotFoundException( "Private key '" + privateKey + "' not found" ); + if (authenticationInfo.getPassword() == null) { + + if (authenticationInfo.getPrivateKey() != null) { + privateKey = new File(authenticationInfo.getPrivateKey()); + if (!privateKey.exists()) { + throw new FileNotFoundException("Private key '" + privateKey + "' not found"); } - } - else - { + } else { privateKey = findPrivateKey(); } - if ( privateKey != null && privateKey.exists() ) - { - if ( authenticationInfo.getPassphrase() == null ) - { - authenticationInfo.setPassphrase( "" ); + if (privateKey != null && privateKey.exists()) { + if (authenticationInfo.getPassphrase() == null) { + authenticationInfo.setPassphrase(""); } } } return privateKey; } - private static File findPrivateKey() - { - String privateKeyDirectory = System.getProperty( "wagon.privateKeyDirectory" ); + private static File findPrivateKey() { + String privateKeyDirectory = System.getProperty("wagon.privateKeyDirectory"); - if ( privateKeyDirectory == null ) - { - privateKeyDirectory = System.getProperty( "user.home" ); + if (privateKeyDirectory == null) { + privateKeyDirectory = System.getProperty("user.home"); } - File privateKey = new File( privateKeyDirectory, ".ssh/id_dsa" ); + File privateKey = new File(privateKeyDirectory, ".ssh/id_dsa"); - if ( !privateKey.exists() ) - { - privateKey = new File( privateKeyDirectory, ".ssh/id_rsa" ); - if ( !privateKey.exists() ) - { + if (!privateKey.exists()) { + privateKey = new File(privateKeyDirectory, ".ssh/id_rsa"); + if (!privateKey.exists()) { privateKey = null; } } @@ -144,62 +122,48 @@ private static File findPrivateKey() return privateKey; } - public static void createZip( List files, File zipName, File basedir ) - throws IOException - { + public static void createZip(List files, File zipName, File basedir) throws IOException { ZipOutputStream zos = null; - try - { - zos = new ZipOutputStream( new FileOutputStream( zipName ) ); + try { + zos = new ZipOutputStream(new FileOutputStream(zipName)); - for ( String file : files ) - { - file = file.replace( '\\', '/' ); + for (String file : files) { + file = file.replace('\\', '/'); - writeZipEntry( zos, new File( basedir, file ), file ); + writeZipEntry(zos, new File(basedir, file), file); } zos.close(); zos = null; - } - finally - { - IOUtil.close( zos ); + } finally { + IOUtil.close(zos); } } - private static void writeZipEntry( ZipOutputStream jar, File source, String entryName ) - throws IOException - { + private static void writeZipEntry(ZipOutputStream jar, File source, String entryName) throws IOException { byte[] buffer = new byte[1024]; int bytesRead; - FileInputStream is = new FileInputStream( source ); + FileInputStream is = new FileInputStream(source); - try - { - ZipEntry entry = new ZipEntry( entryName ); + try { + ZipEntry entry = new ZipEntry(entryName); - jar.putNextEntry( entry ); + jar.putNextEntry(entry); - while ( ( bytesRead = is.read( buffer ) ) != -1 ) - { - jar.write( buffer, 0, bytesRead ); + while ((bytesRead = is.read(buffer)) != -1) { + jar.write(buffer, 0, bytesRead); } - } - finally - { + } finally { is.close(); } } - protected static String getPath( String basedir, String dir ) - { + protected static String getPath(String basedir, String dir) { String path; path = basedir; - if ( !basedir.endsWith( "/" ) && !dir.startsWith( "/" ) ) - { + if (!basedir.endsWith("/") && !dir.startsWith("/")) { path += "/"; } path += dir; @@ -210,156 +174,125 @@ protected static String getPath( String basedir, String dir ) * Put a whole directory content, by transferring a unique zip file and uncompressing it * on the target ssh server with unzip command. */ - public void putDirectory( Wagon wagon, File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public void putDirectory(Wagon wagon, File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Repository repository = wagon.getRepository(); String basedir = repository.getBasedir(); - String destDir = StringUtils.replace( destinationDirectory, "\\", "/" ); + String destDir = StringUtils.replace(destinationDirectory, "\\", "/"); - String path = getPath( basedir, destDir ); - try - { - if ( repository.getPermissions() != null ) - { + String path = getPath(basedir, destDir); + try { + if (repository.getPermissions() != null) { String dirPerms = repository.getPermissions().getDirectoryMode(); - if ( dirPerms != null ) - { - String umaskCmd = "umask " + PermissionModeUtils.getUserMaskFor( dirPerms ); - executor.executeCommand( umaskCmd ); + if (dirPerms != null) { + String umaskCmd = "umask " + PermissionModeUtils.getUserMaskFor(dirPerms); + executor.executeCommand(umaskCmd); } } - //String mkdirCmd = "mkdir -p " + path; + // String mkdirCmd = "mkdir -p " + path; String mkdirCmd = "mkdir -p \"" + path + "\""; - executor.executeCommand( mkdirCmd ); - } - catch ( CommandExecutionException e ) - { - throw new TransferFailedException( "Error performing commands for file transfer", e ); + executor.executeCommand(mkdirCmd); + } catch (CommandExecutionException e) { + throw new TransferFailedException("Error performing commands for file transfer", e); } File zipFile; - try - { - zipFile = File.createTempFile( "wagon", ".zip" ); + try { + zipFile = File.createTempFile("wagon", ".zip"); zipFile.deleteOnExit(); - List files = FileUtils.getFileNames( sourceDirectory, "**/**", "", false ); + List files = FileUtils.getFileNames(sourceDirectory, "**/**", "", false); - createZip( files, zipFile, sourceDirectory ); - } - catch ( IOException e ) - { - throw new TransferFailedException( "Unable to create ZIP archive of directory", e ); + createZip(files, zipFile, sourceDirectory); + } catch (IOException e) { + throw new TransferFailedException("Unable to create ZIP archive of directory", e); } - wagon.put( zipFile, getPath( destDir, zipFile.getName() ) ); + wagon.put(zipFile, getPath(destDir, zipFile.getName())); - try - { - //executor.executeCommand( + try { + // executor.executeCommand( // "cd " + path + "; unzip -q -o " + zipFile.getName() + "; rm -f " + zipFile.getName() ); - executor.executeCommand( "cd \"" + path + "\"; unzip -q -o \"" + zipFile.getName() + "\"; rm -f \"" - + zipFile.getName() + "\"" ); + executor.executeCommand("cd \"" + path + "\"; unzip -q -o \"" + zipFile.getName() + "\"; rm -f \"" + + zipFile.getName() + "\""); zipFile.delete(); RepositoryPermissions permissions = repository.getPermissions(); - if ( permissions != null && permissions.getGroup() != null ) - { - //executor.executeCommand( "chgrp -Rf " + permissions.getGroup() + " " + path ); - executor.executeCommand( "chgrp -Rf " + permissions.getGroup() + " \"" + path + "\"" ); + if (permissions != null && permissions.getGroup() != null) { + // executor.executeCommand( "chgrp -Rf " + permissions.getGroup() + " " + path ); + executor.executeCommand("chgrp -Rf " + permissions.getGroup() + " \"" + path + "\""); } - if ( permissions != null && permissions.getFileMode() != null ) - { - //executor.executeCommand( "chmod -Rf " + permissions.getFileMode() + " " + path ); - executor.executeCommand( "chmod -Rf " + permissions.getFileMode() + " \"" + path + "\"" ); + if (permissions != null && permissions.getFileMode() != null) { + // executor.executeCommand( "chmod -Rf " + permissions.getFileMode() + " " + path ); + executor.executeCommand("chmod -Rf " + permissions.getFileMode() + " \"" + path + "\""); } - } - catch ( CommandExecutionException e ) - { - throw new TransferFailedException( "Error performing commands for file transfer", e ); + } catch (CommandExecutionException e) { + throw new TransferFailedException("Error performing commands for file transfer", e); } } - public List getFileList( String destinationDirectory, Repository repository ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - try - { - String path = getPath( repository.getBasedir(), destinationDirectory ); - //Streams streams = executor.executeCommand( "ls -FlA " + path, false ); - Streams streams = executor.executeCommand( "ls -FlA \"" + path + "\"", false ); - - return new LSParser().parseFiles( streams.getOut() ); - } - catch ( CommandExecutionException e ) - { - if ( e.getMessage().trim().endsWith( "No such file or directory" ) ) - { - throw new ResourceDoesNotExistException( e.getMessage().trim(), e ); - } - else if ( e.getMessage().trim().endsWith( "Not a directory" ) ) - { - throw new ResourceDoesNotExistException( e.getMessage().trim(), e ); - } - else - { - throw new TransferFailedException( "Error performing file listing.", e ); + public List getFileList(String destinationDirectory, Repository repository) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + try { + String path = getPath(repository.getBasedir(), destinationDirectory); + // Streams streams = executor.executeCommand( "ls -FlA " + path, false ); + Streams streams = executor.executeCommand("ls -FlA \"" + path + "\"", false); + + return new LSParser().parseFiles(streams.getOut()); + } catch (CommandExecutionException e) { + if (e.getMessage().trim().endsWith("No such file or directory")) { + throw new ResourceDoesNotExistException(e.getMessage().trim(), e); + } else if (e.getMessage().trim().endsWith("Not a directory")) { + throw new ResourceDoesNotExistException(e.getMessage().trim(), e); + } else { + throw new TransferFailedException("Error performing file listing.", e); } } } - public boolean resourceExists( String resourceName, Repository repository ) - throws TransferFailedException, AuthorizationException - { - try - { - String path = getPath( repository.getBasedir(), resourceName ); - //executor.executeCommand( "ls " + path, false ); - executor.executeCommand( "ls \"" + path + "\"" ); + public boolean resourceExists(String resourceName, Repository repository) + throws TransferFailedException, AuthorizationException { + try { + String path = getPath(repository.getBasedir(), resourceName); + // executor.executeCommand( "ls " + path, false ); + executor.executeCommand("ls \"" + path + "\""); // Parsing of output not really needed. As a failed ls results in a // CommandExectionException on the 'ls' command. return true; - } - catch ( CommandExecutionException e ) - { + } catch (CommandExecutionException e) { // Error? Then the 'ls' command failed. No such file found. return false; } } - public void createRemoteDirectories( String path, RepositoryPermissions permissions ) - throws CommandExecutionException - { + public void createRemoteDirectories(String path, RepositoryPermissions permissions) + throws CommandExecutionException { String umaskCmd = null; - if ( permissions != null ) - { + if (permissions != null) { String dirPerms = permissions.getDirectoryMode(); - if ( dirPerms != null ) - { - umaskCmd = "umask " + PermissionModeUtils.getUserMaskFor( dirPerms ); + if (dirPerms != null) { + umaskCmd = "umask " + PermissionModeUtils.getUserMaskFor(dirPerms); } } - //String mkdirCmd = "mkdir -p " + path; + // String mkdirCmd = "mkdir -p " + path; String mkdirCmd = "mkdir -p \"" + path + "\""; - if ( umaskCmd != null ) - { + if (umaskCmd != null) { mkdirCmd = umaskCmd + "; " + mkdirCmd; } - executor.executeCommand( mkdirCmd ); + executor.executeCommand(mkdirCmd); } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/SshWagon.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/SshWagon.java index 16a38cbd5..e9cefe2dc 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/SshWagon.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/SshWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,20 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider; /** * SshWagon - identifier for 100% java implementations of Ssh. - * + * * NOTE: External or native ssh implementations cannot use this interface. * * @author Joakim Erdfelt * */ -public interface SshWagon - extends Wagon -{ - void setKnownHostsProvider( KnownHostsProvider knownHostsProvider ); +public interface SshWagon extends Wagon { + void setKnownHostsProvider(KnownHostsProvider knownHostsProvider); } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/ConsoleInteractiveUserInfo.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/ConsoleInteractiveUserInfo.java index a1048109b..ee1f3a998 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/ConsoleInteractiveUserInfo.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/ConsoleInteractiveUserInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.interactive; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,85 +16,68 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.interactive; + +import java.util.Arrays; import org.codehaus.plexus.components.interactivity.Prompter; import org.codehaus.plexus.components.interactivity.PrompterException; -import java.util.Arrays; - /** * Shows messages to System.out, and ask replies using an InputHandler * * @author Juan F. Codagnone * @since Sep 12, 2005 - * + * * @plexus.component role="org.apache.maven.wagon.providers.ssh.interactive.InteractiveUserInfo" * instantiation-strategy="per-lookup" */ -public class ConsoleInteractiveUserInfo - implements InteractiveUserInfo -{ +public class ConsoleInteractiveUserInfo implements InteractiveUserInfo { /** * @plexus.requirement role-hint="default" */ private volatile Prompter prompter; - public ConsoleInteractiveUserInfo() - { - } + public ConsoleInteractiveUserInfo() {} - public ConsoleInteractiveUserInfo( Prompter prompter ) - { + public ConsoleInteractiveUserInfo(Prompter prompter) { this.prompter = prompter; } /** * @see InteractiveUserInfo#promptYesNo(String) */ - public boolean promptYesNo( String message ) - { + public boolean promptYesNo(String message) { String ret; - try - { - ret = prompter.prompt( message, Arrays.asList( "yes", "no" ) ); - } - catch ( PrompterException e ) - { + try { + ret = prompter.prompt(message, Arrays.asList("yes", "no")); + } catch (PrompterException e) { // no op ret = null; } - return "yes".equalsIgnoreCase( ret ); + return "yes".equalsIgnoreCase(ret); } /** * @see InteractiveUserInfo#showMessage(String) */ - public void showMessage( String message ) - { - try - { - prompter.showMessage( message ); - } - catch ( PrompterException e ) - { + public void showMessage(String message) { + try { + prompter.showMessage(message); + } catch (PrompterException e) { // no op } } - public String promptPassword( String message ) - { - try - { - return prompter.promptForPassword( message ); - } - catch ( PrompterException e ) - { + public String promptPassword(String message) { + try { + return prompter.promptForPassword(message); + } catch (PrompterException e) { return null; } } - public String promptPassphrase( String message ) - { - return promptPassword( message ); + public String promptPassphrase(String message) { + return promptPassword(message); } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/InteractiveUserInfo.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/InteractiveUserInfo.java index e9c4e9264..7d42c012e 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/InteractiveUserInfo.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/InteractiveUserInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.interactive; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.interactive; /** * Interactive part for UserInfo @@ -26,15 +25,14 @@ * @see com.jcraft.jsch.UserInfo * @since Sep 12, 2005 */ -public interface InteractiveUserInfo -{ +public interface InteractiveUserInfo { String ROLE = InteractiveUserInfo.class.getName(); - boolean promptYesNo( String message ); + boolean promptYesNo(String message); - void showMessage( String message ); + void showMessage(String message); - String promptPassword( String message ); + String promptPassword(String message); - String promptPassphrase( String message ); + String promptPassphrase(String message); } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/NullInteractiveUserInfo.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/NullInteractiveUserInfo.java index 7a1b887b5..a3c97d41d 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/NullInteractiveUserInfo.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/interactive/NullInteractiveUserInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.interactive; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.interactive; /** * Dummy Implementation for InteractiveUserInfo, nice for @@ -27,17 +26,14 @@ * @see org.apache.maven.wagon.providers.ssh.interactive.InteractiveUserInfo * @since Sep 12, 2005 */ -public class NullInteractiveUserInfo - implements InteractiveUserInfo -{ +public class NullInteractiveUserInfo implements InteractiveUserInfo { private final boolean promptYesNoResult; /** * @see #NullInteractiveUserInfo(boolean) */ - public NullInteractiveUserInfo() - { - this( false ); // the safest value + public NullInteractiveUserInfo() { + this(false); // the safest value } /** @@ -46,34 +42,29 @@ public NullInteractiveUserInfo() * * @param promptYesNoResult the hardcoded result */ - public NullInteractiveUserInfo( final boolean promptYesNoResult ) - { + public NullInteractiveUserInfo(final boolean promptYesNoResult) { this.promptYesNoResult = promptYesNoResult; } /** * @see InteractiveUserInfo#promptYesNo(java.lang.String) */ - public boolean promptYesNo( final String message ) - { + public boolean promptYesNo(final String message) { return promptYesNoResult; } /** * @see InteractiveUserInfo#showMessage(java.lang.String) */ - public void showMessage( final String message ) - { + public void showMessage(final String message) { // nothing to do } - public String promptPassword( String message ) - { + public String promptPassword(String message) { return null; } - public String promptPassphrase( String message ) - { + public String promptPassphrase(String message) { return null; } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/AbstractKnownHostsProvider.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/AbstractKnownHostsProvider.java index 4a2e0b961..00e5a017a 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/AbstractKnownHostsProvider.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/AbstractKnownHostsProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import java.io.IOException; import java.util.HashSet; @@ -29,9 +28,7 @@ * @author Brett Porter * */ -public abstract class AbstractKnownHostsProvider - implements KnownHostsProvider -{ +public abstract class AbstractKnownHostsProvider implements KnownHostsProvider { /** * Valid values are ask, yes, no. * @@ -46,30 +43,19 @@ public abstract class AbstractKnownHostsProvider protected Set knownHosts = new HashSet<>(); - public void setHostKeyChecking( String hostKeyChecking ) - { + public void setHostKeyChecking(String hostKeyChecking) { this.hostKeyChecking = hostKeyChecking; } - public String getHostKeyChecking() - { + public String getHostKeyChecking() { return hostKeyChecking; } - public String getContents() - { + public String getContents() { return contents; } - public void storeKnownHosts( String contents ) - throws IOException - { - } - - public void addKnownHost( KnownHostEntry knownHost ) - throws IOException - { - } - + public void storeKnownHosts(String contents) throws IOException {} + public void addKnownHost(KnownHostEntry knownHost) throws IOException {} } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProvider.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProvider.java index 48ab25062..3c7578149 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProvider.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import java.io.ByteArrayInputStream; import java.io.File; @@ -38,9 +37,7 @@ * role-hint="file" * instantiation-strategy="per-lookup" */ -public class FileKnownHostsProvider - extends StreamKnownHostsProvider -{ +public class FileKnownHostsProvider extends StreamKnownHostsProvider { private final File file; /** @@ -49,10 +46,8 @@ public class FileKnownHostsProvider * @param file the file that holds the known hosts, in the openssh format * @throws IOException */ - public FileKnownHostsProvider( File file ) - throws IOException - { - super( file.exists() ? (InputStream) new FileInputStream( file ) : new ByteArrayInputStream( "".getBytes() ) ); + public FileKnownHostsProvider(File file) throws IOException { + super(file.exists() ? (InputStream) new FileInputStream(file) : new ByteArrayInputStream("".getBytes())); this.file = file; } @@ -62,38 +57,29 @@ public FileKnownHostsProvider( File file ) * @throws IOException * @see #FileKnownHostsProvider(File) */ - public FileKnownHostsProvider() - throws IOException - { - this( new File( System.getProperty( "user.home" ), ".ssh/known_hosts" ) ); + public FileKnownHostsProvider() throws IOException { + this(new File(System.getProperty("user.home"), ".ssh/known_hosts")); } - public void storeKnownHosts( String contents ) - throws IOException - { - Set hosts = this.loadKnownHosts( contents ); + public void storeKnownHosts(String contents) throws IOException { + Set hosts = this.loadKnownHosts(contents); - if ( ! this.knownHosts.equals( hosts ) ) - { + if (!this.knownHosts.equals(hosts)) { file.getParentFile().mkdirs(); - FileUtils.fileWrite( file.getAbsolutePath(), contents ); + FileUtils.fileWrite(file.getAbsolutePath(), contents); this.knownHosts = hosts; } } - public void addKnownHost( KnownHostEntry knownHostEntry ) - throws IOException - { - if ( !this.knownHosts.contains( knownHostEntry ) ) - { + public void addKnownHost(KnownHostEntry knownHostEntry) throws IOException { + if (!this.knownHosts.contains(knownHostEntry)) { String knownHost = knownHostEntry.getHostName() + " " + knownHostEntry.getKeyType() + " " - + knownHostEntry.getKeyValue() + "\n"; - FileUtils.fileAppend( file.getAbsolutePath(), knownHost ); + + knownHostEntry.getKeyValue() + "\n"; + FileUtils.fileAppend(file.getAbsolutePath(), knownHost); } } - public File getFile() - { + public File getFile() { return file; } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostChangedException.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostChangedException.java index f33499259..3040d8fd1 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostChangedException.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostChangedException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import org.apache.maven.wagon.authentication.AuthenticationException; /** * Exception related to known_host check failures. */ -public class KnownHostChangedException - extends AuthenticationException -{ - public KnownHostChangedException( String host, Throwable cause ) - { - super( "The host key was different to that in the known_hosts configuration for host: " + host, cause ); +public class KnownHostChangedException extends AuthenticationException { + public KnownHostChangedException(String host, Throwable cause) { + super("The host key was different to that in the known_hosts configuration for host: " + host, cause); } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostEntry.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostEntry.java index 35df9a734..c186bb244 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostEntry.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostEntry.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; /** - * + * */ -public class KnownHostEntry -{ +public class KnownHostEntry { private String hostName; @@ -31,111 +29,84 @@ public class KnownHostEntry private String keyValue; - public KnownHostEntry() - { - } + public KnownHostEntry() {} - public KnownHostEntry( String hostName, String keyType, String keyValue ) - { + public KnownHostEntry(String hostName, String keyType, String keyValue) { this.hostName = hostName; this.keyType = keyType; this.keyValue = keyValue; } - public String getHostName() - { + public String getHostName() { return hostName; } - public void setHostName( String hostName ) - { + public void setHostName(String hostName) { this.hostName = hostName; } - public String getKeyType() - { + public String getKeyType() { return keyType; } - public void setKeyType( String keyType ) - { + public void setKeyType(String keyType) { this.keyType = keyType; } - public String getKeyValue() - { + public String getKeyValue() { return keyValue; } - public void setKeyValue( String keyValue ) - { + public void setKeyValue(String keyValue) { this.keyValue = keyValue; } - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( ( hostName == null ) ? 0 : hostName.hashCode() ); - result = prime * result + ( ( keyType == null ) ? 0 : keyType.hashCode() ); - result = prime * result + ( ( keyValue == null ) ? 0 : keyValue.hashCode() ); + result = prime * result + ((hostName == null) ? 0 : hostName.hashCode()); + result = prime * result + ((keyType == null) ? 0 : keyType.hashCode()); + result = prime * result + ((keyValue == null) ? 0 : keyValue.hashCode()); return result; } - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } KnownHostEntry other = (KnownHostEntry) obj; - if ( hostName == null ) - { - if ( other.hostName != null ) - { + if (hostName == null) { + if (other.hostName != null) { return false; } - } - else if ( !hostName.equals( other.hostName ) ) - { + } else if (!hostName.equals(other.hostName)) { return false; } - if ( keyType == null ) - { - if ( other.keyType != null ) - { + if (keyType == null) { + if (other.keyType != null) { return false; } - } - else if ( !keyType.equals( other.keyType ) ) - { + } else if (!keyType.equals(other.keyType)) { return false; } - if ( keyValue == null ) - { - if ( other.keyValue != null ) - { + if (keyValue == null) { + if (other.keyValue != null) { return false; } - } - else if ( !keyValue.equals( other.keyValue ) ) - { + } else if (!keyValue.equals(other.keyValue)) { return false; } return true; } - } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProvider.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProvider.java index abaebefdb..67bf9d1cd 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProvider.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/KnownHostsProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import java.io.IOException; @@ -27,17 +26,14 @@ * @author Juan F. Codagnone * @since Sep 12, 2005 */ -public interface KnownHostsProvider -{ +public interface KnownHostsProvider { String ROLE = KnownHostsProvider.class.getName(); - void storeKnownHosts( String contents ) - throws IOException; + void storeKnownHosts(String contents) throws IOException; - void addKnownHost( KnownHostEntry knownHost ) - throws IOException; + void addKnownHost(KnownHostEntry knownHost) throws IOException; - void setHostKeyChecking( String hostKeyChecking ); + void setHostKeyChecking(String hostKeyChecking); String getHostKeyChecking(); diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/NullKnownHostProvider.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/NullKnownHostProvider.java index e3a3fc41e..462485109 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/NullKnownHostProvider.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/NullKnownHostProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,18 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; /** * Dummy KnownHostsProvider * * @author Juan F. Codagnone * @since Sep 12, 2005 - * + * * @plexus.component role="org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider" * role-hint="null" * instantiation-strategy="per-lookup" */ -public final class NullKnownHostProvider - extends AbstractKnownHostsProvider -{ -} +public final class NullKnownHostProvider extends AbstractKnownHostsProvider {} diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/SingleKnownHostProvider.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/SingleKnownHostProvider.java index f7d8c915f..229b4e057 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/SingleKnownHostProvider.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/SingleKnownHostProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; /** * Simple KnownHostsProvider with known wired values @@ -25,22 +24,17 @@ * @plexus.component role="org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider" * role-hint="single" * instantiation-strategy="per-lookup" - * + * * @author Juan F. Codagnone * @since Sep 12, 2005 */ -public class SingleKnownHostProvider - extends AbstractKnownHostsProvider -{ - public SingleKnownHostProvider() - { - } - +public class SingleKnownHostProvider extends AbstractKnownHostsProvider { + public SingleKnownHostProvider() {} + /** * Creates the SingleKnownHostProvider. */ - public SingleKnownHostProvider( String host, String key ) - { + public SingleKnownHostProvider(String host, String key) { this.contents = host + " ssh-rsa " + key + "\n"; } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/StreamKnownHostsProvider.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/StreamKnownHostsProvider.java index 478d27363..4706c4546 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/StreamKnownHostsProvider.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/StreamKnownHostsProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import java.io.BufferedReader; import java.io.IOException; @@ -36,55 +35,42 @@ * @author Juan F. Codagnone * @since Sep 12, 2005 */ -public class StreamKnownHostsProvider - extends AbstractKnownHostsProvider -{ +public class StreamKnownHostsProvider extends AbstractKnownHostsProvider { - public StreamKnownHostsProvider( InputStream stream ) - throws IOException - { - try - { + public StreamKnownHostsProvider(InputStream stream) throws IOException { + try { StringOutputStream stringOutputStream = new StringOutputStream(); - IOUtil.copy( stream, stringOutputStream ); + IOUtil.copy(stream, stringOutputStream); stream.close(); stream = null; this.contents = stringOutputStream.toString(); - - this.knownHosts = this.loadKnownHosts( this.contents ); - } - finally - { - IOUtil.close( stream ); + + this.knownHosts = this.loadKnownHosts(this.contents); + } finally { + IOUtil.close(stream); } } - - protected Set loadKnownHosts( String contents ) - throws IOException - { + + protected Set loadKnownHosts(String contents) throws IOException { Set hosts = new HashSet<>(); - - BufferedReader br = new BufferedReader( new StringReader( contents ) ); - + + BufferedReader br = new BufferedReader(new StringReader(contents)); + String line; - - do - { + + do { line = br.readLine(); - if ( line != null ) - { - String tokens[] = StringUtils.split( line ); - if ( tokens.length == 3 ) - { - hosts.add( new KnownHostEntry( tokens[0], tokens[1], tokens[2] ) ); + if (line != null) { + String tokens[] = StringUtils.split(line); + if (tokens.length == 3) { + hosts.add(new KnownHostEntry(tokens[0], tokens[1], tokens[2])); } } - - } - while ( line != null ); - + + } while (line != null); + return hosts; } } diff --git a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/UnknownHostException.java b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/UnknownHostException.java index 3aaed46ae..0c55eaf6b 100644 --- a/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/UnknownHostException.java +++ b/wagon-providers/wagon-ssh-common/src/main/java/org/apache/maven/wagon/providers/ssh/knownhost/UnknownHostException.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import org.apache.maven.wagon.authentication.AuthenticationException; /** * Exception related to known_host check failures. */ -public class UnknownHostException - extends AuthenticationException -{ - public UnknownHostException( String host, Throwable cause ) - { - super( "The host was not known and was not accepted by the configuration: " + host, cause ); +public class UnknownHostException extends AuthenticationException { + public UnknownHostException(String host, Throwable cause) { + super("The host was not known and was not accepted by the configuration: " + host, cause); } } diff --git a/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/LSParserTest.java b/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/LSParserTest.java index 95e328902..2f4541bca 100644 --- a/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/LSParserTest.java +++ b/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/LSParserTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,93 +16,84 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.wagon.TransferFailedException; +package org.apache.maven.wagon.providers.ssh; import java.util.List; import junit.framework.TestCase; +import org.apache.maven.wagon.TransferFailedException; -public class LSParserTest - extends TestCase -{ - public void testParseLinux() - throws TransferFailedException - { +public class LSParserTest extends TestCase { + public void testParseLinux() throws TransferFailedException { String rawLS = "total 32\n" + "drwxr-xr-x 5 joakim joakim 4096 2006-12-11 10:30 .\n" - + "drwxr-xr-x 14 joakim joakim 4096 2006-12-11 10:30 ..\n" - + "-rw-r--r-- 1 joakim joakim 320 2006-12-09 18:46 .classpath\n" - + "-rw-r--r-- 1 joakim joakim 1194 2006-12-11 09:25 pom.xml\n" - + "-rw-r--r-- 1 joakim joakim 662 2006-12-09 18:46 .project\n" - + "drwxr-xr-x 4 joakim joakim 4096 2006-11-21 12:26 src\n" - + "drwxr-xr-x 4 joakim joakim 4096 2006-11-21 12:26 spaced out\n" - + "drwxr-xr-x 7 joakim joakim 4096 2006-12-11 10:31 .svn\n" - + "drwxr-xr-x 3 joakim joakim 4096 2006-12-11 08:39 target\n"; + + "drwxr-xr-x 14 joakim joakim 4096 2006-12-11 10:30 ..\n" + + "-rw-r--r-- 1 joakim joakim 320 2006-12-09 18:46 .classpath\n" + + "-rw-r--r-- 1 joakim joakim 1194 2006-12-11 09:25 pom.xml\n" + + "-rw-r--r-- 1 joakim joakim 662 2006-12-09 18:46 .project\n" + + "drwxr-xr-x 4 joakim joakim 4096 2006-11-21 12:26 src\n" + + "drwxr-xr-x 4 joakim joakim 4096 2006-11-21 12:26 spaced out\n" + + "drwxr-xr-x 7 joakim joakim 4096 2006-12-11 10:31 .svn\n" + + "drwxr-xr-x 3 joakim joakim 4096 2006-12-11 08:39 target\n"; LSParser parser = new LSParser(); - List files = parser.parseFiles( rawLS ); - assertNotNull( files ); - assertEquals( 9, files.size() ); - assertTrue( files.contains( "pom.xml" ) ); - assertTrue( files.contains( "spaced out" ) ); + List files = parser.parseFiles(rawLS); + assertNotNull(files); + assertEquals(9, files.size()); + assertTrue(files.contains("pom.xml")); + assertTrue(files.contains("spaced out")); } - public void testParseOSX() throws TransferFailedException - { + public void testParseOSX() throws TransferFailedException { String rawLS = "total 32\n" + "drwxr-xr-x 5 joakim joakim 238 Dec 11 10:30 .\n" - + "drwxr-xr-x 14 joakim joakim 518 Dec 11 10:30 ..\n" - + "-rw-r--r-- 1 joakim joakim 320 May 9 2006 .classpath\n" - + "-rw-r--r-- 1 joakim joakim 1194 Dec 11 09:25 pom.xml\n" - + "-rw-r--r-- 1 joakim joakim 662 May 9 2006 .project\n" - + "drwxr-xr-x 4 joakim joakim 204 Dec 11 12:26 src\n" - + "drwxr-xr-x 4 joakim joakim 204 Dec 11 12:26 spaced out\n" - + "drwxr-xr-x 7 joakim joakim 476 Dec 11 10:31 .svn\n" - + "drwxr-xr-x 3 joakim joakim 238 Dec 11 08:39 target\n"; + + "drwxr-xr-x 14 joakim joakim 518 Dec 11 10:30 ..\n" + + "-rw-r--r-- 1 joakim joakim 320 May 9 2006 .classpath\n" + + "-rw-r--r-- 1 joakim joakim 1194 Dec 11 09:25 pom.xml\n" + + "-rw-r--r-- 1 joakim joakim 662 May 9 2006 .project\n" + + "drwxr-xr-x 4 joakim joakim 204 Dec 11 12:26 src\n" + + "drwxr-xr-x 4 joakim joakim 204 Dec 11 12:26 spaced out\n" + + "drwxr-xr-x 7 joakim joakim 476 Dec 11 10:31 .svn\n" + + "drwxr-xr-x 3 joakim joakim 238 Dec 11 08:39 target\n"; LSParser parser = new LSParser(); - List files = parser.parseFiles( rawLS ); - assertNotNull( files ); - assertEquals( 9, files.size() ); - assertTrue( files.contains( "pom.xml" ) ); - assertTrue( files.contains( "spaced out" ) ); + List files = parser.parseFiles(rawLS); + assertNotNull(files); + assertEquals(9, files.size()); + assertTrue(files.contains("pom.xml")); + assertTrue(files.contains("spaced out")); } - public void testParseOSXFrLocale() throws TransferFailedException - { + public void testParseOSXFrLocale() throws TransferFailedException { String rawLS = "total 40\n" + "-rw-r--r-- 1 olamy staff 11 21 sep 00:34 .index.txt\n" + "-rw-r--r-- 1 olamy staff 19 21 sep 00:34 more-resources.dat\n" + "-rw-r--r-- 1 olamy staff 20 21 sep 00:34 test-resource b.txt\n" - +"-rw-r--r-- 1 olamy staff 18 21 sep 00:34 test-resource.pom\n" + + "-rw-r--r-- 1 olamy staff 18 21 sep 00:34 test-resource.pom\n" + "-rw-r--r-- 1 olamy staff 18 21 sep 00:34 test-resource.txt\n"; LSParser parser = new LSParser(); - List files = parser.parseFiles( rawLS ); - assertNotNull( files ); - assertEquals( 5, files.size() ); - assertTrue( files.contains( "more-resources.dat" ) ); - assertTrue( files.contains( ".index.txt" ) ); + List files = parser.parseFiles(rawLS); + assertNotNull(files); + assertEquals(5, files.size()); + assertTrue(files.contains("more-resources.dat")); + assertTrue(files.contains(".index.txt")); } - - - public void testParseCygwin() throws TransferFailedException - { + public void testParseCygwin() throws TransferFailedException { String rawLS = "total 32\n" + "drwxr-xr-x+ 5 joakim None 0 Dec 11 10:30 .\n" - + "drwxr-xr-x+ 14 joakim None 0 Dec 11 10:30 ..\n" - + "-rw-r--r--+ 1 joakim None 320 May 9 2006 .classpath\n" - + "-rw-r--r--+ 1 joakim None 1194 Dec 11 09:25 pom.xml\n" - + "-rw-r--r--+ 1 joakim None 662 May 9 2006 .project\n" - + "drwxr-xr-x+ 4 joakim None 0 Dec 11 12:26 src\n" - + "drwxr-xr-x+ 4 joakim None 0 Dec 11 12:26 spaced out\n" - + "drwxr-xr-x+ 7 joakim None 0 Dec 11 10:31 .svn\n" - + "drwxr-xr-x+ 3 joakim None 0 Dec 11 08:39 target\n"; - + + "drwxr-xr-x+ 14 joakim None 0 Dec 11 10:30 ..\n" + + "-rw-r--r--+ 1 joakim None 320 May 9 2006 .classpath\n" + + "-rw-r--r--+ 1 joakim None 1194 Dec 11 09:25 pom.xml\n" + + "-rw-r--r--+ 1 joakim None 662 May 9 2006 .project\n" + + "drwxr-xr-x+ 4 joakim None 0 Dec 11 12:26 src\n" + + "drwxr-xr-x+ 4 joakim None 0 Dec 11 12:26 spaced out\n" + + "drwxr-xr-x+ 7 joakim None 0 Dec 11 10:31 .svn\n" + + "drwxr-xr-x+ 3 joakim None 0 Dec 11 08:39 target\n"; + LSParser parser = new LSParser(); - List files = parser.parseFiles( rawLS ); - assertNotNull( files ); - assertEquals( 9, files.size() ); - assertTrue( files.contains( "pom.xml" ) ); - assertTrue( files.contains( "spaced out" ) ); + List files = parser.parseFiles(rawLS); + assertNotNull(files); + assertEquals(9, files.size()); + assertTrue(files.contains("pom.xml")); + assertTrue(files.contains("spaced out")); } /** @@ -112,19 +101,18 @@ public void testParseCygwin() throws TransferFailedException * Just adding a real-world example of the ls to see if it is a problem. * - Joakime */ - public void testParsePeopleApacheStaging() throws TransferFailedException - { + public void testParsePeopleApacheStaging() throws TransferFailedException { String rawLS = "total 6\n" - + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 .\n" - + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 ..\n" - + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 org\n" - + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 spaced out\n"; + + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 .\n" + + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 ..\n" + + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 org\n" + + "drwxr-xr-x 3 snicoll snicoll 512 Feb 7 11:04 spaced out\n"; LSParser parser = new LSParser(); - List files = parser.parseFiles( rawLS ); - assertNotNull( files ); - assertEquals( 4, files.size() ); - assertTrue( files.contains( "org" ) ); - assertTrue( files.contains( "spaced out" ) ); + List files = parser.parseFiles(rawLS); + assertNotNull(files); + assertEquals(4, files.size()); + assertTrue(files.contains("org")); + assertTrue(files.contains("spaced out")); } } diff --git a/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProviderTest.java b/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProviderTest.java index 66f8fae78..f1b919b0c 100644 --- a/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProviderTest.java +++ b/wagon-providers/wagon-ssh-common/src/test/java/org/apache/maven/wagon/providers/ssh/knownhost/FileKnownHostsProviderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.knownhost; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,58 +16,47 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.knownhost; import java.io.File; +import junit.framework.TestCase; import org.codehaus.plexus.util.FileUtils; -import junit.framework.TestCase; +public class FileKnownHostsProviderTest extends TestCase { + private File basedir = new File(System.getProperty("basedir", ".")); -public class FileKnownHostsProviderTest - extends TestCase -{ - private File basedir = new File( System.getProperty( "basedir", "." ) ); - private File testKnownHostsFile; - - + private FileKnownHostsProvider provider; - - public void setUp() - throws Exception - { - File readonlyKnownHostFile = new File( basedir, "src/test/resources/known_hosts" ); - testKnownHostsFile = new File( basedir, "target/known_hosts" ); + + public void setUp() throws Exception { + File readonlyKnownHostFile = new File(basedir, "src/test/resources/known_hosts"); + testKnownHostsFile = new File(basedir, "target/known_hosts"); testKnownHostsFile.delete(); - FileUtils.copyFile( readonlyKnownHostFile, testKnownHostsFile ); - testKnownHostsFile.setLastModified( testKnownHostsFile.lastModified() - 60 * 1000 ); + FileUtils.copyFile(readonlyKnownHostFile, testKnownHostsFile); + testKnownHostsFile.setLastModified(testKnownHostsFile.lastModified() - 60 * 1000); - provider = new FileKnownHostsProvider( testKnownHostsFile ); - + provider = new FileKnownHostsProvider(testKnownHostsFile); } - - public void testStoreKnownHostsNoChange() - throws Exception - { + + public void testStoreKnownHostsNoChange() throws Exception { long timestamp = this.testKnownHostsFile.lastModified(); - //file with the same contents, but with entries swapped - File sameKnownHostFile = new File( basedir, "src/test/resources/known_hosts_same" ); - String contents = FileUtils.fileRead( sameKnownHostFile ); - - provider.storeKnownHosts( contents ); - assertEquals( "known_hosts file is rewritten", timestamp, testKnownHostsFile.lastModified() ); + // file with the same contents, but with entries swapped + File sameKnownHostFile = new File(basedir, "src/test/resources/known_hosts_same"); + String contents = FileUtils.fileRead(sameKnownHostFile); + + provider.storeKnownHosts(contents); + assertEquals("known_hosts file is rewritten", timestamp, testKnownHostsFile.lastModified()); } - - public void testStoreKnownHostsWithChange() - throws Exception - { + + public void testStoreKnownHostsWithChange() throws Exception { long timestamp = this.testKnownHostsFile.lastModified(); - File sameKnownHostFile = new File( basedir, "src/test/resources/known_hosts_same" ); - String contents = FileUtils.fileRead( sameKnownHostFile ); + File sameKnownHostFile = new File(basedir, "src/test/resources/known_hosts_same"); + String contents = FileUtils.fileRead(sameKnownHostFile); contents += "1 2 3"; - - provider.storeKnownHosts( contents ); - assertTrue( "known_hosts file is not rewritten", timestamp != testKnownHostsFile.lastModified() ); + + provider.storeKnownHosts(contents); + assertTrue("known_hosts file is not rewritten", timestamp != testKnownHostsFile.lastModified()); } - } diff --git a/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalCommandExecutor.java b/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalCommandExecutor.java index 3fb95952b..0d3567e55 100644 --- a/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalCommandExecutor.java +++ b/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalCommandExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.external; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,26 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.external; /** - * ScpExternalCommandExecutor - bridge class for plexus:descriptor + * ScpExternalCommandExecutor - bridge class for plexus:descriptor * * @author Joakim Erdfelt * - * + * * @todo is this even needed anymore? - * + * * @plexus.component role="org.apache.maven.wagon.CommandExecutor" - * role-hint="scpexe" + * role-hint="scpexe" * instantiation-strategy="per-lookup" */ -public class ScpExternalCommandExecutor - extends ScpExternalWagon -{ +public class ScpExternalCommandExecutor extends ScpExternalWagon { - public ScpExternalCommandExecutor() - { + public ScpExternalCommandExecutor() { super(); } - } diff --git a/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagon.java b/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagon.java index b2b665a2d..0ab0cd296 100644 --- a/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagon.java +++ b/wagon-providers/wagon-ssh-external/src/main/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.external; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.external; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.List; +import java.util.Locale; import org.apache.maven.wagon.AbstractWagon; import org.apache.maven.wagon.CommandExecutionException; @@ -40,11 +44,6 @@ import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; -import java.io.File; -import java.io.FileNotFoundException; -import java.util.List; -import java.util.Locale; - /** * SCP deployer using "external" scp program. To allow for * ssh-agent type behavior, until we can construct a Java SSH Agent and interface for JSch. @@ -55,10 +54,7 @@ * role-hint="scpexe" * instantiation-strategy="per-lookup" */ -public class ScpExternalWagon - extends AbstractWagon - implements CommandExecutor -{ +public class ScpExternalWagon extends AbstractWagon implements CommandExecutor { /** * The external SCP command to use - default is scp. * @@ -87,7 +83,7 @@ public class ScpExternalWagon */ private String sshArgs; - private ScpHelper sshTool = new ScpHelper( this ); + private ScpHelper sshTool = new ScpHelper(this); private static final int SSH_FATAL_EXIT_CODE = 255; @@ -95,25 +91,20 @@ public class ScpExternalWagon // // ---------------------------------------------------------------------- - protected void openConnectionInternal() - throws AuthenticationException - { - if ( authenticationInfo == null ) - { + protected void openConnectionInternal() throws AuthenticationException { + if (authenticationInfo == null) { authenticationInfo = new AuthenticationInfo(); } } - public void closeConnection() - { + public void closeConnection() { // nothing to disconnect } - public boolean getIfNewer( String resourceName, File destination, long timestamp ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - fireSessionDebug( "getIfNewer in SCP wagon is not supported - performing an unconditional get" ); - get( resourceName, destination ); + public boolean getIfNewer(String resourceName, File destination, long timestamp) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + fireSessionDebug("getIfNewer in SCP wagon is not supported - performing an unconditional get"); + get(resourceName, destination); return true; } @@ -121,333 +112,269 @@ public boolean getIfNewer( String resourceName, File destination, long timestamp * @return The hostname of the remote server prefixed with the username, which comes either from the repository URL * or from the authenticationInfo. */ - private String buildRemoteHost() - { + private String buildRemoteHost() { String username = this.getRepository().getUsername(); - if ( username == null ) - { + if (username == null) { username = authenticationInfo.getUserName(); } - if ( username == null ) - { + if (username == null) { return getRepository().getHost(); - } - else - { + } else { return username + "@" + getRepository().getHost(); } } - public void executeCommand( String command ) - throws CommandExecutionException - { - fireTransferDebug( "Executing command: " + command ); + public void executeCommand(String command) throws CommandExecutionException { + fireTransferDebug("Executing command: " + command); - executeCommand( command, false ); + executeCommand(command, false); } - public Streams executeCommand( String command, boolean ignoreFailures ) - throws CommandExecutionException - { + public Streams executeCommand(String command, boolean ignoreFailures) throws CommandExecutionException { boolean putty = isPuTTY(); File privateKey; - try - { - privateKey = ScpHelper.getPrivateKey( authenticationInfo ); - } - catch ( FileNotFoundException e ) - { - throw new CommandExecutionException( e.getMessage(), e ); + try { + privateKey = ScpHelper.getPrivateKey(authenticationInfo); + } catch (FileNotFoundException e) { + throw new CommandExecutionException(e.getMessage(), e); } - Commandline cl = createBaseCommandLine( putty, sshExecutable, privateKey ); + Commandline cl = createBaseCommandLine(putty, sshExecutable, privateKey); int port = - repository.getPort() == WagonConstants.UNKNOWN_PORT ? ScpHelper.DEFAULT_SSH_PORT : repository.getPort(); - if ( port != ScpHelper.DEFAULT_SSH_PORT ) - { - if ( putty ) - { - cl.createArg().setLine( "-P " + port ); - } - else - { - cl.createArg().setLine( "-p " + port ); + repository.getPort() == WagonConstants.UNKNOWN_PORT ? ScpHelper.DEFAULT_SSH_PORT : repository.getPort(); + if (port != ScpHelper.DEFAULT_SSH_PORT) { + if (putty) { + cl.createArg().setLine("-P " + port); + } else { + cl.createArg().setLine("-p " + port); } } - if ( sshArgs != null ) - { - cl.createArg().setLine( sshArgs ); + if (sshArgs != null) { + cl.createArg().setLine(sshArgs); } String remoteHost = this.buildRemoteHost(); - cl.createArg().setValue( remoteHost ); + cl.createArg().setValue(remoteHost); - cl.createArg().setValue( command ); + cl.createArg().setValue(command); - fireSessionDebug( "Executing command: " + cl.toString() ); + fireSessionDebug("Executing command: " + cl.toString()); - try - { + try { CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer(); CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); - int exitCode = CommandLineUtils.executeCommandLine( cl, out, err ); + int exitCode = CommandLineUtils.executeCommandLine(cl, out, err); Streams streams = new Streams(); - streams.setOut( out.getOutput() ); - streams.setErr( err.getOutput() ); - fireSessionDebug( streams.getOut() ); - fireSessionDebug( streams.getErr() ); - if ( exitCode != 0 ) - { - if ( !ignoreFailures || exitCode == SSH_FATAL_EXIT_CODE ) - { - throw new CommandExecutionException( "Exit code " + exitCode + " - " + err.getOutput() ); + streams.setOut(out.getOutput()); + streams.setErr(err.getOutput()); + fireSessionDebug(streams.getOut()); + fireSessionDebug(streams.getErr()); + if (exitCode != 0) { + if (!ignoreFailures || exitCode == SSH_FATAL_EXIT_CODE) { + throw new CommandExecutionException("Exit code " + exitCode + " - " + err.getOutput()); } } return streams; - } - catch ( CommandLineException e ) - { - throw new CommandExecutionException( "Error executing command line", e ); + } catch (CommandLineException e) { + throw new CommandExecutionException("Error executing command line", e); } } - protected boolean isPuTTY() - { - String exe = sshExecutable.toLowerCase( Locale.ENGLISH ); - return exe.contains( "plink" ) || exe.contains( "klink" ); + protected boolean isPuTTY() { + String exe = sshExecutable.toLowerCase(Locale.ENGLISH); + return exe.contains("plink") || exe.contains("klink"); } - private Commandline createBaseCommandLine( boolean putty, String executable, File privateKey ) - { + private Commandline createBaseCommandLine(boolean putty, String executable, File privateKey) { Commandline cl = new Commandline(); - cl.setExecutable( executable ); + cl.setExecutable(executable); - if ( privateKey != null ) - { - cl.createArg().setValue( "-i" ); - cl.createArg().setFile( privateKey ); + if (privateKey != null) { + cl.createArg().setValue("-i"); + cl.createArg().setFile(privateKey); } String password = authenticationInfo.getPassword(); - if ( putty && password != null ) - { - cl.createArg().setValue( "-pw" ); - cl.createArg().setValue( password ); + if (putty && password != null) { + cl.createArg().setValue("-pw"); + cl.createArg().setValue(password); } // should check interactive flag, but scpexe never works in interactive mode right now due to i/o streams - if ( putty ) - { - cl.createArg().setValue( "-batch" ); - } - else - { - cl.createArg().setValue( "-o" ); - cl.createArg().setValue( "BatchMode yes" ); + if (putty) { + cl.createArg().setValue("-batch"); + } else { + cl.createArg().setValue("-o"); + cl.createArg().setValue("BatchMode yes"); } return cl; } - - private void executeScpCommand( Resource resource, File localFile, boolean put ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + private void executeScpCommand(Resource resource, File localFile, boolean put) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { boolean putty = isPuTTYSCP(); File privateKey; - try - { - privateKey = ScpHelper.getPrivateKey( authenticationInfo ); - } - catch ( FileNotFoundException e ) - { + try { + privateKey = ScpHelper.getPrivateKey(authenticationInfo); + } catch (FileNotFoundException e) { fireSessionConnectionRefused(); - throw new AuthorizationException( e.getMessage() ); + throw new AuthorizationException(e.getMessage()); } - Commandline cl = createBaseCommandLine( putty, scpExecutable, privateKey ); + Commandline cl = createBaseCommandLine(putty, scpExecutable, privateKey); - cl.setWorkingDirectory( localFile.getParentFile().getAbsolutePath() ); + cl.setWorkingDirectory(localFile.getParentFile().getAbsolutePath()); int port = - repository.getPort() == WagonConstants.UNKNOWN_PORT ? ScpHelper.DEFAULT_SSH_PORT : repository.getPort(); - if ( port != ScpHelper.DEFAULT_SSH_PORT ) - { - cl.createArg().setLine( "-P " + port ); + repository.getPort() == WagonConstants.UNKNOWN_PORT ? ScpHelper.DEFAULT_SSH_PORT : repository.getPort(); + if (port != ScpHelper.DEFAULT_SSH_PORT) { + cl.createArg().setLine("-P " + port); } - if ( scpArgs != null ) - { - cl.createArg().setLine( scpArgs ); + if (scpArgs != null) { + cl.createArg().setLine(scpArgs); } - String resourceName = normalizeResource( resource ); + String resourceName = normalizeResource(resource); String remoteFile = getRepository().getBasedir() + "/" + resourceName; - remoteFile = StringUtils.replace( remoteFile, " ", "\\ " ); + remoteFile = StringUtils.replace(remoteFile, " ", "\\ "); String qualifiedRemoteFile = this.buildRemoteHost() + ":" + remoteFile; - if ( put ) - { - cl.createArg().setValue( localFile.getName() ); - cl.createArg().setValue( qualifiedRemoteFile ); - } - else - { - cl.createArg().setValue( qualifiedRemoteFile ); - cl.createArg().setValue( localFile.getName() ); + if (put) { + cl.createArg().setValue(localFile.getName()); + cl.createArg().setValue(qualifiedRemoteFile); + } else { + cl.createArg().setValue(qualifiedRemoteFile); + cl.createArg().setValue(localFile.getName()); } - fireSessionDebug( "Executing command: " + cl.toString() ); + fireSessionDebug("Executing command: " + cl.toString()); - try - { + try { CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); - int exitCode = CommandLineUtils.executeCommandLine( cl, null, err ); - if ( exitCode != 0 ) - { - if ( !put - && err.getOutput().trim().toLowerCase( Locale.ENGLISH ).contains( "no such file or directory" ) ) - { - throw new ResourceDoesNotExistException( err.getOutput() ); - } - else - { + int exitCode = CommandLineUtils.executeCommandLine(cl, null, err); + if (exitCode != 0) { + if (!put && err.getOutput().trim().toLowerCase(Locale.ENGLISH).contains("no such file or directory")) { + throw new ResourceDoesNotExistException(err.getOutput()); + } else { TransferFailedException e = - new TransferFailedException( "Exit code: " + exitCode + " - " + err.getOutput() ); + new TransferFailedException("Exit code: " + exitCode + " - " + err.getOutput()); - fireTransferError( resource, e, put ? TransferEvent.REQUEST_PUT : TransferEvent.REQUEST_GET ); + fireTransferError(resource, e, put ? TransferEvent.REQUEST_PUT : TransferEvent.REQUEST_GET); throw e; } } - } - catch ( CommandLineException e ) - { - fireTransferError( resource, e, put ? TransferEvent.REQUEST_PUT : TransferEvent.REQUEST_GET ); + } catch (CommandLineException e) { + fireTransferError(resource, e, put ? TransferEvent.REQUEST_PUT : TransferEvent.REQUEST_GET); - throw new TransferFailedException( "Error executing command line", e ); + throw new TransferFailedException("Error executing command line", e); } } - boolean isPuTTYSCP() - { - String exe = scpExecutable.toLowerCase( Locale.ENGLISH ); - return exe.contains( "pscp" ) || exe.contains( "kscp" ); + boolean isPuTTYSCP() { + String exe = scpExecutable.toLowerCase(Locale.ENGLISH); + return exe.contains("pscp") || exe.contains("kscp"); } - private String normalizeResource( Resource resource ) - { - return StringUtils.replace( resource.getName(), "\\", "/" ); + private String normalizeResource(Resource resource) { + return StringUtils.replace(resource.getName(), "\\", "/"); } - public void put( File source, String destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( destination ); + public void put(File source, String destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(destination); - firePutInitiated( resource, source ); + firePutInitiated(resource, source); - if ( !source.exists() ) - { - throw new ResourceDoesNotExistException( "Specified source file does not exist: " + source ); + if (!source.exists()) { + throw new ResourceDoesNotExistException("Specified source file does not exist: " + source); } String basedir = getRepository().getBasedir(); - String resourceName = StringUtils.replace( destination, "\\", "/" ); + String resourceName = StringUtils.replace(destination, "\\", "/"); - String dir = PathUtils.dirname( resourceName ); + String dir = PathUtils.dirname(resourceName); - dir = StringUtils.replace( dir, "\\", "/" ); + dir = StringUtils.replace(dir, "\\", "/"); String umaskCmd = null; - if ( getRepository().getPermissions() != null ) - { + if (getRepository().getPermissions() != null) { String dirPerms = getRepository().getPermissions().getDirectoryMode(); - if ( dirPerms != null ) - { - umaskCmd = "umask " + PermissionModeUtils.getUserMaskFor( dirPerms ); + if (dirPerms != null) { + umaskCmd = "umask " + PermissionModeUtils.getUserMaskFor(dirPerms); } } String mkdirCmd = "mkdir -p " + basedir + "/" + dir + "\n"; - if ( umaskCmd != null ) - { + if (umaskCmd != null) { mkdirCmd = umaskCmd + "; " + mkdirCmd; } - try - { - executeCommand( mkdirCmd ); - } - catch ( CommandExecutionException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + try { + executeCommand(mkdirCmd); + } catch (CommandExecutionException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( "Error executing command for transfer", e ); + throw new TransferFailedException("Error executing command for transfer", e); } - resource.setContentLength( source.length() ); + resource.setContentLength(source.length()); - resource.setLastModified( source.lastModified() ); + resource.setLastModified(source.lastModified()); - firePutStarted( resource, source ); + firePutStarted(resource, source); - executeScpCommand( resource, source, true ); + executeScpCommand(resource, source, true); - postProcessListeners( resource, source, TransferEvent.REQUEST_PUT ); + postProcessListeners(resource, source, TransferEvent.REQUEST_PUT); - try - { + try { RepositoryPermissions permissions = getRepository().getPermissions(); - if ( permissions != null && permissions.getGroup() != null ) - { - executeCommand( "chgrp -f " + permissions.getGroup() + " " + basedir + "/" + resourceName + "\n", - true ); + if (permissions != null && permissions.getGroup() != null) { + executeCommand("chgrp -f " + permissions.getGroup() + " " + basedir + "/" + resourceName + "\n", true); } - if ( permissions != null && permissions.getFileMode() != null ) - { - executeCommand( "chmod -f " + permissions.getFileMode() + " " + basedir + "/" + resourceName + "\n", - true ); + if (permissions != null && permissions.getFileMode() != null) { + executeCommand( + "chmod -f " + permissions.getFileMode() + " " + basedir + "/" + resourceName + "\n", true); } - } - catch ( CommandExecutionException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + } catch (CommandExecutionException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( "Error executing command for transfer", e ); + throw new TransferFailedException("Error executing command for transfer", e); } - firePutCompleted( resource, source ); + firePutCompleted(resource, source); } - public void get( String resourceName, File destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - String path = StringUtils.replace( resourceName, "\\", "/" ); + public void get(String resourceName, File destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + String path = StringUtils.replace(resourceName, "\\", "/"); - Resource resource = new Resource( path ); + Resource resource = new Resource(path); - fireGetInitiated( resource, destination ); + fireGetInitiated(resource, destination); - createParentDirectories( destination ); + createParentDirectories(destination); - fireGetStarted( resource, destination ); + fireGetStarted(resource, destination); - executeScpCommand( resource, destination, false ); + executeScpCommand(resource, destination, false); - postProcessListeners( resource, destination, TransferEvent.REQUEST_GET ); + postProcessListeners(resource, destination, TransferEvent.REQUEST_GET); - fireGetCompleted( resource, destination ); + fireGetCompleted(resource, destination); } // @@ -457,66 +384,53 @@ public void get( String resourceName, File destination ) // method on a Wagon. // - public List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - return sshTool.getFileList( destinationDirectory, repository ); + public List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + return sshTool.getFileList(destinationDirectory, repository); } - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - sshTool.putDirectory( this, sourceDirectory, destinationDirectory ); + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + sshTool.putDirectory(this, sourceDirectory, destinationDirectory); } - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - return sshTool.resourceExists( resourceName, repository ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + return sshTool.resourceExists(resourceName, repository); } - public boolean supportsDirectoryCopy() - { + public boolean supportsDirectoryCopy() { return true; } - public String getScpExecutable() - { + public String getScpExecutable() { return scpExecutable; } - public void setScpExecutable( String scpExecutable ) - { + public void setScpExecutable(String scpExecutable) { this.scpExecutable = scpExecutable; } - public String getSshExecutable() - { + public String getSshExecutable() { return sshExecutable; } - public void setSshExecutable( String sshExecutable ) - { + public void setSshExecutable(String sshExecutable) { this.sshExecutable = sshExecutable; } - public String getScpArgs() - { + public String getScpArgs() { return scpArgs; } - public void setScpArgs( String scpArgs ) - { + public void setScpArgs(String scpArgs) { this.scpArgs = scpArgs; } - public String getSshArgs() - { + public String getSshArgs() { return sshArgs; } - public void setSshArgs( String sshArgs ) - { + public void setSshArgs(String sshArgs) { this.sshArgs = sshArgs; } } diff --git a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/EmbeddedScpExternalWagonWithKeyTest.java b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/EmbeddedScpExternalWagonWithKeyTest.java index 5c21ad3e6..678bc42f6 100644 --- a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/EmbeddedScpExternalWagonWithKeyTest.java +++ b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/EmbeddedScpExternalWagonWithKeyTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.external; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.external; + +import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.maven.wagon.Streams; @@ -27,87 +28,65 @@ import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; -import java.io.File; - /** * @author Michal Maczka * */ -public class EmbeddedScpExternalWagonWithKeyTest - extends AbstractEmbeddedScpWagonWithKeyTest -{ - +public class EmbeddedScpExternalWagonWithKeyTest extends AbstractEmbeddedScpWagonWithKeyTest { @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { ScpExternalWagon scpWagon = (ScpExternalWagon) super.getWagon(); - scpWagon.setInteractive( false ); - File dummyKnowHostsFile = new File( "target/dummy_knowhost" ); - if ( dummyKnowHostsFile.exists() ) - { + scpWagon.setInteractive(false); + File dummyKnowHostsFile = new File("target/dummy_knowhost"); + if (dummyKnowHostsFile.exists()) { dummyKnowHostsFile.delete(); } scpWagon.setScpArgs( - "-o StrictHostKeyChecking=no -o UserKnownHostsFile=" + dummyKnowHostsFile.getCanonicalPath() ); + "-o StrictHostKeyChecking=no -o UserKnownHostsFile=" + dummyKnowHostsFile.getCanonicalPath()); scpWagon.setSshArgs( - "-o StrictHostKeyChecking=no -o UserKnownHostsFile=" + dummyKnowHostsFile.getCanonicalPath() ); + "-o StrictHostKeyChecking=no -o UserKnownHostsFile=" + dummyKnowHostsFile.getCanonicalPath()); dummyKnowHostsFile.deleteOnExit(); return scpWagon; } - - protected String getProtocol() - { + protected String getProtocol() { return "scpexe"; } - - protected AuthenticationInfo getAuthInfo() - { - try - { + protected AuthenticationInfo getAuthInfo() { + try { AuthenticationInfo authInfo = super.getAuthInfo(); // user : guest/guest123 - passphrase : toto01 - authInfo.setUserName( "guest" ); - File sshKeysTarget = new File( "target/ssh-keys" ); - FileUtils.copyDirectory( new File( "src/test/ssh-keys" ), sshKeysTarget ); + authInfo.setUserName("guest"); + File sshKeysTarget = new File("target/ssh-keys"); + FileUtils.copyDirectory(new File("src/test/ssh-keys"), sshKeysTarget); // ssh keys need to 700 permissions // to prevent WARNING: UNPROTECTED PRIVATE KEY FILE! - Commandline commandline = new Commandline( "chmod" ); - commandline.createArg().setValue( "-R" ); - commandline.createArg().setValue( "700" ); - commandline.createArg().setValue( sshKeysTarget.getCanonicalPath() ); + Commandline commandline = new Commandline("chmod"); + commandline.createArg().setValue("-R"); + commandline.createArg().setValue("700"); + commandline.createArg().setValue(sshKeysTarget.getCanonicalPath()); CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer(); CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); - int exitCode = CommandLineUtils.executeCommandLine( commandline, out, err ); + int exitCode = CommandLineUtils.executeCommandLine(commandline, out, err); Streams streams = new Streams(); - streams.setOut( out.getOutput() ); - streams.setErr( err.getOutput() ); - if ( exitCode != 0 ) - { - throw new RuntimeException( - "fail to chmod exit code " + exitCode + ", error" + streams.getErr() + ", out " - + streams.getOut() ); + streams.setOut(out.getOutput()); + streams.setErr(err.getOutput()); + if (exitCode != 0) { + throw new RuntimeException("fail to chmod exit code " + exitCode + ", error" + streams.getErr() + + ", out " + streams.getOut()); } - authInfo.setPrivateKey( new File( sshKeysTarget, "id_rsa" ).getCanonicalPath() ); + authInfo.setPrivateKey(new File(sshKeysTarget, "id_rsa").getCanonicalPath()); return authInfo; - } - catch ( Exception e ) - { - throw new RuntimeException( e.getMessage(), e ); - + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); } } - public void testFailedGetToStream() - throws Exception - { + public void testFailedGetToStream() throws Exception { // ignore this test as it need a stream wagon } - - } diff --git a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagonTest.java b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagonTest.java index 9b2e4ed50..8020374db 100644 --- a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagonTest.java +++ b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpExternalWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.external; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.external; + +import java.io.File; import org.apache.maven.wagon.WagonConstants; import org.apache.maven.wagon.WagonTestCase; @@ -26,85 +27,72 @@ import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; -import java.io.File; - /** * @author Michal Maczka * */ -public class ScpExternalWagonTest - extends WagonTestCase -{ - protected int getExpectedContentLengthOnGet( int expectedSize ) - { +public class ScpExternalWagonTest extends WagonTestCase { + protected int getExpectedContentLengthOnGet(int expectedSize) { return WagonConstants.UNKNOWN_LENGTH; } - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return false; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { return 0; } - protected String getProtocol() - { + protected String getProtocol() { return "scpexe"; } - public String getTestRepositoryUrl() - { + public String getTestRepositoryUrl() { return TestData.getTestRepositoryUrl(); } - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = new AuthenticationInfo(); String userName = TestData.getUserName(); - authInfo.setUserName( userName ); + authInfo.setUserName(userName); File privateKey = TestData.getPrivateKey(); - if ( privateKey.exists() ) - { - authInfo.setPrivateKey( privateKey.getAbsolutePath() ); + if (privateKey.exists()) { + authInfo.setPrivateKey(privateKey.getAbsolutePath()); - authInfo.setPassphrase( "" ); + authInfo.setPassphrase(""); } return authInfo; } - public void testIsPuTTY() - throws Exception - { + public void testIsPuTTY() throws Exception { ScpExternalWagon wagon = (ScpExternalWagon) getWagon(); - wagon.setSshExecutable( "c:\\program files\\PuTTY\\plink.exe" ); - assertTrue( wagon.isPuTTY() ); - wagon.setSshExecutable( "plink" ); - assertTrue( wagon.isPuTTY() ); - wagon.setSshExecutable( "PLINK" ); - assertTrue( wagon.isPuTTY() ); - wagon.setSshExecutable( "PlInK" ); - assertTrue( wagon.isPuTTY() ); - wagon.setSshExecutable( "ssh" ); - assertFalse( wagon.isPuTTY() ); - - wagon.setScpExecutable( "c:\\program files\\PuTTY\\pscp.exe" ); - assertTrue( wagon.isPuTTYSCP() ); - wagon.setScpExecutable( "pscp" ); - assertTrue( wagon.isPuTTYSCP() ); - wagon.setScpExecutable( "PSCP" ); - assertTrue( wagon.isPuTTYSCP() ); - wagon.setScpExecutable( "PsCp" ); - assertTrue( wagon.isPuTTYSCP() ); - wagon.setScpExecutable( "scp" ); - assertFalse( wagon.isPuTTYSCP() ); + wagon.setSshExecutable("c:\\program files\\PuTTY\\plink.exe"); + assertTrue(wagon.isPuTTY()); + wagon.setSshExecutable("plink"); + assertTrue(wagon.isPuTTY()); + wagon.setSshExecutable("PLINK"); + assertTrue(wagon.isPuTTY()); + wagon.setSshExecutable("PlInK"); + assertTrue(wagon.isPuTTY()); + wagon.setSshExecutable("ssh"); + assertFalse(wagon.isPuTTY()); + + wagon.setScpExecutable("c:\\program files\\PuTTY\\pscp.exe"); + assertTrue(wagon.isPuTTYSCP()); + wagon.setScpExecutable("pscp"); + assertTrue(wagon.isPuTTYSCP()); + wagon.setScpExecutable("PSCP"); + assertTrue(wagon.isPuTTYSCP()); + wagon.setScpExecutable("PsCp"); + assertTrue(wagon.isPuTTYSCP()); + wagon.setScpExecutable("scp"); + assertFalse(wagon.isPuTTYSCP()); } } diff --git a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpWagonWithSshPrivateKeySearchTest.java b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpWagonWithSshPrivateKeySearchTest.java index 85c8d08d5..93f398831 100644 --- a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpWagonWithSshPrivateKeySearchTest.java +++ b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/ScpWagonWithSshPrivateKeySearchTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.external; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.external; import org.apache.maven.wagon.WagonConstants; import org.apache.maven.wagon.WagonTestCase; @@ -30,45 +29,34 @@ * @author Michal Maczka * */ -public class ScpWagonWithSshPrivateKeySearchTest - extends WagonTestCase -{ - protected boolean supportsGetIfNewer() - { +public class ScpWagonWithSshPrivateKeySearchTest extends WagonTestCase { + protected boolean supportsGetIfNewer() { return false; } - protected int getExpectedContentLengthOnGet( int expectedSize ) - { + protected int getExpectedContentLengthOnGet(int expectedSize) { return WagonConstants.UNKNOWN_LENGTH; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { return 0; } - protected String getProtocol() - { + protected String getProtocol() { return "scpexe"; } - public String getTestRepositoryUrl() - { + public String getTestRepositoryUrl() { return TestData.getTestRepositoryUrl(); } - - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = super.getAuthInfo(); - authInfo.setUserName( TestData.getUserName() ); + authInfo.setUserName(TestData.getUserName()); - authInfo.setPassphrase( "" ); + authInfo.setPassphrase(""); return authInfo; } - - } diff --git a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/SshCommandExecutorTest.java b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/SshCommandExecutorTest.java index 0d34719ee..1654d36da 100644 --- a/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/SshCommandExecutorTest.java +++ b/wagon-providers/wagon-ssh-external/src/test/java/org/apache/maven/wagon/providers/ssh/external/SshCommandExecutorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.external; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.external; import org.apache.maven.wagon.CommandExecutorTestCase; import org.apache.maven.wagon.repository.Repository; @@ -28,12 +27,9 @@ * @author Brett Porter * */ -public class SshCommandExecutorTest - extends CommandExecutorTestCase -{ +public class SshCommandExecutorTest extends CommandExecutorTestCase { - protected Repository getTestRepository() - { - return new Repository( "test", "scpexe://localhost/" ); + protected Repository getTestRepository() { + return new Repository("test", "scpexe://localhost/"); } } diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/AbstractJschWagon.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/AbstractJschWagon.java index 2e94cbcd6..825e1d754 100644 --- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/AbstractJschWagon.java +++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/AbstractJschWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -30,6 +29,22 @@ import java.util.List; import java.util.Properties; +import com.jcraft.jsch.ChannelExec; +import com.jcraft.jsch.HostKey; +import com.jcraft.jsch.HostKeyRepository; +import com.jcraft.jsch.IdentityRepository; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Proxy; +import com.jcraft.jsch.ProxyHTTP; +import com.jcraft.jsch.ProxySOCKS5; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.UIKeyboardInteractive; +import com.jcraft.jsch.UserInfo; +import com.jcraft.jsch.agentproxy.AgentProxyException; +import com.jcraft.jsch.agentproxy.Connector; +import com.jcraft.jsch.agentproxy.ConnectorFactory; +import com.jcraft.jsch.agentproxy.RemoteIdentityRepository; import org.apache.maven.wagon.CommandExecutionException; import org.apache.maven.wagon.CommandExecutor; import org.apache.maven.wagon.ResourceDoesNotExistException; @@ -55,31 +70,11 @@ import org.apache.maven.wagon.resource.Resource; import org.codehaus.plexus.util.IOUtil; -import com.jcraft.jsch.ChannelExec; -import com.jcraft.jsch.HostKey; -import com.jcraft.jsch.HostKeyRepository; -import com.jcraft.jsch.IdentityRepository; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.Proxy; -import com.jcraft.jsch.ProxyHTTP; -import com.jcraft.jsch.ProxySOCKS5; -import com.jcraft.jsch.Session; -import com.jcraft.jsch.UIKeyboardInteractive; -import com.jcraft.jsch.UserInfo; -import com.jcraft.jsch.agentproxy.AgentProxyException; -import com.jcraft.jsch.agentproxy.Connector; -import com.jcraft.jsch.agentproxy.ConnectorFactory; -import com.jcraft.jsch.agentproxy.RemoteIdentityRepository; - /** * AbstractJschWagon */ -public abstract class AbstractJschWagon - extends StreamWagon - implements SshWagon, CommandExecutor -{ - protected ScpHelper sshTool = new ScpHelper( this ); +public abstract class AbstractJschWagon extends StreamWagon implements SshWagon, CommandExecutor { + protected ScpHelper sshTool = new ScpHelper(this); protected Session session; @@ -109,235 +104,179 @@ public abstract class AbstractJschWagon protected static final String EXEC_CHANNEL = "exec"; - public void openConnectionInternal() - throws AuthenticationException - { - if ( authenticationInfo == null ) - { + public void openConnectionInternal() throws AuthenticationException { + if (authenticationInfo == null) { authenticationInfo = new AuthenticationInfo(); } - if ( !interactive ) - { + if (!interactive) { uIKeyboardInteractive = null; - setInteractiveUserInfo( new NullInteractiveUserInfo() ); + setInteractiveUserInfo(new NullInteractiveUserInfo()); } JSch sch = new JSch(); File privateKey; - try - { - privateKey = ScpHelper.getPrivateKey( authenticationInfo ); - } - catch ( FileNotFoundException e ) - { - throw new AuthenticationException( e.getMessage() ); + try { + privateKey = ScpHelper.getPrivateKey(authenticationInfo); + } catch (FileNotFoundException e) { + throw new AuthenticationException(e.getMessage()); } - //can only pick one method of authentication - if ( privateKey != null && privateKey.exists() ) - { - fireSessionDebug( "Using private key: " + privateKey ); - try - { - sch.addIdentity( privateKey.getAbsolutePath(), authenticationInfo.getPassphrase() ); + // can only pick one method of authentication + if (privateKey != null && privateKey.exists()) { + fireSessionDebug("Using private key: " + privateKey); + try { + sch.addIdentity(privateKey.getAbsolutePath(), authenticationInfo.getPassphrase()); + } catch (JSchException e) { + throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e); } - catch ( JSchException e ) - { - throw new AuthenticationException( "Cannot connect. Reason: " + e.getMessage(), e ); - } - } - else - { - try - { + } else { + try { Connector connector = ConnectorFactory.getDefault().createConnector(); - if ( connector != null ) - { - IdentityRepository repo = new RemoteIdentityRepository( connector ); - sch.setIdentityRepository( repo ); + if (connector != null) { + IdentityRepository repo = new RemoteIdentityRepository(connector); + sch.setIdentityRepository(repo); } + } catch (AgentProxyException e) { + fireSessionDebug("Unable to connect to agent: " + e.toString()); } - catch ( AgentProxyException e ) - { - fireSessionDebug( "Unable to connect to agent: " + e.toString() ); - } - } String host = getRepository().getHost(); int port = - repository.getPort() == WagonConstants.UNKNOWN_PORT ? ScpHelper.DEFAULT_SSH_PORT : repository.getPort(); - try - { + repository.getPort() == WagonConstants.UNKNOWN_PORT ? ScpHelper.DEFAULT_SSH_PORT : repository.getPort(); + try { String userName = authenticationInfo.getUserName(); - if ( userName == null ) - { - userName = System.getProperty( "user.name" ); + if (userName == null) { + userName = System.getProperty("user.name"); } - session = sch.getSession( userName, host, port ); - session.setTimeout( getTimeout() ); - } - catch ( JSchException e ) - { - throw new AuthenticationException( "Cannot connect. Reason: " + e.getMessage(), e ); + session = sch.getSession(userName, host, port); + session.setTimeout(getTimeout()); + } catch (JSchException e) { + throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e); } Proxy proxy = null; - ProxyInfo proxyInfo = getProxyInfo( ProxyInfo.PROXY_SOCKS5, getRepository().getHost() ); - if ( proxyInfo != null && proxyInfo.getHost() != null ) - { - proxy = new ProxySOCKS5( proxyInfo.getHost(), proxyInfo.getPort() ); - ( (ProxySOCKS5) proxy ).setUserPasswd( proxyInfo.getUserName(), proxyInfo.getPassword() ); - } - else - { - proxyInfo = getProxyInfo( ProxyInfo.PROXY_HTTP, getRepository().getHost() ); - if ( proxyInfo != null && proxyInfo.getHost() != null ) - { - proxy = new ProxyHTTP( proxyInfo.getHost(), proxyInfo.getPort() ); - ( (ProxyHTTP) proxy ).setUserPasswd( proxyInfo.getUserName(), proxyInfo.getPassword() ); - } - else - { + ProxyInfo proxyInfo = + getProxyInfo(ProxyInfo.PROXY_SOCKS5, getRepository().getHost()); + if (proxyInfo != null && proxyInfo.getHost() != null) { + proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort()); + ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); + } else { + proxyInfo = getProxyInfo(ProxyInfo.PROXY_HTTP, getRepository().getHost()); + if (proxyInfo != null && proxyInfo.getHost() != null) { + proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort()); + ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); + } else { // Backwards compatibility - proxyInfo = getProxyInfo( getRepository().getProtocol(), getRepository().getHost() ); - if ( proxyInfo != null && proxyInfo.getHost() != null ) - { + proxyInfo = getProxyInfo( + getRepository().getProtocol(), getRepository().getHost()); + if (proxyInfo != null && proxyInfo.getHost() != null) { // if port == 1080 we will use SOCKS5 Proxy, otherwise will use HTTP Proxy - if ( proxyInfo.getPort() == SOCKS5_PROXY_PORT ) - { - proxy = new ProxySOCKS5( proxyInfo.getHost(), proxyInfo.getPort() ); - ( (ProxySOCKS5) proxy ).setUserPasswd( proxyInfo.getUserName(), proxyInfo.getPassword() ); - } - else - { - proxy = new ProxyHTTP( proxyInfo.getHost(), proxyInfo.getPort() ); - ( (ProxyHTTP) proxy ).setUserPasswd( proxyInfo.getUserName(), proxyInfo.getPassword() ); + if (proxyInfo.getPort() == SOCKS5_PROXY_PORT) { + proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort()); + ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); + } else { + proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort()); + ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); } } } } - session.setProxy( proxy ); + session.setProxy(proxy); // username and password will be given via UserInfo interface. - UserInfo ui = new WagonUserInfo( authenticationInfo, getInteractiveUserInfo() ); + UserInfo ui = new WagonUserInfo(authenticationInfo, getInteractiveUserInfo()); - if ( uIKeyboardInteractive != null ) - { - ui = new UserInfoUIKeyboardInteractiveProxy( ui, uIKeyboardInteractive ); + if (uIKeyboardInteractive != null) { + ui = new UserInfoUIKeyboardInteractiveProxy(ui, uIKeyboardInteractive); } Properties config = new Properties(); - if ( getKnownHostsProvider() != null ) - { - try - { + if (getKnownHostsProvider() != null) { + try { String contents = getKnownHostsProvider().getContents(); - if ( contents != null ) - { - sch.setKnownHosts( new ByteArrayInputStream( contents.getBytes() ) ); + if (contents != null) { + sch.setKnownHosts(new ByteArrayInputStream(contents.getBytes())); } - } - catch ( JSchException e ) - { + } catch (JSchException e) { // continue without known_hosts } - if ( strictHostKeyChecking == null ) - { + if (strictHostKeyChecking == null) { strictHostKeyChecking = getKnownHostsProvider().getHostKeyChecking(); } - config.setProperty( "StrictHostKeyChecking", strictHostKeyChecking ); + config.setProperty("StrictHostKeyChecking", strictHostKeyChecking); } - if ( preferredAuthentications != null ) - { - config.setProperty( "PreferredAuthentications", preferredAuthentications ); + if (preferredAuthentications != null) { + config.setProperty("PreferredAuthentications", preferredAuthentications); } - config.setProperty( "BatchMode", interactive ? "no" : "yes" ); + config.setProperty("BatchMode", interactive ? "no" : "yes"); - session.setConfig( config ); + session.setConfig(config); - session.setUserInfo( ui ); + session.setUserInfo(ui); - try - { + try { session.connect(); - } - catch ( JSchException e ) - { - if ( e.getMessage().startsWith( "UnknownHostKey:" ) || e.getMessage().startsWith( "reject HostKey:" ) ) - { - throw new UnknownHostException( host, e ); - } - else if ( e.getMessage().contains( "HostKey has been changed" ) ) - { - throw new KnownHostChangedException( host, e ); - } - else - { - throw new AuthenticationException( "Cannot connect. Reason: " + e.getMessage(), e ); + } catch (JSchException e) { + if (e.getMessage().startsWith("UnknownHostKey:") || e.getMessage().startsWith("reject HostKey:")) { + throw new UnknownHostException(host, e); + } else if (e.getMessage().contains("HostKey has been changed")) { + throw new KnownHostChangedException(host, e); + } else { + throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e); } } - if ( getKnownHostsProvider() != null ) - { + if (getKnownHostsProvider() != null) { HostKeyRepository hkr = sch.getHostKeyRepository(); - HostKey[] hk = hkr.getHostKey( host, null ); - try - { - if ( hk != null ) - { - for ( HostKey hostKey : hk ) - { - KnownHostEntry knownHostEntry = new KnownHostEntry( hostKey.getHost(), hostKey.getType(), - hostKey.getKey() ); - getKnownHostsProvider().addKnownHost( knownHostEntry ); + HostKey[] hk = hkr.getHostKey(host, null); + try { + if (hk != null) { + for (HostKey hostKey : hk) { + KnownHostEntry knownHostEntry = + new KnownHostEntry(hostKey.getHost(), hostKey.getType(), hostKey.getKey()); + getKnownHostsProvider().addKnownHost(knownHostEntry); } } - } - catch ( IOException e ) - { + } catch (IOException e) { closeConnection(); throw new AuthenticationException( - "Connection aborted - failed to write to known_hosts. Reason: " + e.getMessage(), e ); + "Connection aborted - failed to write to known_hosts. Reason: " + e.getMessage(), e); } } } - public void closeConnection() - { - if ( session != null ) - { + public void closeConnection() { + if (session != null) { session.disconnect(); session = null; } } - public Streams executeCommand( String command, boolean ignoreStdErr, boolean ignoreNoneZeroExitCode ) - throws CommandExecutionException - { + public Streams executeCommand(String command, boolean ignoreStdErr, boolean ignoreNoneZeroExitCode) + throws CommandExecutionException { ChannelExec channel = null; BufferedReader stdoutReader = null; BufferedReader stderrReader = null; Streams streams = null; - try - { - channel = (ChannelExec) session.openChannel( EXEC_CHANNEL ); + try { + channel = (ChannelExec) session.openChannel(EXEC_CHANNEL); - fireSessionDebug( "Executing: " + command ); - channel.setCommand( command + "\n" ); + fireSessionDebug("Executing: " + command); + channel.setCommand(command + "\n"); - stdoutReader = new BufferedReader( new InputStreamReader( channel.getInputStream() ) ); - stderrReader = new BufferedReader( new InputStreamReader( channel.getErrStream() ) ); + stdoutReader = new BufferedReader(new InputStreamReader(channel.getInputStream())); + stderrReader = new BufferedReader(new InputStreamReader(channel.getErrStream())); channel.connect(); - streams = CommandExecutorStreamProcessor.processStreams( stderrReader, stdoutReader ); + streams = CommandExecutorStreamProcessor.processStreams(stderrReader, stdoutReader); stdoutReader.close(); stdoutReader = null; @@ -347,166 +286,132 @@ public Streams executeCommand( String command, boolean ignoreStdErr, boolean ign int exitCode = channel.getExitStatus(); - if ( streams.getErr().length() > 0 && !ignoreStdErr ) - { - throw new CommandExecutionException( "Exit code: " + exitCode + " - " + streams.getErr() ); + if (streams.getErr().length() > 0 && !ignoreStdErr) { + throw new CommandExecutionException("Exit code: " + exitCode + " - " + streams.getErr()); } - if ( exitCode != 0 && !ignoreNoneZeroExitCode ) - { - throw new CommandExecutionException( "Exit code: " + exitCode + " - " + streams.getErr() ); + if (exitCode != 0 && !ignoreNoneZeroExitCode) { + throw new CommandExecutionException("Exit code: " + exitCode + " - " + streams.getErr()); } return streams; - } - catch ( IOException e ) - { - throw new CommandExecutionException( "Cannot execute remote command: " + command, e ); - } - catch ( JSchException e ) - { - throw new CommandExecutionException( "Cannot execute remote command: " + command, e ); - } - finally - { - if ( streams != null ) - { - fireSessionDebug( "Stdout results:" + streams.getOut() ); - fireSessionDebug( "Stderr results:" + streams.getErr() ); + } catch (IOException e) { + throw new CommandExecutionException("Cannot execute remote command: " + command, e); + } catch (JSchException e) { + throw new CommandExecutionException("Cannot execute remote command: " + command, e); + } finally { + if (streams != null) { + fireSessionDebug("Stdout results:" + streams.getOut()); + fireSessionDebug("Stderr results:" + streams.getErr()); } - IOUtil.close( stdoutReader ); - IOUtil.close( stderrReader ); - if ( channel != null ) - { + IOUtil.close(stdoutReader); + IOUtil.close(stderrReader); + if (channel != null) { channel.disconnect(); } } } - protected void handleGetException( Resource resource, Exception e ) - throws TransferFailedException - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); + protected void handleGetException(Resource resource, Exception e) throws TransferFailedException { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); - String msg = - "Error occurred while downloading '" + resource + "' from the remote repository:" + getRepository() + ": " - + e.getMessage(); + String msg = "Error occurred while downloading '" + resource + "' from the remote repository:" + getRepository() + + ": " + e.getMessage(); - throw new TransferFailedException( msg, e ); + throw new TransferFailedException(msg, e); } - public List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - return sshTool.getFileList( destinationDirectory, repository ); + public List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + return sshTool.getFileList(destinationDirectory, repository); } - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - sshTool.putDirectory( this, sourceDirectory, destinationDirectory ); + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + sshTool.putDirectory(this, sourceDirectory, destinationDirectory); } - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - return sshTool.resourceExists( resourceName, repository ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + return sshTool.resourceExists(resourceName, repository); } - public boolean supportsDirectoryCopy() - { + public boolean supportsDirectoryCopy() { return true; } - public void executeCommand( String command ) - throws CommandExecutionException - { - fireTransferDebug( "Executing command: " + command ); + public void executeCommand(String command) throws CommandExecutionException { + fireTransferDebug("Executing command: " + command); - //backward compatible with wagon 2.10 - executeCommand( command, false, true ); + // backward compatible with wagon 2.10 + executeCommand(command, false, true); } - public Streams executeCommand( String command, boolean ignoreFailures ) - throws CommandExecutionException - { - fireTransferDebug( "Executing command: " + command ); + public Streams executeCommand(String command, boolean ignoreFailures) throws CommandExecutionException { + fireTransferDebug("Executing command: " + command); - //backward compatible with wagon 2.10 - return executeCommand( command, ignoreFailures, true ); + // backward compatible with wagon 2.10 + return executeCommand(command, ignoreFailures, true); } - public InteractiveUserInfo getInteractiveUserInfo() - { + public InteractiveUserInfo getInteractiveUserInfo() { return this.interactiveUserInfo; } - public KnownHostsProvider getKnownHostsProvider() - { + public KnownHostsProvider getKnownHostsProvider() { return this.knownHostsProvider; } - public void setInteractiveUserInfo( InteractiveUserInfo interactiveUserInfo ) - { + public void setInteractiveUserInfo(InteractiveUserInfo interactiveUserInfo) { this.interactiveUserInfo = interactiveUserInfo; } - public void setKnownHostsProvider( KnownHostsProvider knownHostsProvider ) - { + public void setKnownHostsProvider(KnownHostsProvider knownHostsProvider) { this.knownHostsProvider = knownHostsProvider; } - public void setUIKeyboardInteractive( UIKeyboardInteractive uIKeyboardInteractive ) - { + public void setUIKeyboardInteractive(UIKeyboardInteractive uIKeyboardInteractive) { this.uIKeyboardInteractive = uIKeyboardInteractive; } - public String getPreferredAuthentications() - { + public String getPreferredAuthentications() { return preferredAuthentications; } - public void setPreferredAuthentications( String preferredAuthentications ) - { + public void setPreferredAuthentications(String preferredAuthentications) { this.preferredAuthentications = preferredAuthentications; } - public String getStrictHostKeyChecking() - { + public String getStrictHostKeyChecking() { return strictHostKeyChecking; } - public void setStrictHostKeyChecking( String strictHostKeyChecking ) - { + public void setStrictHostKeyChecking(String strictHostKeyChecking) { this.strictHostKeyChecking = strictHostKeyChecking; } /** {@inheritDoc} */ // This method will be removed as soon as JSch issue #122 is resolved @Override - protected void transfer( Resource resource, InputStream input, OutputStream output, int requestType, long maxSize ) - throws IOException - { + protected void transfer(Resource resource, InputStream input, OutputStream output, int requestType, long maxSize) + throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - TransferEvent transferEvent = new TransferEvent( this, resource, TransferEvent.TRANSFER_PROGRESS, requestType ); - transferEvent.setTimestamp( System.currentTimeMillis() ); + TransferEvent transferEvent = new TransferEvent(this, resource, TransferEvent.TRANSFER_PROGRESS, requestType); + transferEvent.setTimestamp(System.currentTimeMillis()); long remaining = maxSize; - while ( remaining > 0L ) - { + while (remaining > 0L) { // let's safely cast to int because the min value will be lower than the buffer size. - int n = input.read( buffer, 0, (int) Math.min( buffer.length, remaining ) ); + int n = input.read(buffer, 0, (int) Math.min(buffer.length, remaining)); - if ( n == -1 ) - { + if (n == -1) { break; } - fireTransferProgress( transferEvent, buffer, n ); + fireTransferProgress(transferEvent, buffer, n); - output.write( buffer, 0, n ); + output.write(buffer, 0, n); remaining -= n; } diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpCommandExecutor.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpCommandExecutor.java index 0f14468f6..f0757e7af 100644 --- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpCommandExecutor.java +++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpCommandExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,24 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; /** - * ScpCommandExecutor - bridge class for plexus:descriptor + * ScpCommandExecutor - bridge class for plexus:descriptor * * @author Joakim Erdfelt * - * + * * @todo is this even needed anymore? - * + * * @plexus.component role="org.apache.maven.wagon.CommandExecutor" - * role-hint="scp" + * role-hint="scp" * instantiation-strategy="per-lookup" */ -public class ScpCommandExecutor - extends ScpWagon -{ - public ScpCommandExecutor() - { +public class ScpCommandExecutor extends ScpWagon { + public ScpCommandExecutor() { super(); } } diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagon.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagon.java index 7f96c7792..978f225e7 100644 --- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagon.java +++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSchException; @@ -31,11 +35,6 @@ import org.apache.maven.wagon.repository.RepositoryPermissions; import org.apache.maven.wagon.resource.Resource; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - /** * SCP protocol wagon. *

    @@ -52,9 +51,7 @@ * role-hint="scp" * instantiation-strategy="per-lookup" */ -public class ScpWagon - extends AbstractJschWagon -{ +public class ScpWagon extends AbstractJschWagon { private static final char COPY_START_CHAR = 'C'; private static final char ACK_SEPARATOR = ' '; @@ -71,304 +68,247 @@ public class ScpWagon private OutputStream channelOutputStream; - private void setFileGroup( RepositoryPermissions permissions, String basedir, Resource resource ) - throws CommandExecutionException - { - if ( permissions != null && permissions.getGroup() != null ) - { - //executeCommand( "chgrp -f " + permissions.getGroup() + " " + getPath( basedir, resource.getName() ) ); - executeCommand( "chgrp -f " + permissions.getGroup() + " \"" + getPath( basedir, resource.getName() ) - + "\"" ); + private void setFileGroup(RepositoryPermissions permissions, String basedir, Resource resource) + throws CommandExecutionException { + if (permissions != null && permissions.getGroup() != null) { + // executeCommand( "chgrp -f " + permissions.getGroup() + " " + getPath( basedir, resource.getName() ) ); + executeCommand("chgrp -f " + permissions.getGroup() + " \"" + getPath(basedir, resource.getName()) + "\""); } } - protected void cleanupPutTransfer( Resource resource ) - { - if ( channel != null ) - { + protected void cleanupPutTransfer(Resource resource) { + if (channel != null) { channel.disconnect(); channel = null; } } - protected void finishPutTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException - { - try - { - sendEom( output ); + protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException { + try { + sendEom(output); - checkAck( channelInputStream ); + checkAck(channelInputStream); // This came from SCPClient in Ganymede SSH2. It is sent after all files. - output.write( END_OF_FILES_MSG.getBytes() ); + output.write(END_OF_FILES_MSG.getBytes()); output.flush(); - } - catch ( IOException e ) - { - handleIOException( resource, e ); + } catch (IOException e) { + handleIOException(resource, e); } String basedir = getRepository().getBasedir(); - try - { - setFileGroup( getRepository().getPermissions(), basedir, resource ); - } - catch ( CommandExecutionException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + try { + setFileGroup(getRepository().getPermissions(), basedir, resource); + } catch (CommandExecutionException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( e.getMessage(), e ); + throw new TransferFailedException(e.getMessage(), e); } } - private void checkAck( InputStream in ) - throws IOException - { + private void checkAck(InputStream in) throws IOException { int code = in.read(); - if ( code == -1 ) - { - throw new IOException( "Unexpected end of data" ); - } - else if ( code == 1 ) - { - String line = readLine( in ); - - throw new IOException( "SCP terminated with error: '" + line + "'" ); - } - else if ( code == 2 ) - { - throw new IOException( "SCP terminated with error (code: " + code + ")" ); - } - else if ( code != 0 ) - { - throw new IOException( "SCP terminated with unknown error code" ); + if (code == -1) { + throw new IOException("Unexpected end of data"); + } else if (code == 1) { + String line = readLine(in); + + throw new IOException("SCP terminated with error: '" + line + "'"); + } else if (code == 2) { + throw new IOException("SCP terminated with error (code: " + code + ")"); + } else if (code != 0) { + throw new IOException("SCP terminated with unknown error code"); } } - protected void finishGetTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException - { - try - { - checkAck( input ); + protected void finishGetTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException { + try { + checkAck(input); - sendEom( channelOutputStream ); - } - catch ( IOException e ) - { - handleGetException( resource, e ); + sendEom(channelOutputStream); + } catch (IOException e) { + handleGetException(resource, e); } } - protected void cleanupGetTransfer( Resource resource ) - { - if ( channel != null ) - { + protected void cleanupGetTransfer(Resource resource) { + if (channel != null) { channel.disconnect(); } } @Deprecated - protected void getTransfer( Resource resource, OutputStream output, InputStream input, boolean closeInput, - int maxSize ) - throws TransferFailedException - { - super.getTransfer( resource, output, input, closeInput, (int) resource.getContentLength() ); + protected void getTransfer( + Resource resource, OutputStream output, InputStream input, boolean closeInput, int maxSize) + throws TransferFailedException { + super.getTransfer(resource, output, input, closeInput, (int) resource.getContentLength()); } - protected void getTransfer( Resource resource, OutputStream output, InputStream input, boolean closeInput, - long maxSize ) - throws TransferFailedException - { - super.getTransfer( resource, output, input, closeInput, resource.getContentLength() ); + protected void getTransfer( + Resource resource, OutputStream output, InputStream input, boolean closeInput, long maxSize) + throws TransferFailedException { + super.getTransfer(resource, output, input, closeInput, resource.getContentLength()); } - protected String readLine( InputStream in ) - throws IOException - { + protected String readLine(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); - while ( true ) - { - if ( sb.length() > LINE_BUFFER_SIZE ) - { - throw new IOException( "Remote server sent a too long line" ); + while (true) { + if (sb.length() > LINE_BUFFER_SIZE) { + throw new IOException("Remote server sent a too long line"); } int c = in.read(); - if ( c < 0 ) - { - throw new IOException( "Remote connection terminated unexpectedly." ); + if (c < 0) { + throw new IOException("Remote connection terminated unexpectedly."); } - if ( c == LF ) - { + if (c == LF) { break; } - sb.append( (char) c ); + sb.append((char) c); } return sb.toString(); } - protected static void sendEom( OutputStream out ) - throws IOException - { - out.write( 0 ); + protected static void sendEom(OutputStream out) throws IOException { + out.write(0); out.flush(); } - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException - { + public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException { Resource resource = inputData.getResource(); - String path = getPath( getRepository().getBasedir(), resource.getName() ); - //String cmd = "scp -p -f " + path; + String path = getPath(getRepository().getBasedir(), resource.getName()); + // String cmd = "scp -p -f " + path; String cmd = "scp -p -f \"" + path + "\""; - fireTransferDebug( "Executing command: " + cmd ); + fireTransferDebug("Executing command: " + cmd); - try - { - channel = (ChannelExec) session.openChannel( EXEC_CHANNEL ); + try { + channel = (ChannelExec) session.openChannel(EXEC_CHANNEL); - channel.setCommand( cmd ); + channel.setCommand(cmd); // get I/O streams for remote scp channelOutputStream = channel.getOutputStream(); InputStream in = channel.getInputStream(); - inputData.setInputStream( in ); + inputData.setInputStream(in); channel.connect(); - sendEom( channelOutputStream ); + sendEom(channelOutputStream); int exitCode = in.read(); - if ( exitCode == 'T' ) - { - String line = readLine( in ); + if (exitCode == 'T') { + String line = readLine(in); - String[] times = line.split( " " ); + String[] times = line.split(" "); - resource.setLastModified( Long.valueOf( times[0] ).longValue() * 1000 ); + resource.setLastModified(Long.valueOf(times[0]).longValue() * 1000); - sendEom( channelOutputStream ); + sendEom(channelOutputStream); exitCode = in.read(); } - String line = readLine( in ); + String line = readLine(in); - if ( exitCode != COPY_START_CHAR ) - { - if ( exitCode == 1 && ( line.contains( "No such file or directory" ) - || line.indexOf( "no such file or directory" ) != 1 ) ) - { - throw new ResourceDoesNotExistException( line ); - } - else - { - throw new IOException( "Exit code: " + exitCode + " - " + line ); + if (exitCode != COPY_START_CHAR) { + if (exitCode == 1 + && (line.contains("No such file or directory") + || line.indexOf("no such file or directory") != 1)) { + throw new ResourceDoesNotExistException(line); + } else { + throw new IOException("Exit code: " + exitCode + " - " + line); } } - if ( line == null ) - { - throw new EOFException( "Unexpected end of data" ); + if (line == null) { + throw new EOFException("Unexpected end of data"); } - String perms = line.substring( 0, 4 ); - fireTransferDebug( "Remote file permissions: " + perms ); + String perms = line.substring(0, 4); + fireTransferDebug("Remote file permissions: " + perms); - if ( line.charAt( 4 ) != ACK_SEPARATOR && line.charAt( 5 ) != ACK_SEPARATOR ) - { - throw new IOException( "Invalid transfer header: " + line ); + if (line.charAt(4) != ACK_SEPARATOR && line.charAt(5) != ACK_SEPARATOR) { + throw new IOException("Invalid transfer header: " + line); } - int index = line.indexOf( ACK_SEPARATOR, 5 ); - if ( index < 0 ) - { - throw new IOException( "Invalid transfer header: " + line ); + int index = line.indexOf(ACK_SEPARATOR, 5); + if (index < 0) { + throw new IOException("Invalid transfer header: " + line); } - long filesize = Long.parseLong( line.substring( 5, index ) ); - fireTransferDebug( "Remote file size: " + filesize ); + long filesize = Long.parseLong(line.substring(5, index)); + fireTransferDebug("Remote file size: " + filesize); - resource.setContentLength( filesize ); + resource.setContentLength(filesize); - String filename = line.substring( index + 1 ); - fireTransferDebug( "Remote filename: " + filename ); + String filename = line.substring(index + 1); + fireTransferDebug("Remote filename: " + filename); - sendEom( channelOutputStream ); - } - catch ( JSchException e ) - { - handleGetException( resource, e ); - } - catch ( IOException e ) - { - handleGetException( resource, e ); + sendEom(channelOutputStream); + } catch (JSchException e) { + handleGetException(resource, e); + } catch (IOException e) { + handleGetException(resource, e); } } - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { + public void fillOutputData(OutputData outputData) throws TransferFailedException { Resource resource = outputData.getResource(); String basedir = getRepository().getBasedir(); - String path = getPath( basedir, resource.getName() ); + String path = getPath(basedir, resource.getName()); - String dir = ScpHelper.getResourceDirectory( resource.getName() ); + String dir = ScpHelper.getResourceDirectory(resource.getName()); - try - { - sshTool.createRemoteDirectories( getPath( basedir, dir ), getRepository().getPermissions() ); - } - catch ( CommandExecutionException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + try { + sshTool.createRemoteDirectories( + getPath(basedir, dir), getRepository().getPermissions()); + } catch (CommandExecutionException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - throw new TransferFailedException( e.getMessage(), e ); + throw new TransferFailedException(e.getMessage(), e); } - String octalMode = getOctalMode( getRepository().getPermissions() ); + String octalMode = getOctalMode(getRepository().getPermissions()); // exec 'scp -p -t rfile' remotely String command = "scp"; - if ( octalMode != null ) - { + if (octalMode != null) { command += " -p"; } command += " -t \"" + path + "\""; - fireTransferDebug( "Executing command: " + command ); + fireTransferDebug("Executing command: " + command); String resourceName = resource.getName(); OutputStream out = null; - try - { - channel = (ChannelExec) session.openChannel( EXEC_CHANNEL ); + try { + channel = (ChannelExec) session.openChannel(EXEC_CHANNEL); - channel.setCommand( command ); + channel.setCommand(command); // get I/O streams for remote scp out = channel.getOutputStream(); - outputData.setOutputStream( out ); + outputData.setOutputStream(out); channelInputStream = channel.getInputStream(); channel.connect(); - checkAck( channelInputStream ); + checkAck(channelInputStream); // send "C0644 filesize filename", where filename should not include '/' long filesize = resource.getContentLength(); @@ -376,75 +316,57 @@ public void fillOutputData( OutputData outputData ) String mode = octalMode == null ? "0644" : octalMode; command = "C" + mode + " " + filesize + " "; - if ( resourceName.lastIndexOf( ScpHelper.PATH_SEPARATOR ) > 0 ) - { - command += resourceName.substring( resourceName.lastIndexOf( ScpHelper.PATH_SEPARATOR ) + 1 ); - } - else - { + if (resourceName.lastIndexOf(ScpHelper.PATH_SEPARATOR) > 0) { + command += resourceName.substring(resourceName.lastIndexOf(ScpHelper.PATH_SEPARATOR) + 1); + } else { command += resourceName; } command += "\n"; - out.write( command.getBytes() ); + out.write(command.getBytes()); out.flush(); - checkAck( channelInputStream ); - } - catch ( JSchException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + checkAck(channelInputStream); + } catch (JSchException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); String msg = "Error occurred while deploying '" + resourceName + "' to remote repository: " - + getRepository().getUrl() + ": " + e.getMessage(); + + getRepository().getUrl() + ": " + e.getMessage(); - throw new TransferFailedException( msg, e ); - } - catch ( IOException e ) - { - handleIOException( resource, e ); + throw new TransferFailedException(msg, e); + } catch (IOException e) { + handleIOException(resource, e); } } - private void handleIOException( Resource resource, IOException e ) - throws TransferFailedException - { - if ( e.getMessage().contains( "set mode: Operation not permitted" ) ) - { - fireTransferDebug( e.getMessage() ); - } - else - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + private void handleIOException(Resource resource, IOException e) throws TransferFailedException { + if (e.getMessage().contains("set mode: Operation not permitted")) { + fireTransferDebug(e.getMessage()); + } else { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); String msg = "Error occurred while deploying '" + resource.getName() + "' to remote repository: " - + getRepository().getUrl() + ": " + e.getMessage(); + + getRepository().getUrl() + ": " + e.getMessage(); - throw new TransferFailedException( msg, e ); + throw new TransferFailedException(msg, e); } } - public String getOctalMode( RepositoryPermissions permissions ) - { + public String getOctalMode(RepositoryPermissions permissions) { String mode = null; - if ( permissions != null && permissions.getFileMode() != null ) - { - if ( permissions.getFileMode().matches( "[0-9]{3,4}" ) ) - { + if (permissions != null && permissions.getFileMode() != null) { + if (permissions.getFileMode().matches("[0-9]{3,4}")) { mode = permissions.getFileMode(); - if ( mode.length() == 3 ) - { + if (mode.length() == 3) { mode = "0" + mode; } - } - else - { + } else { // TODO: calculate? // TODO: as warning - fireSessionDebug( "Not using non-octal permissions: " + permissions.getFileMode() ); + fireSessionDebug("Not using non-octal permissions: " + permissions.getFileMode()); } } return mode; diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagon.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagon.java index a37fe6cda..a9ec70643 100644 --- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagon.java +++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; import java.io.File; import java.io.InputStream; @@ -25,6 +24,10 @@ import java.util.ArrayList; import java.util.List; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpATTRS; +import com.jcraft.jsch.SftpException; import org.apache.maven.wagon.InputData; import org.apache.maven.wagon.OutputData; import org.apache.maven.wagon.PathUtils; @@ -37,11 +40,6 @@ import org.apache.maven.wagon.repository.RepositoryPermissions; import org.apache.maven.wagon.resource.Resource; -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.SftpATTRS; -import com.jcraft.jsch.SftpException; - /** * SFTP protocol wagon. * @@ -49,14 +47,12 @@ * * @todo [BP] add compression flag * @todo see if SftpProgressMonitor allows us to do streaming (without it, we can't do checksums as the input stream is lost) - * - * @plexus.component role="org.apache.maven.wagon.Wagon" + * + * @plexus.component role="org.apache.maven.wagon.Wagon" * role-hint="sftp" * instantiation-strategy="per-lookup" */ -public class SftpWagon - extends AbstractJschWagon -{ +public class SftpWagon extends AbstractJschWagon { private static final String SFTP_CHANNEL = "sftp"; private static final int S_IFDIR = 0x4000; @@ -64,150 +60,110 @@ public class SftpWagon private static final long MILLIS_PER_SEC = 1000L; private ChannelSftp channel; - - public void closeConnection() - { - if ( channel != null ) - { + + public void closeConnection() { + if (channel != null) { channel.disconnect(); } super.closeConnection(); } - public void openConnectionInternal() - throws AuthenticationException - { + public void openConnectionInternal() throws AuthenticationException { super.openConnectionInternal(); - try - { - channel = (ChannelSftp) session.openChannel( SFTP_CHANNEL ); + try { + channel = (ChannelSftp) session.openChannel(SFTP_CHANNEL); channel.connect(); - } - catch ( JSchException e ) - { - throw new AuthenticationException( "Error connecting to remote repository: " + getRepository().getUrl(), - e ); + } catch (JSchException e) { + throw new AuthenticationException( + "Error connecting to remote repository: " + getRepository().getUrl(), e); } } - private void returnToParentDirectory( Resource resource ) - { - try - { - String dir = ScpHelper.getResourceDirectory( resource.getName() ); - String[] dirs = PathUtils.dirnames( dir ); - for ( String d : dirs ) - { - channel.cd( ".." ); + private void returnToParentDirectory(Resource resource) { + try { + String dir = ScpHelper.getResourceDirectory(resource.getName()); + String[] dirs = PathUtils.dirnames(dir); + for (String d : dirs) { + channel.cd(".."); } - } - catch ( SftpException e ) - { - fireTransferDebug( "Error returning to parent directory: " + e.getMessage() ); + } catch (SftpException e) { + fireTransferDebug("Error returning to parent directory: " + e.getMessage()); } } - private void putFile( File source, Resource resource, RepositoryPermissions permissions ) - throws SftpException, TransferFailedException - { - resource.setContentLength( source.length() ); - - resource.setLastModified( source.lastModified() ); - - String filename = ScpHelper.getResourceFilename( resource.getName() ); + private void putFile(File source, Resource resource, RepositoryPermissions permissions) + throws SftpException, TransferFailedException { + resource.setContentLength(source.length()); + + resource.setLastModified(source.lastModified()); + + String filename = ScpHelper.getResourceFilename(resource.getName()); - firePutStarted( resource, source ); + firePutStarted(resource, source); - channel.put( source.getAbsolutePath(), filename ); + channel.put(source.getAbsolutePath(), filename); - postProcessListeners( resource, source, TransferEvent.REQUEST_PUT ); + postProcessListeners(resource, source, TransferEvent.REQUEST_PUT); - if ( permissions != null && permissions.getGroup() != null ) - { - setGroup( filename, permissions ); + if (permissions != null && permissions.getGroup() != null) { + setGroup(filename, permissions); } - if ( permissions != null && permissions.getFileMode() != null ) - { - setFileMode( filename, permissions ); + if (permissions != null && permissions.getFileMode() != null) { + setFileMode(filename, permissions); } - firePutCompleted( resource, source ); + firePutCompleted(resource, source); } - private void setGroup( String filename, RepositoryPermissions permissions ) - { - try - { - int group = Integer.valueOf( permissions.getGroup() ).intValue(); - channel.chgrp( group, filename ); - } - catch ( NumberFormatException e ) - { + private void setGroup(String filename, RepositoryPermissions permissions) { + try { + int group = Integer.valueOf(permissions.getGroup()).intValue(); + channel.chgrp(group, filename); + } catch (NumberFormatException e) { // TODO: warning level - fireTransferDebug( "Not setting group: must be a numerical GID for SFTP" ); - } - catch ( SftpException e ) - { - fireTransferDebug( "Not setting group: " + e.getMessage() ); + fireTransferDebug("Not setting group: must be a numerical GID for SFTP"); + } catch (SftpException e) { + fireTransferDebug("Not setting group: " + e.getMessage()); } } - private void setFileMode( String filename, RepositoryPermissions permissions ) - { - try - { - int mode = getOctalMode( permissions.getFileMode() ); - channel.chmod( mode, filename ); - } - catch ( NumberFormatException e ) - { + private void setFileMode(String filename, RepositoryPermissions permissions) { + try { + int mode = getOctalMode(permissions.getFileMode()); + channel.chmod(mode, filename); + } catch (NumberFormatException e) { // TODO: warning level - fireTransferDebug( "Not setting mode: must be a numerical mode for SFTP" ); - } - catch ( SftpException e ) - { - fireTransferDebug( "Not setting mode: " + e.getMessage() ); + fireTransferDebug("Not setting mode: must be a numerical mode for SFTP"); + } catch (SftpException e) { + fireTransferDebug("Not setting mode: " + e.getMessage()); } } - private void mkdirs( String resourceName, int mode ) - throws SftpException, TransferFailedException - { - String[] dirs = PathUtils.dirnames( resourceName ); - for ( String dir : dirs ) - { - mkdir( dir, mode ); + private void mkdirs(String resourceName, int mode) throws SftpException, TransferFailedException { + String[] dirs = PathUtils.dirnames(resourceName); + for (String dir : dirs) { + mkdir(dir, mode); - channel.cd( dir ); + channel.cd(dir); } } - private void mkdir( String dir, int mode ) - throws TransferFailedException, SftpException - { - try - { - SftpATTRS attrs = channel.stat( dir ); - if ( ( attrs.getPermissions() & S_IFDIR ) == 0 ) - { - throw new TransferFailedException( "Remote path is not a directory: " + dir ); + private void mkdir(String dir, int mode) throws TransferFailedException, SftpException { + try { + SftpATTRS attrs = channel.stat(dir); + if ((attrs.getPermissions() & S_IFDIR) == 0) { + throw new TransferFailedException("Remote path is not a directory: " + dir); } - } - catch ( SftpException e ) - { + } catch (SftpException e) { // doesn't exist, make it and try again - channel.mkdir( dir ); - if ( mode != -1 ) - { - try - { - channel.chmod( mode, dir ); - } - catch ( SftpException e1 ) - { + channel.mkdir(dir); + if (mode != -1) { + try { + channel.chmod(mode, dir); + } catch (SftpException e1) { // for some extrange reason we recive this exception, // even when chmod success } @@ -215,353 +171,274 @@ private void mkdir( String dir, int mode ) } } - private SftpATTRS changeToRepositoryDirectory( String dir, String filename ) - throws ResourceDoesNotExistException, SftpException - { + private SftpATTRS changeToRepositoryDirectory(String dir, String filename) + throws ResourceDoesNotExistException, SftpException { // This must be called first to ensure that if the file doesn't exist it throws an exception SftpATTRS attrs; - try - { - channel.cd( repository.getBasedir() ); + try { + channel.cd(repository.getBasedir()); - if ( dir.length() > 0 ) - { - channel.cd( dir ); + if (dir.length() > 0) { + channel.cd(dir); } - if ( filename.length() == 0 ) - { + if (filename.length() == 0) { filename = "."; } - - attrs = channel.stat( filename ); - } - catch ( SftpException e ) - { - if ( e.toString().trim().endsWith( "No such file" ) ) - { - throw new ResourceDoesNotExistException( e.toString(), e ); - } - else if ( e.toString().trim().contains( "Can't change directory" ) ) - { - throw new ResourceDoesNotExistException( e.toString(), e ); - } - else - { + + attrs = channel.stat(filename); + } catch (SftpException e) { + if (e.toString().trim().endsWith("No such file")) { + throw new ResourceDoesNotExistException(e.toString(), e); + } else if (e.toString().trim().contains("Can't change directory")) { + throw new ResourceDoesNotExistException(e.toString(), e); + } else { throw e; } } return attrs; } - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { final RepositoryPermissions permissions = repository.getPermissions(); - try - { - channel.cd( "/" ); - + try { + channel.cd("/"); + String basedir = getRepository().getBasedir(); - int directoryMode = getDirectoryMode( permissions ); - - mkdirs( basedir + "/", directoryMode ); - - fireTransferDebug( "Recursively uploading directory " + sourceDirectory.getAbsolutePath() + " as " - + destinationDirectory ); - - mkdirs( destinationDirectory, directoryMode ); - ftpRecursivePut( sourceDirectory, null, ScpHelper.getResourceFilename( destinationDirectory ), - directoryMode ); - } - catch ( SftpException e ) - { - String msg = - "Error occurred while deploying '" + sourceDirectory.getAbsolutePath() + "' " + "to remote repository: " - + getRepository().getUrl() + ": " + e.getMessage(); + int directoryMode = getDirectoryMode(permissions); + + mkdirs(basedir + "/", directoryMode); - throw new TransferFailedException( msg, e ); + fireTransferDebug("Recursively uploading directory " + sourceDirectory.getAbsolutePath() + " as " + + destinationDirectory); + + mkdirs(destinationDirectory, directoryMode); + ftpRecursivePut(sourceDirectory, null, ScpHelper.getResourceFilename(destinationDirectory), directoryMode); + } catch (SftpException e) { + String msg = "Error occurred while deploying '" + sourceDirectory.getAbsolutePath() + "' " + + "to remote repository: " + getRepository().getUrl() + ": " + e.getMessage(); + + throw new TransferFailedException(msg, e); } } - private void ftpRecursivePut( File sourceFile, String prefix, String fileName, int directoryMode ) - throws TransferFailedException, SftpException - { + private void ftpRecursivePut(File sourceFile, String prefix, String fileName, int directoryMode) + throws TransferFailedException, SftpException { final RepositoryPermissions permissions = repository.getPermissions(); - if ( sourceFile.isDirectory() ) - { + if (sourceFile.isDirectory()) { // ScpHelper.getResourceFilename( destinationDirectory ) - could return empty string - if ( !fileName.equals( "." ) && !fileName.equals( "" ) ) - { - prefix = getFileName( prefix, fileName ); - mkdir( fileName, directoryMode ); - channel.cd( fileName ); + if (!fileName.equals(".") && !fileName.equals("")) { + prefix = getFileName(prefix, fileName); + mkdir(fileName, directoryMode); + channel.cd(fileName); } File[] files = sourceFile.listFiles(); - if ( files != null && files.length > 0 ) - { + if (files != null && files.length > 0) { // Directories first, then files. Let's go deep early. - for ( File file : files ) - { - if ( file.isDirectory() ) - { - ftpRecursivePut( file, prefix, file.getName(), directoryMode ); + for (File file : files) { + if (file.isDirectory()) { + ftpRecursivePut(file, prefix, file.getName(), directoryMode); } } - for ( File file : files ) - { - if ( !file.isDirectory() ) - { - ftpRecursivePut( file, prefix, file.getName(), directoryMode ); + for (File file : files) { + if (!file.isDirectory()) { + ftpRecursivePut(file, prefix, file.getName(), directoryMode); } } } - - channel.cd( ".." ); - } - else - { - Resource resource = ScpHelper.getResource( getFileName( prefix, fileName ) ); - firePutInitiated( resource, sourceFile ); + channel.cd(".."); + } else { + Resource resource = ScpHelper.getResource(getFileName(prefix, fileName)); - putFile( sourceFile, resource, permissions ); + firePutInitiated(resource, sourceFile); + + putFile(sourceFile, resource, permissions); } } - private String getFileName( String prefix, String fileName ) - { - if ( prefix != null ) - { + private String getFileName(String prefix, String fileName) { + if (prefix != null) { prefix = prefix + "/" + fileName; - } - else - { + } else { prefix = fileName; } return prefix; } - - public List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( destinationDirectory.length() == 0 ) - { + + public List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (destinationDirectory.length() == 0) { destinationDirectory = "."; } - - String filename = ScpHelper.getResourceFilename( destinationDirectory ); - String dir = ScpHelper.getResourceDirectory( destinationDirectory ); + String filename = ScpHelper.getResourceFilename(destinationDirectory); + + String dir = ScpHelper.getResourceDirectory(destinationDirectory); // we already setuped the root directory. Ignore beginning / - if ( dir.length() > 0 && dir.charAt( 0 ) == ScpHelper.PATH_SEPARATOR ) - { - dir = dir.substring( 1 ); + if (dir.length() > 0 && dir.charAt(0) == ScpHelper.PATH_SEPARATOR) { + dir = dir.substring(1); } - try - { - SftpATTRS attrs = changeToRepositoryDirectory( dir, filename ); - if ( ( attrs.getPermissions() & S_IFDIR ) == 0 ) - { - throw new TransferFailedException( "Remote path is not a directory:" + dir ); + try { + SftpATTRS attrs = changeToRepositoryDirectory(dir, filename); + if ((attrs.getPermissions() & S_IFDIR) == 0) { + throw new TransferFailedException("Remote path is not a directory:" + dir); } - @SuppressWarnings( "unchecked" ) - List fileList = channel.ls( filename ); - List files = new ArrayList<>( fileList.size() ); - for ( ChannelSftp.LsEntry entry : fileList ) - { + @SuppressWarnings("unchecked") + List fileList = channel.ls(filename); + List files = new ArrayList<>(fileList.size()); + for (ChannelSftp.LsEntry entry : fileList) { String name = entry.getFilename(); - if ( entry.getAttrs().isDir() ) - { - if ( !name.equals( "." ) && !name.equals( ".." ) ) - { - if ( !name.endsWith( "/" ) ) - { + if (entry.getAttrs().isDir()) { + if (!name.equals(".") && !name.equals("..")) { + if (!name.endsWith("/")) { name += "/"; } - files.add( name ); + files.add(name); } - } - else - { - files.add( name ); + } else { + files.add(name); } } return files; - } - catch ( SftpException e ) - { - String msg = - "Error occurred while listing '" + destinationDirectory + "' " + "on remote repository: " + } catch (SftpException e) { + String msg = "Error occurred while listing '" + destinationDirectory + "' " + "on remote repository: " + getRepository().getUrl() + ": " + e.getMessage(); - throw new TransferFailedException( msg, e ); + throw new TransferFailedException(msg, e); } } - - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - String filename = ScpHelper.getResourceFilename( resourceName ); - String dir = ScpHelper.getResourceDirectory( resourceName ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + String filename = ScpHelper.getResourceFilename(resourceName); + + String dir = ScpHelper.getResourceDirectory(resourceName); // we already setuped the root directory. Ignore beginning / - if ( dir.length() > 0 && dir.charAt( 0 ) == ScpHelper.PATH_SEPARATOR ) - { - dir = dir.substring( 1 ); + if (dir.length() > 0 && dir.charAt(0) == ScpHelper.PATH_SEPARATOR) { + dir = dir.substring(1); } - try - { - changeToRepositoryDirectory( dir, filename ); - + try { + changeToRepositoryDirectory(dir, filename); + return true; - } - catch ( ResourceDoesNotExistException e ) - { + } catch (ResourceDoesNotExistException e) { return false; - } - catch ( SftpException e ) - { - String msg = - "Error occurred while looking for '" + resourceName + "' " + "on remote repository: " + } catch (SftpException e) { + String msg = "Error occurred while looking for '" + resourceName + "' " + "on remote repository: " + getRepository().getUrl() + ": " + e.getMessage(); - throw new TransferFailedException( msg, e ); + throw new TransferFailedException(msg, e); } } - protected void cleanupGetTransfer( Resource resource ) - { - returnToParentDirectory( resource ); + protected void cleanupGetTransfer(Resource resource) { + returnToParentDirectory(resource); } - - protected void cleanupPutTransfer( Resource resource ) - { - returnToParentDirectory( resource ); + + protected void cleanupPutTransfer(Resource resource) { + returnToParentDirectory(resource); } - protected void finishPutTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException - { + protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException { RepositoryPermissions permissions = getRepository().getPermissions(); - String filename = ScpHelper.getResourceFilename( resource.getName() ); - if ( permissions != null && permissions.getGroup() != null ) - { - setGroup( filename, permissions ); + String filename = ScpHelper.getResourceFilename(resource.getName()); + if (permissions != null && permissions.getGroup() != null) { + setGroup(filename, permissions); } - - if ( permissions != null && permissions.getFileMode() != null ) - { - setFileMode( filename, permissions ); + + if (permissions != null && permissions.getFileMode() != null) { + setFileMode(filename, permissions); } } - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException - { + public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException { Resource resource = inputData.getResource(); - - String filename = ScpHelper.getResourceFilename( resource.getName() ); - String dir = ScpHelper.getResourceDirectory( resource.getName() ); + String filename = ScpHelper.getResourceFilename(resource.getName()); + + String dir = ScpHelper.getResourceDirectory(resource.getName()); // we already setuped the root directory. Ignore beginning / - if ( dir.length() > 0 && dir.charAt( 0 ) == ScpHelper.PATH_SEPARATOR ) - { - dir = dir.substring( 1 ); + if (dir.length() > 0 && dir.charAt(0) == ScpHelper.PATH_SEPARATOR) { + dir = dir.substring(1); } - try - { - SftpATTRS attrs = changeToRepositoryDirectory( dir, filename ); + try { + SftpATTRS attrs = changeToRepositoryDirectory(dir, filename); long lastModified = attrs.getMTime() * MILLIS_PER_SEC; - resource.setContentLength( attrs.getSize() ); + resource.setContentLength(attrs.getSize()); - resource.setLastModified( lastModified ); - - inputData.setInputStream( channel.get( filename ) ); - } - catch ( SftpException e ) - { - handleGetException( resource, e ); + resource.setLastModified(lastModified); + + inputData.setInputStream(channel.get(filename)); + } catch (SftpException e) { + handleGetException(resource, e); } } - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - int directoryMode = getDirectoryMode( getRepository().getPermissions() ); + public void fillOutputData(OutputData outputData) throws TransferFailedException { + int directoryMode = getDirectoryMode(getRepository().getPermissions()); Resource resource = outputData.getResource(); - - try - { - channel.cd( "/" ); + + try { + channel.cd("/"); String basedir = getRepository().getBasedir(); - mkdirs( basedir + "/", directoryMode ); + mkdirs(basedir + "/", directoryMode); - mkdirs( resource.getName(), directoryMode ); + mkdirs(resource.getName(), directoryMode); - String filename = ScpHelper.getResourceFilename( resource.getName() ); - outputData.setOutputStream( channel.put( filename ) ); - } - catch ( TransferFailedException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + String filename = ScpHelper.getResourceFilename(resource.getName()); + outputData.setOutputStream(channel.put(filename)); + } catch (TransferFailedException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; - } - catch ( SftpException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + } catch (SftpException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); - String msg = - "Error occurred while deploying '" + resource.getName() + "' " + "to remote repository: " + String msg = "Error occurred while deploying '" + resource.getName() + "' " + "to remote repository: " + getRepository().getUrl() + ": " + e.getMessage(); - throw new TransferFailedException( msg, e ); + throw new TransferFailedException(msg, e); } } - + /** * @param permissions repository's permissions * @return the directory mode for the repository or -1 if it * wasn't set */ - public int getDirectoryMode( RepositoryPermissions permissions ) - { + public int getDirectoryMode(RepositoryPermissions permissions) { int ret = -1; - if ( permissions != null ) - { - ret = getOctalMode( permissions.getDirectoryMode() ); + if (permissions != null) { + ret = getOctalMode(permissions.getDirectoryMode()); } return ret; } - public int getOctalMode( String mode ) - { + public int getOctalMode(String mode) { int ret; - try - { - ret = Integer.valueOf( mode, 8 ).intValue(); - } - catch ( NumberFormatException e ) - { + try { + ret = Integer.valueOf(mode, 8).intValue(); + } catch (NumberFormatException e) { // TODO: warning level - fireTransferDebug( "the file mode must be a numerical mode for SFTP" ); + fireTransferDebug("the file mode must be a numerical mode for SFTP"); ret = -1; } return ret; diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/WagonUserInfo.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/WagonUserInfo.java index 50a107b13..d56791d83 100644 --- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/WagonUserInfo.java +++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/WagonUserInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,27 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; import com.jcraft.jsch.UserInfo; import org.apache.maven.wagon.authentication.AuthenticationInfo; import org.apache.maven.wagon.providers.ssh.interactive.InteractiveUserInfo; /** - * WagonUserInfo + * WagonUserInfo * * */ -class WagonUserInfo - implements UserInfo -{ +class WagonUserInfo implements UserInfo { private final InteractiveUserInfo userInfo; private String password; private String passphrase; - WagonUserInfo( AuthenticationInfo authInfo, InteractiveUserInfo userInfo ) - { + WagonUserInfo(AuthenticationInfo authInfo, InteractiveUserInfo userInfo) { this.userInfo = userInfo; this.password = authInfo.getPassword(); @@ -46,44 +42,35 @@ class WagonUserInfo this.passphrase = authInfo.getPassphrase(); } - public String getPassphrase() - { + public String getPassphrase() { return passphrase; } - public String getPassword() - { + public String getPassword() { return password; } - public boolean promptPassphrase( String message ) - { - if ( passphrase == null && userInfo != null ) - { - passphrase = userInfo.promptPassphrase( message ); + public boolean promptPassphrase(String message) { + if (passphrase == null && userInfo != null) { + passphrase = userInfo.promptPassphrase(message); } return passphrase != null; } - public boolean promptPassword( String message ) - { - if ( password == null && userInfo != null ) - { - password = userInfo.promptPassword( message ); + public boolean promptPassword(String message) { + if (password == null && userInfo != null) { + password = userInfo.promptPassword(message); } return password != null; } - public boolean promptYesNo( String message ) - { - return userInfo != null && userInfo.promptYesNo( message ); + public boolean promptYesNo(String message) { + return userInfo != null && userInfo.promptYesNo(message); } - public void showMessage( String message ) - { - if ( userInfo != null ) - { - userInfo.showMessage( message ); + public void showMessage(String message) { + if (userInfo != null) { + userInfo.showMessage(message); } } } diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/PrompterUIKeyboardInteractive.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/PrompterUIKeyboardInteractive.java index ff33faee9..5bdd2e20d 100644 --- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/PrompterUIKeyboardInteractive.java +++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/PrompterUIKeyboardInteractive.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch.interactive; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch.interactive; import com.jcraft.jsch.UIKeyboardInteractive; import org.codehaus.plexus.components.interactivity.Prompter; @@ -25,30 +24,25 @@ /** * UIKeyboardInteractive that use plexus-prompter. - * + * * UIKeyboardInteractive are usefull when you don't use user with * password authentication with a server that use keyboard-interactive and * doesn't allow password method PasswordAuthentication no. * * @author Juan F. Codagnone * @since Sep 22, 2005 - * - * @plexus.component role="com.jcraft.jsch.UIKeyboardInteractive" + * + * @plexus.component role="com.jcraft.jsch.UIKeyboardInteractive" */ -public class PrompterUIKeyboardInteractive - implements UIKeyboardInteractive -{ +public class PrompterUIKeyboardInteractive implements UIKeyboardInteractive { /** * @plexus.requirement role-hint="default" */ private volatile Prompter prompter; - public PrompterUIKeyboardInteractive() - { - } + public PrompterUIKeyboardInteractive() {} - public PrompterUIKeyboardInteractive( Prompter promper ) - { + public PrompterUIKeyboardInteractive(Prompter promper) { this.prompter = promper; } @@ -56,34 +50,25 @@ public PrompterUIKeyboardInteractive( Prompter promper ) * @see UIKeyboardInteractive#promptKeyboardInteractive(String,String, *String,String[],boolean[]) */ - public String[] promptKeyboardInteractive( String destination, String name, String instruction, String[] prompt, - boolean[] echo ) - { + public String[] promptKeyboardInteractive( + String destination, String name, String instruction, String[] prompt, boolean[] echo) { - if ( prompt.length != echo.length ) - { + if (prompt.length != echo.length) { // jcsh is buggy? - throw new IllegalArgumentException( "prompt and echo size arrays are different!" ); + throw new IllegalArgumentException("prompt and echo size arrays are different!"); } String[] ret = new String[prompt.length]; - try - { + try { - for ( int i = 0; i < ret.length; i++ ) - { - if ( echo[i] ) - { - ret[i] = prompter.prompt( prompt[i] ); - } - else - { - ret[i] = prompter.promptForPassword( prompt[i] ); + for (int i = 0; i < ret.length; i++) { + if (echo[i]) { + ret[i] = prompter.prompt(prompt[i]); + } else { + ret[i] = prompter.promptForPassword(prompt[i]); } } - } - catch ( PrompterException e ) - { + } catch (PrompterException e) { // TODO: log // the user canceled? ret = null; diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/UserInfoUIKeyboardInteractiveProxy.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/UserInfoUIKeyboardInteractiveProxy.java index c26df3878..064130740 100644 --- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/UserInfoUIKeyboardInteractiveProxy.java +++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/jsch/interactive/UserInfoUIKeyboardInteractiveProxy.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch.interactive; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch.interactive; import com.jcraft.jsch.UIKeyboardInteractive; import com.jcraft.jsch.UserInfo; @@ -29,15 +28,12 @@ * @author Juan F. Codagnone * @since Sep 22, 2005 */ -public class UserInfoUIKeyboardInteractiveProxy - implements UserInfo, UIKeyboardInteractive -{ +public class UserInfoUIKeyboardInteractiveProxy implements UserInfo, UIKeyboardInteractive { private final UIKeyboardInteractive interactive; private final UserInfo userInfo; - public UserInfoUIKeyboardInteractiveProxy( UserInfo userInfo, UIKeyboardInteractive interactive ) - { + public UserInfoUIKeyboardInteractiveProxy(UserInfo userInfo, UIKeyboardInteractive interactive) { this.userInfo = userInfo; this.interactive = interactive; } @@ -45,62 +41,53 @@ public UserInfoUIKeyboardInteractiveProxy( UserInfo userInfo, UIKeyboardInteract /** * @see com.jcraft.jsch.UIKeyboardInteractive#promptKeyboardInteractive(String,String,String,String[],boolean[]) */ - public String[] promptKeyboardInteractive( String destination, String name, String instruction, String[] prompt, - boolean[] echo ) - { - if ( userInfo.getPassword() != null && prompt != null && prompt.length != 0 ) - { + public String[] promptKeyboardInteractive( + String destination, String name, String instruction, String[] prompt, boolean[] echo) { + if (userInfo.getPassword() != null && prompt != null && prompt.length != 0) { prompt[0] = "Keyboard interactive required, supplied password is ignored\n" + prompt[0]; } - return interactive.promptKeyboardInteractive( destination, name, instruction, prompt, echo ); + return interactive.promptKeyboardInteractive(destination, name, instruction, prompt, echo); } /** * @see com.jcraft.jsch.UserInfo#getPassphrase() */ - public String getPassphrase() - { + public String getPassphrase() { return userInfo.getPassphrase(); } /** * @see com.jcraft.jsch.UserInfo#getPassword() */ - public String getPassword() - { + public String getPassword() { return userInfo.getPassword(); } /** * @see com.jcraft.jsch.UserInfo#promptPassword(String) */ - public boolean promptPassword( String arg0 ) - { - return userInfo.promptPassword( arg0 ); + public boolean promptPassword(String arg0) { + return userInfo.promptPassword(arg0); } /** * @see com.jcraft.jsch.UserInfo#promptPassphrase(String) */ - public boolean promptPassphrase( String arg0 ) - { - return userInfo.promptPassphrase( arg0 ); + public boolean promptPassphrase(String arg0) { + return userInfo.promptPassphrase(arg0); } /** * @see com.jcraft.jsch.UserInfo#promptYesNo(String) */ - public boolean promptYesNo( String arg0 ) - { - return userInfo.promptYesNo( arg0 ); + public boolean promptYesNo(String arg0) { + return userInfo.promptYesNo(arg0); } /** * @see com.jcraft.jsch.UserInfo#showMessage(String) */ - public void showMessage( String arg0 ) - { - userInfo.showMessage( arg0 ); + public void showMessage(String arg0) { + userInfo.showMessage(arg0); } - } diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonTest.java index 72dc1c091..8b7455036 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonTest.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.wagon.providers.ssh.jsch; /* @@ -19,70 +37,47 @@ * under the License. */ +import java.io.IOException; + import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.providers.ssh.AbstractEmbeddedScpWagonTest; import org.apache.maven.wagon.providers.ssh.knownhost.KnownHostEntry; import org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider; -import java.io.IOException; - /** * @author Michal Maczka * */ -public class EmbeddedScpWagonTest - extends AbstractEmbeddedScpWagonTest -{ +public class EmbeddedScpWagonTest extends AbstractEmbeddedScpWagonTest { @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { ScpWagon scpWagon = (ScpWagon) super.getWagon(); - scpWagon.setInteractive( false ); - scpWagon.setKnownHostsProvider( new KnownHostsProvider() - { - public void storeKnownHosts( String contents ) - throws IOException - { + scpWagon.setInteractive(false); + scpWagon.setKnownHostsProvider(new KnownHostsProvider() { + public void storeKnownHosts(String contents) throws IOException {} - } + public void addKnownHost(KnownHostEntry knownHost) throws IOException {} - public void addKnownHost( KnownHostEntry knownHost ) - throws IOException - { - } + public void setHostKeyChecking(String hostKeyChecking) {} - public void setHostKeyChecking( String hostKeyChecking ) - { - } - - public String getHostKeyChecking() - { + public String getHostKeyChecking() { return "no"; } - public String getContents() - { + public String getContents() { return null; } - } ); + }); return scpWagon; } - - protected String getProtocol() - { + protected String getProtocol() { return "scp"; } - - @Override - protected boolean supportsGetIfNewer() - { + protected boolean supportsGetIfNewer() { return false; } - - } diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonWithKeyTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonWithKeyTest.java index 47d642db6..a0f4e7719 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonWithKeyTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/EmbeddedScpWagonWithKeyTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; + +import java.io.File; +import java.io.IOException; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.authentication.AuthenticationInfo; @@ -25,71 +27,45 @@ import org.apache.maven.wagon.providers.ssh.knownhost.KnownHostEntry; import org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider; -import java.io.File; -import java.io.IOException; - /** * @author Michal Maczka * */ -public class EmbeddedScpWagonWithKeyTest - extends AbstractEmbeddedScpWagonWithKeyTest -{ - +public class EmbeddedScpWagonWithKeyTest extends AbstractEmbeddedScpWagonWithKeyTest { @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { ScpWagon scpWagon = (ScpWagon) super.getWagon(); - scpWagon.setInteractive( false ); - scpWagon.setKnownHostsProvider( new KnownHostsProvider() - { - public void storeKnownHosts( String contents ) - throws IOException - { + scpWagon.setInteractive(false); + scpWagon.setKnownHostsProvider(new KnownHostsProvider() { + public void storeKnownHosts(String contents) throws IOException {} - } + public void addKnownHost(KnownHostEntry knownHost) throws IOException {} - public void addKnownHost( KnownHostEntry knownHost ) - throws IOException - { - } - - public void setHostKeyChecking( String hostKeyChecking ) - { - } + public void setHostKeyChecking(String hostKeyChecking) {} - public String getHostKeyChecking() - { + public String getHostKeyChecking() { return "no"; } - public String getContents() - { + public String getContents() { return null; } - } ); + }); return scpWagon; } - - protected String getProtocol() - { + protected String getProtocol() { return "scp"; } - - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = super.getAuthInfo(); // user : guest/guest123 - passphrase : toto01 - authInfo.setUserName( "guest" ); - //authInfo.setPassword( TestData.getUserPassword() ); - authInfo.setPrivateKey( new File( "src/test/ssh-keys/id_rsa" ).getPath() ); + authInfo.setUserName("guest"); + // authInfo.setPassword( TestData.getUserPassword() ); + authInfo.setPrivateKey(new File("src/test/ssh-keys/id_rsa").getPath()); return authInfo; } - - } diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/KnownHostsProviderTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/KnownHostsProviderTest.java index 6792862a7..f75c5bb55 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/KnownHostsProviderTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/KnownHostsProviderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; import org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProviderTestCase; @@ -28,8 +27,4 @@ * @see org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider * @since Sep 12, 2005 */ -public class KnownHostsProviderTest - extends KnownHostsProviderTestCase -{ - -} +public class KnownHostsProviderTest extends KnownHostsProviderTestCase {} diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonTest.java index d1bddeb98..ff8ca82c7 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; + +import java.io.File; import org.apache.maven.wagon.StreamingWagonTestCase; import org.apache.maven.wagon.authentication.AuthenticationInfo; @@ -25,46 +26,37 @@ import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; -import java.io.File; - /** * @author Michal Maczka * */ -public class ScpWagonTest - extends StreamingWagonTestCase -{ +public class ScpWagonTest extends StreamingWagonTestCase { - protected String getProtocol() - { + protected String getProtocol() { return "scp"; } - public String getTestRepositoryUrl() - { + public String getTestRepositoryUrl() { return TestData.getTestRepositoryUrl(); } - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = super.getAuthInfo(); - authInfo.setUserName( TestData.getUserName() ); + authInfo.setUserName(TestData.getUserName()); File privateKey = TestData.getPrivateKey(); - if ( privateKey.exists() ) - { - authInfo.setPrivateKey( privateKey.getAbsolutePath() ); + if (privateKey.exists()) { + authInfo.setPrivateKey(privateKey.getAbsolutePath()); - authInfo.setPassphrase( "" ); + authInfo.setPassphrase(""); } return authInfo; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - return new File( repository.getBasedir(), resource.getName() ).lastModified(); + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + return new File(repository.getBasedir(), resource.getName()).lastModified(); } } diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithProxyTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithProxyTest.java index 2d3fbd664..aed55debc 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithProxyTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithProxyTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.ServerSocket; @@ -25,10 +28,6 @@ import java.net.SocketTimeoutException; import java.util.Random; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.proxy.ProxyInfo; @@ -42,164 +41,120 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; -public class ScpWagonWithProxyTest - extends PlexusTestCase -{ +public class ScpWagonWithProxyTest extends PlexusTestCase { private boolean handled; - public void testHttpProxy() - throws Exception - { + public void testHttpProxy() throws Exception { handled = false; - Handler handler = new AbstractHandler() - { - public void handle( String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response ) throws IOException, ServletException - { - assertEquals( "CONNECT", request.getMethod() ); + Handler handler = new AbstractHandler() { + public void handle( + String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + assertEquals("CONNECT", request.getMethod()); handled = true; - baseRequest.setHandled( true ); + baseRequest.setHandled(true); } }; - Server server = new Server( ); - ServerConnector connector = new ServerConnector( server, new HttpConnectionFactory( new HttpConfiguration() ) ); - server.addConnector( connector ); - server.setHandler( handler ); + Server server = new Server(); + ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration())); + server.addConnector(connector); + server.setHandler(handler); server.start(); int port = connector.getLocalPort(); ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setHost( "localhost" ); - proxyInfo.setPort( port ); - proxyInfo.setType( "http" ); - proxyInfo.setNonProxyHosts( null ); - - Wagon wagon = (Wagon) lookup( Wagon.ROLE, "scp" ); - try - { - wagon.connect( new Repository( "id", "scp://localhost/tmp" ), proxyInfo ); + proxyInfo.setHost("localhost"); + proxyInfo.setPort(port); + proxyInfo.setType("http"); + proxyInfo.setNonProxyHosts(null); + + Wagon wagon = (Wagon) lookup(Wagon.ROLE, "scp"); + try { + wagon.connect(new Repository("id", "scp://localhost/tmp"), proxyInfo); fail(); - } - catch ( AuthenticationException e ) - { - assertTrue( handled ); - } - finally - { + } catch (AuthenticationException e) { + assertTrue(handled); + } finally { wagon.disconnect(); server.stop(); } } - public void testSocksProxy() - throws Exception - { + public void testSocksProxy() throws Exception { handled = false; - int port = ( Math.abs( new Random().nextInt() ) % 2048 ) + 1024; + int port = (Math.abs(new Random().nextInt()) % 2048) + 1024; - SocksServer s = new SocksServer( port ); - Thread t = new Thread( s ); - t.setDaemon( true ); + SocksServer s = new SocksServer(port); + Thread t = new Thread(s); + t.setDaemon(true); t.start(); ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setHost( "localhost" ); - proxyInfo.setPort( port ); - proxyInfo.setType( "socks_5" ); - proxyInfo.setNonProxyHosts( null ); - - Wagon wagon = (Wagon) lookup( Wagon.ROLE, "scp" ); - try - { - wagon.connect( new Repository( "id", "scp://localhost/tmp" ), proxyInfo ); + proxyInfo.setHost("localhost"); + proxyInfo.setPort(port); + proxyInfo.setType("socks_5"); + proxyInfo.setNonProxyHosts(null); + + Wagon wagon = (Wagon) lookup(Wagon.ROLE, "scp"); + try { + wagon.connect(new Repository("id", "scp://localhost/tmp"), proxyInfo); fail(); - } - catch ( AuthenticationException e ) - { - assertTrue( handled ); - } - finally - { + } catch (AuthenticationException e) { + assertTrue(handled); + } finally { wagon.disconnect(); t.interrupt(); } } - private final class SocksServer - implements Runnable - { + private final class SocksServer implements Runnable { private final int port; private String userAgent; - private SocksServer( int port ) - { + private SocksServer(int port) { this.port = port; } - public void run() - { + public void run() { ServerSocket ssock = null; - try - { - try - { - ssock = new ServerSocket( port ); - ssock.setSoTimeout( 2000 ); - } - catch ( IOException e ) - { + try { + try { + ssock = new ServerSocket(port); + ssock.setSoTimeout(2000); + } catch (IOException e) { return; } - while ( !Thread.currentThread().isInterrupted() ) - { + while (!Thread.currentThread().isInterrupted()) { Socket sock = null; - try - { - try - { + try { + try { sock = ssock.accept(); - } - catch ( SocketTimeoutException e ) - { + } catch (SocketTimeoutException e) { continue; } handled = true; - } - catch ( IOException e ) - { - } - finally - { - if ( sock != null ) - { - try - { + } catch (IOException e) { + } finally { + if (sock != null) { + try { sock.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { } } } } - } - finally - { - if ( ssock != null ) - { - try - { + } finally { + if (ssock != null) { + try { ssock.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { } } } diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithSshPrivateKeySearchTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithSshPrivateKeySearchTest.java index f86c5eba2..8fdad517e 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithSshPrivateKeySearchTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/ScpWagonWithSshPrivateKeySearchTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; import java.io.File; -import java.io.IOException; -import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.StreamingWagonTestCase; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authentication.AuthenticationInfo; @@ -34,75 +31,57 @@ * @author Michal Maczka * */ -public class ScpWagonWithSshPrivateKeySearchTest - extends StreamingWagonTestCase -{ - protected String getProtocol() - { +public class ScpWagonWithSshPrivateKeySearchTest extends StreamingWagonTestCase { + protected String getProtocol() { return "scp"; } - public String getTestRepositoryUrl() - { + public String getTestRepositoryUrl() { return TestData.getTestRepositoryUrl(0); } - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = super.getAuthInfo(); - authInfo.setUserName( TestData.getUserName() ); + authInfo.setUserName(TestData.getUserName()); - authInfo.setPassphrase( "" ); + authInfo.setPassphrase(""); return authInfo; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - return new File( repository.getBasedir(), resource.getName() ).lastModified(); + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + return new File(repository.getBasedir(), resource.getName()).lastModified(); } - public void testMissingPrivateKey() - throws Exception - { - File file = File.createTempFile( "wagon", "tmp" ); + public void testMissingPrivateKey() throws Exception { + File file = File.createTempFile("wagon", "tmp"); file.delete(); AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setPrivateKey( file.getAbsolutePath() ); + authInfo.setPrivateKey(file.getAbsolutePath()); - try - { - getWagon().connect( new Repository(), authInfo ); + try { + getWagon().connect(new Repository(), authInfo); fail(); - } - catch ( AuthenticationException e ) - { - assertTrue( true ); + } catch (AuthenticationException e) { + assertTrue(true); } } - public void testBadPrivateKey() - throws Exception - { - File file = File.createTempFile( "wagon", "tmp" ); + public void testBadPrivateKey() throws Exception { + File file = File.createTempFile("wagon", "tmp"); file.deleteOnExit(); AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setPrivateKey( file.getAbsolutePath() ); + authInfo.setPrivateKey(file.getAbsolutePath()); - try - { - getWagon().connect( new Repository(), authInfo ); + try { + getWagon().connect(new Repository(), authInfo); fail(); - } - catch ( AuthenticationException e ) - { - assertTrue( true ); - } - finally - { + } catch (AuthenticationException e) { + assertTrue(true); + } finally { file.delete(); } } diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagonTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagonTest.java index 04182cc14..ca9ff4d6b 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagonTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SftpWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; + +import java.io.File; import org.apache.maven.wagon.StreamingWagonTestCase; import org.apache.maven.wagon.authentication.AuthenticationInfo; @@ -25,36 +26,28 @@ import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; -import java.io.File; - /** * @author Brett Porter * */ -public class SftpWagonTest - extends StreamingWagonTestCase -{ - protected String getProtocol() - { +public class SftpWagonTest extends StreamingWagonTestCase { + protected String getProtocol() { return "sftp"; } - public String getTestRepositoryUrl() - { + public String getTestRepositoryUrl() { return TestData.getTestRepositoryUrl(0); } - protected AuthenticationInfo getAuthInfo() - { + protected AuthenticationInfo getAuthInfo() { AuthenticationInfo authInfo = super.getAuthInfo(); - authInfo.setUserName( TestData.getUserName() ); + authInfo.setUserName(TestData.getUserName()); return authInfo; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - return new File( repository.getBasedir(), resource.getName() ).lastModified(); + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + return new File(repository.getBasedir(), resource.getName()).lastModified(); } } diff --git a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SshCommandExecutorTest.java b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SshCommandExecutorTest.java index 27140caac..86161e5bb 100644 --- a/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SshCommandExecutorTest.java +++ b/wagon-providers/wagon-ssh/src/test/java/org/apache/maven/wagon/providers/ssh/jsch/SshCommandExecutorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.ssh.jsch; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.ssh.jsch; import org.apache.maven.wagon.CommandExecutorTestCase; import org.apache.maven.wagon.repository.Repository; @@ -28,12 +27,9 @@ * @author Brett Porter * */ -public class SshCommandExecutorTest - extends CommandExecutorTestCase -{ +public class SshCommandExecutorTest extends CommandExecutorTestCase { - protected Repository getTestRepository() - { - return new Repository( "test", "scp://localhost/" ); + protected Repository getTestRepository() { + return new Repository("test", "scp://localhost/"); } } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/MultiStatus.java b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/MultiStatus.java index 8bf95203b..9013837a8 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/MultiStatus.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/MultiStatus.java @@ -1,5 +1,3 @@ -package org.apache.jackrabbit.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.jackrabbit.webdav; + +import java.util.LinkedHashMap; +import java.util.Map; import org.apache.jackrabbit.webdav.property.DavPropertyNameSet; import org.apache.jackrabbit.webdav.xml.DomUtil; @@ -26,16 +28,11 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -import java.util.Map; -import java.util.LinkedHashMap; - /** * MultiStatus representing the content of a multistatus response body and * allows to retrieve the Xml representation. */ -public class MultiStatus - implements DavConstants, XmlSerializable -{ +public class MultiStatus implements DavConstants, XmlSerializable { /** * Map collecting the responses for this multistatus, where every href must @@ -61,16 +58,13 @@ public class MultiStatus * @param propFindType * @param depth */ - public void addResourceProperties( DavResource resource, DavPropertyNameSet propNameSet, int propFindType, - int depth ) - { - addResponse( new MultiStatusResponse( resource, propNameSet, propFindType ) ); - if ( depth > 0 && resource.isCollection() ) - { + public void addResourceProperties( + DavResource resource, DavPropertyNameSet propNameSet, int propFindType, int depth) { + addResponse(new MultiStatusResponse(resource, propNameSet, propFindType)); + if (depth > 0 && resource.isCollection()) { DavResourceIterator iter = resource.getMembers(); - while ( iter.hasNext() ) - { - addResourceProperties( iter.nextResource(), propNameSet, propFindType, depth - 1 ); + while (iter.hasNext()) { + addResourceProperties(iter.nextResource(), propNameSet, propFindType, depth - 1); } } } @@ -87,9 +81,8 @@ public void addResourceProperties( DavResource resource, DavPropertyNameSet prop * @see #addResourceProperties(DavResource, DavPropertyNameSet, int, int) for * the corresponding method that allows to specify the type explicitly. */ - public void addResourceProperties( DavResource resource, DavPropertyNameSet propNameSet, int depth ) - { - addResourceProperties( resource, propNameSet, PROPFIND_BY_PROPERTY, depth ); + public void addResourceProperties(DavResource resource, DavPropertyNameSet propNameSet, int depth) { + addResourceProperties(resource, propNameSet, PROPFIND_BY_PROPERTY, depth); } /** @@ -101,15 +94,12 @@ public void addResourceProperties( DavResource resource, DavPropertyNameSet prop * @param status * @param depth */ - public void addResourceStatus( DavResource resource, int status, int depth ) - { - addResponse( new MultiStatusResponse( resource.getHref(), status ) ); - if ( depth > 0 && resource.isCollection() ) - { + public void addResourceStatus(DavResource resource, int status, int depth) { + addResponse(new MultiStatusResponse(resource.getHref(), status)); + if (depth > 0 && resource.isCollection()) { DavResourceIterator iter = resource.getMembers(); - while ( iter.hasNext() ) - { - addResourceStatus( iter.nextResource(), status, depth - 1 ); + while (iter.hasNext()) { + addResourceStatus(iter.nextResource(), status, depth - 1); } } } @@ -119,9 +109,8 @@ public void addResourceStatus( DavResource resource, int status, int depth ) * * @param response */ - public void addResponse( MultiStatusResponse response ) - { - responses.put( response.getHref(), response ); + public void addResponse(MultiStatusResponse response) { + responses.put(response.getHref(), response); } /** @@ -130,9 +119,8 @@ public void addResponse( MultiStatusResponse response ) * @return array of all {@link MultiStatusResponse responses} present in this * multistatus. */ - public MultiStatusResponse[] getResponses() - { - return (MultiStatusResponse[]) responses.values().toArray( new MultiStatusResponse[responses.size()] ); + public MultiStatusResponse[] getResponses() { + return (MultiStatusResponse[]) responses.values().toArray(new MultiStatusResponse[responses.size()]); } /** @@ -140,8 +128,7 @@ public MultiStatusResponse[] getResponses() * * @param responseDescription */ - public void setResponseDescription( String responseDescription ) - { + public void setResponseDescription(String responseDescription) { this.responseDescription = responseDescription; } @@ -150,8 +137,7 @@ public void setResponseDescription( String responseDescription ) * * @return responseDescription */ - public String getResponseDescription() - { + public String getResponseDescription() { return responseDescription; } @@ -161,18 +147,14 @@ public String getResponseDescription() * @return Xml document * @param document */ - public Element toXml( Document document ) - { - Element multistatus = DomUtil.createElement( document, XML_MULTISTATUS, NAMESPACE ); - for ( MultiStatusResponse response : responses.values() ) - { - multistatus.appendChild( response.toXml( document ) ); + public Element toXml(Document document) { + Element multistatus = DomUtil.createElement(document, XML_MULTISTATUS, NAMESPACE); + for (MultiStatusResponse response : responses.values()) { + multistatus.appendChild(response.toXml(document)); } - if ( responseDescription != null ) - { - Element respDesc = - DomUtil.createElement( document, XML_RESPONSEDESCRIPTION, NAMESPACE, responseDescription ); - multistatus.appendChild( respDesc ); + if (responseDescription != null) { + Element respDesc = DomUtil.createElement(document, XML_RESPONSEDESCRIPTION, NAMESPACE, responseDescription); + multistatus.appendChild(respDesc); } return multistatus; } @@ -185,26 +167,23 @@ public Element toXml( Document document ) * @throws IllegalArgumentException if the given document is null * or does not provide the required element. */ - public static MultiStatus createFromXml( Element multistatusElement ) - { - if ( !DomUtil.matches( multistatusElement, XML_MULTISTATUS, NAMESPACE ) ) - { - throw new IllegalArgumentException( "DAV:multistatus element expected." ); + public static MultiStatus createFromXml(Element multistatusElement) { + if (!DomUtil.matches(multistatusElement, XML_MULTISTATUS, NAMESPACE)) { + throw new IllegalArgumentException("DAV:multistatus element expected."); } MultiStatus multistatus = new MultiStatus(); - ElementIterator it = DomUtil.getChildren( multistatusElement, XML_RESPONSE, NAMESPACE ); - while ( it.hasNext() ) - { + ElementIterator it = DomUtil.getChildren(multistatusElement, XML_RESPONSE, NAMESPACE); + while (it.hasNext()) { Element respElem = it.nextElement(); - MultiStatusResponse response = MultiStatusResponse.createFromXml( respElem ); - multistatus.addResponse( response ); + MultiStatusResponse response = MultiStatusResponse.createFromXml(respElem); + multistatus.addResponse(response); } // optional response description on the multistatus element - multistatus.setResponseDescription( DomUtil.getChildText( multistatusElement, XML_RESPONSEDESCRIPTION, - NAMESPACE ) ); + multistatus.setResponseDescription( + DomUtil.getChildText(multistatusElement, XML_RESPONSEDESCRIPTION, NAMESPACE)); return multistatus; } } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/client/methods/XmlRequestEntity.java b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/client/methods/XmlRequestEntity.java index c317978aa..697c34b17 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/client/methods/XmlRequestEntity.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/client/methods/XmlRequestEntity.java @@ -1,5 +1,3 @@ -package org.apache.jackrabbit.webdav.client.methods; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -import java.io.OutputStream; -import java.io.IOException; -import java.io.ByteArrayOutputStream; +package org.apache.jackrabbit.webdav.client.methods; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; @@ -37,67 +25,66 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + /** * XmlRequestEntity... * @deprecated is it really use??? */ -public class XmlRequestEntity - extends HttpEntityEnclosingRequestBase -{ +public class XmlRequestEntity extends HttpEntityEnclosingRequestBase { - private static Logger log = LoggerFactory.getLogger( XmlRequestEntity.class ); + private static Logger log = LoggerFactory.getLogger(XmlRequestEntity.class); private final StringEntity delegatee; - public XmlRequestEntity( Document xmlDocument ) - throws IOException - { + public XmlRequestEntity(Document xmlDocument) throws IOException { super(); ByteArrayOutputStream out = new ByteArrayOutputStream(); - try - { + try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); - transformer.setOutputProperty( OutputKeys.METHOD, "xml" ); - transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "no" ); - transformer.transform( new DOMSource( xmlDocument ), new StreamResult( out ) ); - } - catch ( TransformerException e ) - { - log.error( "XML serialization failed", e ); - IOException exception = new IOException( "XML serialization failed" ); - exception.initCause( e ); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "no"); + transformer.transform(new DOMSource(xmlDocument), new StreamResult(out)); + } catch (TransformerException e) { + log.error("XML serialization failed", e); + IOException exception = new IOException("XML serialization failed"); + exception.initCause(e); throw exception; } - delegatee = new StringEntity( out.toString(), "text/xml", "UTF-8" ); + delegatee = new StringEntity(out.toString(), "text/xml", "UTF-8"); } - public boolean isRepeatable() - { + public boolean isRepeatable() { return delegatee.isRepeatable(); } - public String getContentType() - { + public String getContentType() { return delegatee.getContentType().getValue(); } - public void writeRequest( OutputStream out ) throws IOException - { - delegatee.writeTo( out ); + public void writeRequest(OutputStream out) throws IOException { + delegatee.writeTo(out); } - public long getContentLength() - { + public long getContentLength() { return delegatee.getContentLength(); } @Override - public String getMethod() - { + public String getMethod() { return HttpPost.METHOD_NAME; } -} \ No newline at end of file +} diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/PathNavigator.java b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/PathNavigator.java index a03be54f4..320fc99e3 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/PathNavigator.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/PathNavigator.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,53 +16,46 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; -import org.codehaus.plexus.util.StringUtils; - -import java.util.List; import java.util.Arrays; +import java.util.List; + +import org.codehaus.plexus.util.StringUtils; /** * @author James William Dumay */ -public class PathNavigator -{ +public class PathNavigator { private final List list; private int currentPosition; - public PathNavigator( String path ) - { - list = Arrays.asList( StringUtils.split( path, "/" ) ); + public PathNavigator(String path) { + list = Arrays.asList(StringUtils.split(path, "/")); currentPosition = list.size(); } - public String getPath() - { - List currentPathList = list.subList( 0, currentPosition ); + public String getPath() { + List currentPathList = list.subList(0, currentPosition); StringBuilder sb = new StringBuilder(); - for ( String path : currentPathList ) - { - sb.append( path ); - sb.append( '/' ); + for (String path : currentPathList) { + sb.append(path); + sb.append('/'); } return sb.toString(); } - public boolean backward() - { - if ( currentPosition == 0 ) - { + public boolean backward() { + if (currentPosition == 0) { return false; } currentPosition--; return true; } - public boolean forward() - { - if ( currentPosition + 1 > list.size() ) - { + public boolean forward() { + if (currentPosition + 1 > list.size()) { return false; } currentPosition++; diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java index 70fe28a29..97a579124 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; + +import java.io.File; +import java.io.IOException; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.List; import org.apache.http.HttpException; import org.apache.http.HttpStatus; @@ -43,12 +48,6 @@ import org.codehaus.plexus.util.FileUtils; import org.w3c.dom.Node; -import java.io.File; -import java.io.IOException; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.List; - import static org.apache.maven.wagon.shared.http.HttpMessageUtils.formatResourceDoesNotExistMessage; /** @@ -64,12 +63,10 @@ * role-hint="dav" * instantiation-strategy="per-lookup" */ -public class WebDavWagon - extends AbstractHttpClientWagon -{ +public class WebDavWagon extends AbstractHttpClientWagon { protected static final String CONTINUE_ON_FAILURE_PROPERTY = "wagon.webdav.continueOnFailure"; - private final boolean continueOnFailure = Boolean.getBoolean( CONTINUE_ON_FAILURE_PROPERTY ); + private final boolean continueOnFailure = Boolean.getBoolean(CONTINUE_ON_FAILURE_PROPERTY); /** * Defines the protocol mapping to use. @@ -79,21 +76,21 @@ public class WebDavWagon *

    * NOTE: The order of the mapping becomes the search order. */ - private static final String[][] PROTOCOL_MAP = - new String[][]{ { "dav:http://", "http://" }, /* maven 2.0.x url string format. (violates URI spec) */ - { "dav:https://", "https://" }, /* maven 2.0.x url string format. (violates URI spec) */ - { "dav+http://", "http://" }, /* URI spec compliant (protocol+transport) */ - { "dav+https://", "https://" }, /* URI spec compliant (protocol+transport) */ - { "dav://", "http://" }, /* URI spec compliant (protocol only) */ - { "davs://", "https://" } /* URI spec compliant (protocol only) */ }; + private static final String[][] PROTOCOL_MAP = new String[][] { + {"dav:http://", "http://"}, /* maven 2.0.x url string format. (violates URI spec) */ + {"dav:https://", "https://"}, /* maven 2.0.x url string format. (violates URI spec) */ + {"dav+http://", "http://"}, /* URI spec compliant (protocol+transport) */ + {"dav+https://", "https://"}, /* URI spec compliant (protocol+transport) */ + {"dav://", "http://"}, /* URI spec compliant (protocol only) */ + {"davs://", "https://"} /* URI spec compliant (protocol only) */ + }; /** * This wagon supports directory copying * * @return true always */ - public boolean supportsDirectoryCopy() - { + public boolean supportsDirectoryCopy() { return true; } @@ -105,65 +102,49 @@ public boolean supportsDirectoryCopy() * @throws IOException * @throws TransferFailedException */ - protected void mkdirs( String dir ) - throws IOException - { + protected void mkdirs(String dir) throws IOException { Repository repository = getRepository(); String basedir = repository.getBasedir(); String baseUrl = repository.getProtocol() + "://" + repository.getHost(); - if ( repository.getPort() != WagonConstants.UNKNOWN_PORT ) - { + if (repository.getPort() != WagonConstants.UNKNOWN_PORT) { baseUrl += ":" + repository.getPort(); } // create relative path that will always have a leading and trailing slash - String relpath = FileUtils.normalize( getPath( basedir, dir ) + "/" ); + String relpath = FileUtils.normalize(getPath(basedir, dir) + "/"); - PathNavigator navigator = new PathNavigator( relpath ); + PathNavigator navigator = new PathNavigator(relpath); // traverse backwards until we hit a directory that already exists (OK/NOT_ALLOWED), or that we were able to // create (CREATED), or until we get to the top of the path int status = -1; - do - { + do { String url = baseUrl + "/" + navigator.getPath(); - status = doMkCol( url ); - if ( status == HttpStatus.SC_CREATED || status == HttpStatus.SC_METHOD_NOT_ALLOWED ) - { + status = doMkCol(url); + if (status == HttpStatus.SC_CREATED || status == HttpStatus.SC_METHOD_NOT_ALLOWED) { break; } - } - while ( navigator.backward() ); + } while (navigator.backward()); // traverse forward creating missing directories - while ( navigator.forward() ) - { + while (navigator.forward()) { String url = baseUrl + "/" + navigator.getPath(); - status = doMkCol( url ); - if ( status != HttpStatus.SC_CREATED ) - { - throw new IOException( "Unable to create collection: " + url + "; status code = " + status ); + status = doMkCol(url); + if (status != HttpStatus.SC_CREATED) { + throw new IOException("Unable to create collection: " + url + "; status code = " + status); } } } - private int doMkCol( String url ) - throws IOException - { - HttpMkcol method = new HttpMkcol( url ); - try ( CloseableHttpResponse closeableHttpResponse = execute( method ) ) - { + private int doMkCol(String url) throws IOException { + HttpMkcol method = new HttpMkcol(url); + try (CloseableHttpResponse closeableHttpResponse = execute(method)) { return closeableHttpResponse.getStatusLine().getStatusCode(); - } - catch ( HttpException e ) - { - throw new IOException( e.getMessage(), e ); - } - finally - { - if ( method != null ) - { + } catch (HttpException e) { + throw new IOException(e.getMessage(), e); + } finally { + if (method != null) { method.releaseConnection(); } } @@ -178,111 +159,88 @@ private int doMkCol( String url ) * @throws ResourceDoesNotExistException * @throws AuthorizationException */ - public void putDirectory( File sourceDirectory, String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - for ( File file : sourceDirectory.listFiles() ) - { - if ( file.isDirectory() ) - { - putDirectory( file, destinationDirectory + "/" + file.getName() ); - } - else - { + public void putDirectory(File sourceDirectory, String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + for (File file : sourceDirectory.listFiles()) { + if (file.isDirectory()) { + putDirectory(file, destinationDirectory + "/" + file.getName()); + } else { String target = destinationDirectory + "/" + file.getName(); - put( file, target ); + put(file, target); } } } - private boolean isDirectory( String url ) - throws IOException, DavException - { + + private boolean isDirectory(String url) throws IOException, DavException { DavPropertyNameSet nameSet = new DavPropertyNameSet(); - nameSet.add( DavPropertyName.create( DavConstants.PROPERTY_RESOURCETYPE ) ); + nameSet.add(DavPropertyName.create(DavConstants.PROPERTY_RESOURCETYPE)); CloseableHttpResponse closeableHttpResponse = null; HttpPropfind method = null; - try - { - method = new HttpPropfind( url, nameSet, DavConstants.DEPTH_0 ); - closeableHttpResponse = execute( method ); + try { + method = new HttpPropfind(url, nameSet, DavConstants.DEPTH_0); + closeableHttpResponse = execute(method); - if ( method.succeeded( closeableHttpResponse ) ) - { - MultiStatus multiStatus = method.getResponseBodyAsMultiStatus( closeableHttpResponse ); + if (method.succeeded(closeableHttpResponse)) { + MultiStatus multiStatus = method.getResponseBodyAsMultiStatus(closeableHttpResponse); MultiStatusResponse response = multiStatus.getResponses()[0]; - DavPropertySet propertySet = response.getProperties( HttpStatus.SC_OK ); - DavProperty property = propertySet.get( DavConstants.PROPERTY_RESOURCETYPE ); - if ( property != null ) - { + DavPropertySet propertySet = response.getProperties(HttpStatus.SC_OK); + DavProperty property = propertySet.get(DavConstants.PROPERTY_RESOURCETYPE); + if (property != null) { Node node = (Node) property.getValue(); - return node.getLocalName().equals( DavConstants.XML_COLLECTION ); + return node.getLocalName().equals(DavConstants.XML_COLLECTION); } } return false; - } - catch ( HttpException e ) - { - throw new IOException( e.getMessage(), e ); - } - finally - { - //TODO olamy: not sure we still need this!! - if ( method != null ) - { + } catch (HttpException e) { + throw new IOException(e.getMessage(), e); + } finally { + // TODO olamy: not sure we still need this!! + if (method != null) { method.releaseConnection(); } - if ( closeableHttpResponse != null ) - { + if (closeableHttpResponse != null) { closeableHttpResponse.close(); } } } - public List getFileList( String destinationDirectory ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public List getFileList(String destinationDirectory) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { String repositoryUrl = repository.getUrl(); - String url = repositoryUrl + ( repositoryUrl.endsWith( "/" ) ? "" : "/" ) + destinationDirectory; + String url = repositoryUrl + (repositoryUrl.endsWith("/") ? "" : "/") + destinationDirectory; HttpPropfind method = null; CloseableHttpResponse closeableHttpResponse = null; - try - { - if ( isDirectory( url ) ) - { + try { + if (isDirectory(url)) { DavPropertyNameSet nameSet = new DavPropertyNameSet(); - nameSet.add( DavPropertyName.create( DavConstants.PROPERTY_DISPLAYNAME ) ); + nameSet.add(DavPropertyName.create(DavConstants.PROPERTY_DISPLAYNAME)); - method = new HttpPropfind( url, nameSet, DavConstants.DEPTH_1 ); - closeableHttpResponse = execute( method ); - if ( method.succeeded( closeableHttpResponse ) ) - { + method = new HttpPropfind(url, nameSet, DavConstants.DEPTH_1); + closeableHttpResponse = execute(method); + if (method.succeeded(closeableHttpResponse)) { ArrayList dirs = new ArrayList<>(); - MultiStatus multiStatus = method.getResponseBodyAsMultiStatus( closeableHttpResponse ); - for ( int i = 0; i < multiStatus.getResponses().length; i++ ) - { + MultiStatus multiStatus = method.getResponseBodyAsMultiStatus(closeableHttpResponse); + for (int i = 0; i < multiStatus.getResponses().length; i++) { MultiStatusResponse response = multiStatus.getResponses()[i]; String entryUrl = response.getHref(); - String fileName = PathUtils.filename( URLDecoder.decode( entryUrl ) ); - if ( entryUrl.endsWith( "/" ) ) - { - if ( i == 0 ) - { + String fileName = PathUtils.filename(URLDecoder.decode(entryUrl)); + if (entryUrl.endsWith("/")) { + if (i == 0) { // by design jackrabbit WebDAV sticks parent directory as the first entry // so we need to ignore this entry // http://www.webdav.org/specs/rfc4918.html#rfc.section.9.1 continue; } - //extract "dir/" part of "path.to.dir/" - fileName = PathUtils.filename( PathUtils.dirname( URLDecoder.decode( entryUrl ) ) ) + "/"; + // extract "dir/" part of "path.to.dir/" + fileName = PathUtils.filename(PathUtils.dirname(URLDecoder.decode(entryUrl))) + "/"; } - if ( !( fileName == null || fileName.isEmpty() ) ) - { - dirs.add( fileName ); + if (!(fileName == null || fileName.isEmpty())) { + dirs.add(fileName); } } return dirs; @@ -290,61 +248,44 @@ public List getFileList( String destinationDirectory ) int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); String reasonPhrase = closeableHttpResponse.getStatusLine().getReasonPhrase(); - if ( statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_GONE ) - { - EntityUtils.consumeQuietly( closeableHttpResponse.getEntity() ); - throw new ResourceDoesNotExistException( formatResourceDoesNotExistMessage( url, statusCode, - reasonPhrase, getProxyInfo() ) ); + if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_GONE) { + EntityUtils.consumeQuietly(closeableHttpResponse.getEntity()); + throw new ResourceDoesNotExistException( + formatResourceDoesNotExistMessage(url, statusCode, reasonPhrase, getProxyInfo())); } } - } - catch ( HttpException e ) - { - throw new TransferFailedException( e.getMessage(), e ); - } - catch ( DavException e ) - { - throw new TransferFailedException( e.getMessage(), e ); - } - catch ( IOException e ) - { - throw new TransferFailedException( e.getMessage(), e ); - } - finally - { - //TODO olamy: not sure we still need this!! - if ( method != null ) - { + } catch (HttpException e) { + throw new TransferFailedException(e.getMessage(), e); + } catch (DavException e) { + throw new TransferFailedException(e.getMessage(), e); + } catch (IOException e) { + throw new TransferFailedException(e.getMessage(), e); + } finally { + // TODO olamy: not sure we still need this!! + if (method != null) { method.releaseConnection(); } - if ( closeableHttpResponse != null ) - { - try - { + if (closeableHttpResponse != null) { + try { closeableHttpResponse.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { // ignore } } } // FIXME WAGON-580; actually the exception is wrong here; we need an IllegalStateException here throw new ResourceDoesNotExistException( - "Destination path exists but is not a " + "WebDAV collection (directory): " + url ); + "Destination path exists but is not a " + "WebDAV collection (directory): " + url); } - public String getURL( Repository repository ) - { + public String getURL(Repository repository) { String url = repository.getUrl(); // Process mappings first. - for ( String[] entry : PROTOCOL_MAP ) - { + for (String[] entry : PROTOCOL_MAP) { String protocol = entry[0]; - if ( url.startsWith( protocol ) ) - { - return entry[1] + url.substring( protocol.length() ); + if (url.startsWith(protocol)) { + return entry[1] + url.substring(protocol.length()); } } @@ -352,25 +293,16 @@ public String getURL( Repository repository ) return url; } - - public void put( File source, String resourceName ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - try - { - super.put( source, resourceName ); - } - catch ( TransferFailedException e ) - { - if ( continueOnFailure ) - { + public void put(File source, String resourceName) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + try { + super.put(source, resourceName); + } catch (TransferFailedException e) { + if (continueOnFailure) { // TODO use a logging mechanism here or a fireTransferWarning - System.out.println( - "WARN: Skip unable to transfer '" + resourceName + "' from '" + source.getPath() + "' due to " - + e.getMessage() ); - } - else - { + System.out.println("WARN: Skip unable to transfer '" + resourceName + "' from '" + source.getPath() + + "' due to " + e.getMessage()); + } else { throw e; } } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/HttpClientWagonTest.java b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/HttpClientWagonTest.java index 77016ea94..efea8983e 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/HttpClientWagonTest.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/HttpClientWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; import junit.framework.TestCase; import org.apache.http.Header; import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.params.HttpClientParams; import org.apache.http.params.HttpParams; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.OutputData; @@ -35,182 +33,166 @@ import org.apache.maven.wagon.shared.http.HttpMethodConfiguration; import org.junit.Ignore; -public class HttpClientWagonTest - extends TestCase -{ +public class HttpClientWagonTest extends TestCase { @Ignore("not sure how to test this") - public void testSetPreemptiveAuthParamViaConfig() - { + public void testSetPreemptiveAuthParamViaConfig() { HttpMethodConfiguration methodConfig = new HttpMethodConfiguration(); - methodConfig.setUsePreemptive( true ); + methodConfig.setUsePreemptive(true); HttpConfiguration config = new HttpConfiguration(); - config.setAll( methodConfig ); + config.setAll(methodConfig); TestWagon wagon = new TestWagon(); - wagon.setHttpConfiguration( config ); + wagon.setHttpConfiguration(config); HttpHead method = new HttpHead(); - wagon.setHeaders( method ); + wagon.setHeaders(method); HttpParams params = method.getParams(); - assertNotNull( params ); - //assertTrue( params.isParameterTrue( HttpClientParams.PREEMPTIVE_AUTHENTICATION ) ); + assertNotNull(params); + // assertTrue( params.isParameterTrue( HttpClientParams.PREEMPTIVE_AUTHENTICATION ) ); } -// @Ignore("not sure how to test this") -// public void testSetMaxRedirectsParamViaConfig() -// { -// HttpMethodConfiguration methodConfig = new HttpMethodConfiguration(); -// int maxRedirects = 2; -// methodConfig.addParam( HttpClientParams.MAX_REDIRECTS, "%i," + maxRedirects ); -// -// HttpConfiguration config = new HttpConfiguration(); -// config.setAll( methodConfig ); -// -// TestWagon wagon = new TestWagon(); -// wagon.setHttpConfiguration( config ); -// -// HttpHead method = new HttpHead(); -// wagon.setParameters( method ); -// -// HttpParams params = method.getParams(); -// assertNotNull( params ); -// assertEquals( maxRedirects, params.getIntParameter( HttpClientParams.MAX_REDIRECTS, -1 ) ); -// } - - public void testDefaultHeadersUsedByDefault() - { + // @Ignore("not sure how to test this") + // public void testSetMaxRedirectsParamViaConfig() + // { + // HttpMethodConfiguration methodConfig = new HttpMethodConfiguration(); + // int maxRedirects = 2; + // methodConfig.addParam( HttpClientParams.MAX_REDIRECTS, "%i," + maxRedirects ); + // + // HttpConfiguration config = new HttpConfiguration(); + // config.setAll( methodConfig ); + // + // TestWagon wagon = new TestWagon(); + // wagon.setHttpConfiguration( config ); + // + // HttpHead method = new HttpHead(); + // wagon.setParameters( method ); + // + // HttpParams params = method.getParams(); + // assertNotNull( params ); + // assertEquals( maxRedirects, params.getIntParameter( HttpClientParams.MAX_REDIRECTS, -1 ) ); + // } + + public void testDefaultHeadersUsedByDefault() { HttpConfiguration config = new HttpConfiguration(); - config.setAll( new HttpMethodConfiguration() ); + config.setAll(new HttpMethodConfiguration()); TestWagon wagon = new TestWagon(); - wagon.setHttpConfiguration( config ); + wagon.setHttpConfiguration(config); HttpHead method = new HttpHead(); - wagon.setHeaders( method ); + wagon.setHeaders(method); // these are the default headers. // method.addRequestHeader( "Cache-control", "no-cache" ); // method.addRequestHeader( "Pragma", "no-cache" ); // "Accept-Encoding" is automatically set by HttpClient at runtime - Header header = method.getFirstHeader( "Cache-control" ); - assertNotNull( header ); - assertEquals( "no-cache", header.getValue() ); + Header header = method.getFirstHeader("Cache-control"); + assertNotNull(header); + assertEquals("no-cache", header.getValue()); - header = method.getFirstHeader( "Pragma" ); - assertNotNull( header ); - assertEquals( "no-cache", header.getValue() ); + header = method.getFirstHeader("Pragma"); + assertNotNull(header); + assertEquals("no-cache", header.getValue()); } - public void testTurnOffDefaultHeaders() - { + public void testTurnOffDefaultHeaders() { HttpConfiguration config = new HttpConfiguration(); - config.setAll( new HttpMethodConfiguration().setUseDefaultHeaders( false ) ); + config.setAll(new HttpMethodConfiguration().setUseDefaultHeaders(false)); TestWagon wagon = new TestWagon(); - wagon.setHttpConfiguration( config ); + wagon.setHttpConfiguration(config); HttpHead method = new HttpHead(); - wagon.setHeaders( method ); + wagon.setHeaders(method); // these are the default headers. // method.addRequestHeader( "Cache-control", "no-cache" ); // method.addRequestHeader( "Pragma", "no-cache" ); - Header header = method.getFirstHeader( "Cache-control" ); - assertNull( header ); + Header header = method.getFirstHeader("Cache-control"); + assertNull(header); - header = method.getFirstHeader( "Pragma" ); - assertNull( header ); + header = method.getFirstHeader("Pragma"); + assertNull(header); } @Ignore("not sure how to test this") - public void testNTCredentialsWithUsernameNull() - throws AuthenticationException, ConnectionException - { + public void testNTCredentialsWithUsernameNull() throws AuthenticationException, ConnectionException { TestWagon wagon = new TestWagon(); - Repository repository = new Repository( "mockRepoId", "mockRepoURL" ); - wagon.connect( repository ); + Repository repository = new Repository("mockRepoId", "mockRepoURL"); + wagon.connect(repository); wagon.openConnection(); - assertNull( wagon.getAuthenticationInfo().getUserName() ); - assertNull( wagon.getAuthenticationInfo().getPassword() ); + assertNull(wagon.getAuthenticationInfo().getUserName()); + assertNull(wagon.getAuthenticationInfo().getPassword()); - //assertFalse( wagon.getHttpClient()..getState().getCredentials( new AuthScope( null, 0 ) ) instanceof NTCredentials ); + // assertFalse( wagon.getHttpClient()..getState().getCredentials( new AuthScope( null, 0 ) ) instanceof + // NTCredentials ); } @Ignore("not sure how to test this") - public void testNTCredentialsNoNTDomain() - throws AuthenticationException, ConnectionException - { + public void testNTCredentialsNoNTDomain() throws AuthenticationException, ConnectionException { TestWagon wagon = new TestWagon(); AuthenticationInfo authenticationInfo = new AuthenticationInfo(); String myUsernameNoNTDomain = "myUserNameNoNTDomain"; - authenticationInfo.setUserName( myUsernameNoNTDomain ); + authenticationInfo.setUserName(myUsernameNoNTDomain); String myPassword = "myPassword"; - authenticationInfo.setPassword( myPassword ); + authenticationInfo.setPassword(myPassword); - Repository repository = new Repository( "mockRepoId", "mockRepoURL" ); + Repository repository = new Repository("mockRepoId", "mockRepoURL"); - wagon.connect( repository, authenticationInfo, (ProxyInfo) null ); + wagon.connect(repository, authenticationInfo, (ProxyInfo) null); wagon.openConnection(); - assertEquals( myUsernameNoNTDomain, wagon.getAuthenticationInfo().getUserName() ); - assertEquals( myPassword, wagon.getAuthenticationInfo().getPassword() ); + assertEquals(myUsernameNoNTDomain, wagon.getAuthenticationInfo().getUserName()); + assertEquals(myPassword, wagon.getAuthenticationInfo().getPassword()); - //assertFalse( wagon.getClient().getState().getCredentials( new AuthScope( null, 0 ) ) instanceof NTCredentials ); + // assertFalse( wagon.getClient().getState().getCredentials( new AuthScope( null, 0 ) ) instanceof NTCredentials + // ); } @Ignore("not sure how to test this") - public void testNTCredentialsWithNTDomain() - throws AuthenticationException, ConnectionException - { + public void testNTCredentialsWithNTDomain() throws AuthenticationException, ConnectionException { TestWagon wagon = new TestWagon(); AuthenticationInfo authenticationInfo = new AuthenticationInfo(); String myNTDomain = "myNTDomain"; String myUsername = "myUsername"; String myNTDomainAndUser = myNTDomain + "\\" + myUsername; - authenticationInfo.setUserName( myNTDomainAndUser ); + authenticationInfo.setUserName(myNTDomainAndUser); String myPassword = "myPassword"; - authenticationInfo.setPassword( myPassword ); + authenticationInfo.setPassword(myPassword); - Repository repository = new Repository( "mockRepoId", "mockRepoURL" ); + Repository repository = new Repository("mockRepoId", "mockRepoURL"); - wagon.connect( repository, authenticationInfo, (ProxyInfo) null ); + wagon.connect(repository, authenticationInfo, (ProxyInfo) null); wagon.openConnection(); - assertEquals( myNTDomainAndUser, wagon.getAuthenticationInfo().getUserName() ); - assertEquals( myPassword, wagon.getAuthenticationInfo().getPassword() ); + assertEquals(myNTDomainAndUser, wagon.getAuthenticationInfo().getUserName()); + assertEquals(myPassword, wagon.getAuthenticationInfo().getPassword()); -// Credentials credentials = wagon.getClient().getState().getCredentials( new AuthScope( null, 0 ) ); -// assertTrue( credentials instanceof NTCredentials ); -// -// NTCredentials ntCredentials = (NTCredentials) credentials; -// assertEquals( myNTDomain, ntCredentials.getDomain() ); -// assertEquals( myUsername, ntCredentials.getUserName() ); -// assertEquals( myPassword, ntCredentials.getPassword() ); + // Credentials credentials = wagon.getClient().getState().getCredentials( new AuthScope( null, 0 ) ); + // assertTrue( credentials instanceof NTCredentials ); + // + // NTCredentials ntCredentials = (NTCredentials) credentials; + // assertEquals( myNTDomain, ntCredentials.getDomain() ); + // assertEquals( myUsername, ntCredentials.getUserName() ); + // assertEquals( myPassword, ntCredentials.getPassword() ); } - private static final class TestWagon - extends WebDavWagon - { + private static final class TestWagon extends WebDavWagon { @Override - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - - } + public void fillOutputData(OutputData outputData) throws TransferFailedException {} } - } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/PathNavigatorTest.java b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/PathNavigatorTest.java index 95c0b7902..c31e033aa 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/PathNavigatorTest.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/PathNavigatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,46 +16,45 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; import junit.framework.TestCase; /** * @author James William Dumay */ -public class PathNavigatorTest extends TestCase -{ +public class PathNavigatorTest extends TestCase { private static final String TEST_PATH = "foo/bar/baz"; - public void testBackAndForward() - { - PathNavigator navigator = new PathNavigator( TEST_PATH ); + public void testBackAndForward() { + PathNavigator navigator = new PathNavigator(TEST_PATH); + + assertEquals("foo/bar/baz/", navigator.getPath()); - assertEquals( "foo/bar/baz/", navigator.getPath() ); - // Nav backward - assertTrue( navigator.backward() ); - assertEquals( "foo/bar/", navigator.getPath() ); + assertTrue(navigator.backward()); + assertEquals("foo/bar/", navigator.getPath()); + + assertTrue(navigator.backward()); + assertEquals("foo/", navigator.getPath()); - assertTrue( navigator.backward() ); - assertEquals( "foo/", navigator.getPath() ); + assertTrue(navigator.backward()); + assertEquals("", navigator.getPath()); - assertTrue( navigator.backward() ); - assertEquals( "", navigator.getPath() ); + assertFalse(navigator.backward()); + assertEquals("", navigator.getPath()); - assertFalse( navigator.backward() ); - assertEquals( "", navigator.getPath() ); - // Nav forward - assertTrue( navigator.forward() ); - assertEquals( "foo/", navigator.getPath() ); + assertTrue(navigator.forward()); + assertEquals("foo/", navigator.getPath()); - assertTrue( navigator.forward() ); - assertEquals( "foo/bar/", navigator.getPath() ); + assertTrue(navigator.forward()); + assertEquals("foo/bar/", navigator.getPath()); - assertTrue( navigator.forward() ); - assertEquals( "foo/bar/baz/", navigator.getPath() ); + assertTrue(navigator.forward()); + assertEquals("foo/bar/baz/", navigator.getPath()); - assertFalse( navigator.forward() ); - assertEquals( "foo/bar/baz/", navigator.getPath() ); + assertFalse(navigator.forward()); + assertEquals("foo/bar/baz/", navigator.getPath()); } } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonPreemptiveTest.java b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonPreemptiveTest.java index 2ce97e08a..bcc795882 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonPreemptiveTest.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonPreemptiveTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,35 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.shared.http.HttpConfiguration; import org.apache.maven.wagon.shared.http.HttpMethodConfiguration; -public class WebDavWagonPreemptiveTest - extends WebDavWagonTest -{ +public class WebDavWagonPreemptiveTest extends WebDavWagonTest { @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { WebDavWagon wagon = (WebDavWagon) super.getWagon(); wagon.setHttpConfiguration( - new HttpConfiguration() // - .setAll( new HttpMethodConfiguration().setUsePreemptive( true ) ) ); + new HttpConfiguration() // + .setAll(new HttpMethodConfiguration().setUsePreemptive(true))); return wagon; } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return true; } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return true; } - } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonTest.java b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonTest.java index 317007a44..223e2888d 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonTest.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; + +import javax.servlet.http.HttpServletResponse; + +import java.io.File; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.List; +import java.util.Properties; import it.could.webdav.DAVServlet; import org.apache.http.HttpException; @@ -36,14 +43,6 @@ import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import java.io.File; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.List; -import java.util.Properties; - -import javax.servlet.http.HttpServletResponse; - /* * WebDAV Wagon Test * @@ -51,157 +50,129 @@ * * @author Carlos Sanchez */ -public class WebDavWagonTest - extends HttpWagonTestCase -{ +public class WebDavWagonTest extends HttpWagonTestCase { - protected String getTestRepositoryUrl() - throws IOException - { + protected String getTestRepositoryUrl() throws IOException { return getProtocol() + "://localhost:" + getTestRepositoryPort() + "/newfolder/folder2/"; } - protected String getProtocol() - { + protected String getProtocol() { return "dav"; } - protected ServletContextHandler createContext( Server server, File repositoryDirectory ) - throws IOException - { - ServletContextHandler dav = new ServletContextHandler( ServletContextHandler.SESSIONS ); - ServletHolder davServletHolder = new ServletHolder( new DAVServlet() ); - davServletHolder.setInitParameter( "rootPath", repositoryDirectory.getAbsolutePath() ); - davServletHolder.setInitParameter( "xmlOnly", "false" ); - dav.addServlet( davServletHolder, "/*" ); + protected ServletContextHandler createContext(Server server, File repositoryDirectory) throws IOException { + ServletContextHandler dav = new ServletContextHandler(ServletContextHandler.SESSIONS); + ServletHolder davServletHolder = new ServletHolder(new DAVServlet()); + davServletHolder.setInitParameter("rootPath", repositoryDirectory.getAbsolutePath()); + davServletHolder.setInitParameter("xmlOnly", "false"); + dav.addServlet(davServletHolder, "/*"); return dav; } - protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource ) - { - File file = new File( getDavRepository(), resource.getName() ); - return ( file.lastModified() / 1000L ) * 1000L; + protected long getExpectedLastModifiedOnGet(Repository repository, Resource resource) { + File file = new File(getDavRepository(), resource.getName()); + return (file.lastModified() / 1000L) * 1000L; } - - private File getDavRepository() - { - return getTestFile( "target/test-output/http-repository/newfolder/folder2" ); + private File getDavRepository() { + return getTestFile("target/test-output/http-repository/newfolder/folder2"); } - private void assertURL( String userUrl, String expectedUrl ) - { - Repository repo = new Repository( "test-geturl", userUrl ); - String actualUrl = ( new WebDavWagon() ).getURL( repo ); - assertEquals( "WebDavWagon.getURL(" + userUrl + ")", expectedUrl, actualUrl ); + private void assertURL(String userUrl, String expectedUrl) { + Repository repo = new Repository("test-geturl", userUrl); + String actualUrl = (new WebDavWagon()).getURL(repo); + assertEquals("WebDavWagon.getURL(" + userUrl + ")", expectedUrl, actualUrl); } /** * Tests the maven 2.0.x way to define a webdav URL without SSL. */ - public void testGetURLDavHttp() - { - assertURL( "dav:http://localhost:9080/dav/", - "http://localhost:9080/dav/" ); + public void testGetURLDavHttp() { + assertURL("dav:http://localhost:9080/dav/", "http://localhost:9080/dav/"); } /** * Tests the maven 2.0.x way to define a webdav URL with SSL. */ - public void testGetURLDavHttps() - { - assertURL( "dav:https://localhost:9443/dav/", - "https://localhost:9443/dav/" ); + public void testGetURLDavHttps() { + assertURL("dav:https://localhost:9443/dav/", "https://localhost:9443/dav/"); } /** * Tests the URI spec way of defining a webdav URL without SSL. */ - public void testGetURLDavUri() - { - assertURL( "dav://localhost:9080/dav/", - "http://localhost:9080/dav/" ); + public void testGetURLDavUri() { + assertURL("dav://localhost:9080/dav/", "http://localhost:9080/dav/"); } /** * Tests the URI spec way of defining a webdav URL with SSL. */ - public void testGetURLDavUriWithSsl() - { - assertURL( "davs://localhost:9443/dav/", - "https://localhost:9443/dav/" ); + public void testGetURLDavUriWithSsl() { + assertURL("davs://localhost:9443/dav/", "https://localhost:9443/dav/"); } /** * Tests the URI spec way of defining a webdav URL without SSL. */ - public void testGetURLDavPlusHttp() - { - assertURL( "dav+https://localhost:" + getTestRepositoryPort() + "/dav/", - "https://localhost:" + getTestRepositoryPort() + "/dav/" ); + public void testGetURLDavPlusHttp() { + assertURL( + "dav+https://localhost:" + getTestRepositoryPort() + "/dav/", + "https://localhost:" + getTestRepositoryPort() + "/dav/"); } /** * Tests the URI spec way of defining a webdav URL with SSL. */ - public void testGetURLDavPlusHttps() - { - assertURL( "dav+https://localhost:9443/dav/", - "https://localhost:9443/dav/" ); + public void testGetURLDavPlusHttps() { + assertURL("dav+https://localhost:9443/dav/", "https://localhost:9443/dav/"); } - public void testMkdirs() - throws Exception - { + public void testMkdirs() throws Exception { setupWagonTestingFixtures(); setupRepositories(); WebDavWagon wagon = (WebDavWagon) getWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - try - { + try { File dir = getRepositoryDirectory(); // check basedir also doesn't exist and will need to be created - dir = new File( dir, testRepository.getBasedir() ); - assertFalse( dir.exists() ); + dir = new File(dir, testRepository.getBasedir()); + assertFalse(dir.exists()); // test leading / - assertFalse( new File( dir, "foo" ).exists() ); - wagon.mkdirs( "/foo" ); - assertTrue( new File( dir, "foo" ).exists() ); + assertFalse(new File(dir, "foo").exists()); + wagon.mkdirs("/foo"); + assertTrue(new File(dir, "foo").exists()); // test trailing / - assertFalse( new File( dir, "bar" ).exists() ); - wagon.mkdirs( "bar/" ); - assertTrue( new File( dir, "bar" ).exists() ); + assertFalse(new File(dir, "bar").exists()); + wagon.mkdirs("bar/"); + assertTrue(new File(dir, "bar").exists()); // test when already exists - wagon.mkdirs( "bar" ); + wagon.mkdirs("bar"); // test several parts - assertFalse( new File( dir, "1/2/3/4" ).exists() ); - wagon.mkdirs( "1/2/3/4" ); - assertTrue( new File( dir, "1/2/3/4" ).exists() ); + assertFalse(new File(dir, "1/2/3/4").exists()); + wagon.mkdirs("1/2/3/4"); + assertTrue(new File(dir, "1/2/3/4").exists()); // test additional part and trailing / - assertFalse( new File( dir, "1/2/3/4/5" ).exists() ); - wagon.mkdirs( "1/2/3/4/5/" ); - assertTrue( new File( dir, "1/2/3/4" ).exists() ); - } - finally - { + assertFalse(new File(dir, "1/2/3/4/5").exists()); + wagon.mkdirs("1/2/3/4/5/"); + assertTrue(new File(dir, "1/2/3/4").exists()); + } finally { wagon.disconnect(); tearDownWagonTestingFixtures(); } } - public void testMkdirsWithNoBasedir() - throws Exception - { + public void testMkdirsWithNoBasedir() throws Exception { // WAGON-244 setupWagonTestingFixtures(); @@ -209,41 +180,37 @@ public void testMkdirsWithNoBasedir() // reconstruct with no basedir testRepository.setUrl( - testRepository.getProtocol() + "://" + testRepository.getHost() + ":" + testRepository.getPort() ); + testRepository.getProtocol() + "://" + testRepository.getHost() + ":" + testRepository.getPort()); WebDavWagon wagon = (WebDavWagon) getWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - try - { + try { File dir = getRepositoryDirectory(); // check basedir also doesn't exist and will need to be created - dir = new File( dir, testRepository.getBasedir() ); - assertTrue( dir.exists() ); + dir = new File(dir, testRepository.getBasedir()); + assertTrue(dir.exists()); // test leading / - assertFalse( new File( dir, "foo" ).exists() ); - wagon.mkdirs( "/foo" ); - assertTrue( new File( dir, "foo" ).exists() ); - } - finally - { + assertFalse(new File(dir, "foo").exists()); + wagon.mkdirs("/foo"); + assertTrue(new File(dir, "foo").exists()); + } finally { wagon.disconnect(); tearDownWagonTestingFixtures(); } } - protected void setHttpConfiguration( StreamingWagon wagon, Properties headers, Properties params ) - { + protected void setHttpConfiguration(StreamingWagon wagon, Properties headers, Properties params) { HttpConfiguration config = new HttpConfiguration(); HttpMethodConfiguration methodConfiguration = new HttpMethodConfiguration(); - methodConfiguration.setHeaders( headers ); - methodConfiguration.setParams( params ); - config.setAll( methodConfiguration ); - ( (WebDavWagon) wagon ).setHttpConfiguration( config ); + methodConfiguration.setHeaders(headers); + methodConfiguration.setParams(params); + config.setAll(methodConfiguration); + ((WebDavWagon) wagon).setHttpConfiguration(config); } /** @@ -251,9 +218,7 @@ protected void setHttpConfiguration( StreamingWagon wagon, Properties headers, P * * @throws Exception */ - public void testWagonWebDavGetFileList() - throws Exception - { + public void testWagonWebDavGetFileList() throws Exception { setupWagonTestingFixtures(); setupRepositories(); @@ -261,57 +226,50 @@ public void testWagonWebDavGetFileList() String dirName = "file-list"; String filenames[] = - new String[]{ "test-resource.txt", "test-resource.pom", "test-resource b.txt", "more-resources.dat" }; + new String[] {"test-resource.txt", "test-resource.pom", "test-resource b.txt", "more-resources.dat"}; - for ( int i = 0; i < filenames.length; i++ ) - { - putFile( dirName + "/" + filenames[i], dirName + "/" + filenames[i], filenames[i] + "\n" ); + for (int i = 0; i < filenames.length; i++) { + putFile(dirName + "/" + filenames[i], dirName + "/" + filenames[i], filenames[i] + "\n"); } - String dirnames[] = new String[]{ "test-dir1", "test-dir2" }; + String dirnames[] = new String[] {"test-dir1", "test-dir2"}; - for ( int i = 0; i < dirnames.length; i++ ) - { - new File( getDavRepository(), dirName + "/" + dirnames[i] ).mkdirs(); + for (int i = 0; i < dirnames.length; i++) { + new File(getDavRepository(), dirName + "/" + dirnames[i]).mkdirs(); } Wagon wagon = getWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - List list = wagon.getFileList( dirName ); + List list = wagon.getFileList(dirName); - assertNotNull( "file list should not be null.", list ); - assertEquals( "file list should contain 6 items", 6, list.size() ); + assertNotNull("file list should not be null.", list); + assertEquals("file list should contain 6 items", 6, list.size()); - for ( int i = 0; i < filenames.length; i++ ) - { - assertTrue( "Filename '" + filenames[i] + "' should be in list.", list.contains( filenames[i] ) ); + for (int i = 0; i < filenames.length; i++) { + assertTrue("Filename '" + filenames[i] + "' should be in list.", list.contains(filenames[i])); } - for ( int i = 0; i < dirnames.length; i++ ) - { - assertTrue( "Directory '" + dirnames[i] + "' should be in list.", list.contains( dirnames[i] + "/" ) ); + for (int i = 0; i < dirnames.length; i++) { + assertTrue("Directory '" + dirnames[i] + "' should be in list.", list.contains(dirnames[i] + "/")); } /////////////////////////////////////////////////////////////////////////// - list = wagon.getFileList( "" ); - assertNotNull( "file list should not be null.", list ); - assertEquals( "file list should contain 1 items", 1, list.size() ); + list = wagon.getFileList(""); + assertNotNull("file list should not be null.", list); + assertEquals("file list should contain 1 items", 1, list.size()); /////////////////////////////////////////////////////////////////////////// - list = wagon.getFileList( dirName + "/test-dir1" ); - assertNotNull( "file list should not be null.", list ); - assertEquals( "file list should contain 0 items", 0, list.size() ); + list = wagon.getFileList(dirName + "/test-dir1"); + assertNotNull("file list should not be null.", list); + assertEquals("file list should contain 0 items", 0, list.size()); ///////////////////////////////////////////////////////////////////////////// - try - { - list = wagon.getFileList( dirName + "/test-dir-bogus" ); - fail( "Exception expected" ); - } - catch ( ResourceDoesNotExistException e ) - { + try { + list = wagon.getFileList(dirName + "/test-dir-bogus"); + fail("Exception expected"); + } catch (ResourceDoesNotExistException e) { } @@ -320,73 +278,54 @@ public void testWagonWebDavGetFileList() tearDownWagonTestingFixtures(); } - - public void testWagonFailsOnPutFailureByDefault() - throws Exception - { + public void testWagonFailsOnPutFailureByDefault() throws Exception { setupWagonTestingFixtures(); setupRepositories(); File testFile = getTempFile(); - System.clearProperty( WebDavWagon.CONTINUE_ON_FAILURE_PROPERTY ); + System.clearProperty(WebDavWagon.CONTINUE_ON_FAILURE_PROPERTY); WebDavWagon wagon = new TimeoutSimulatingWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - try - { + try { String filename = TimeoutSimulatingWagon.TIMEOUT_TRIGGER + ".txt"; - try - { - wagon.put( testFile, filename ); - fail( "Exception expected" ); - } - catch ( TransferFailedException e ) - { + try { + wagon.put(testFile, filename); + fail("Exception expected"); + } catch (TransferFailedException e) { } - } - finally - { + } finally { wagon.disconnect(); tearDownWagonTestingFixtures(); } } - private File getTempFile() - throws IOException - { - File inputFile = File.createTempFile( "test-resource", ".txt" ); + private File getTempFile() throws IOException { + File inputFile = File.createTempFile("test-resource", ".txt"); inputFile.deleteOnExit(); return inputFile; } - private static class TimeoutSimulatingWagon - extends WebDavWagon - { + private static class TimeoutSimulatingWagon extends WebDavWagon { private static final String TIMEOUT_TRIGGER = "timeout"; - protected CloseableHttpResponse execute( HttpUriRequest httpRequestBase ) - throws HttpException, IOException - { - if ( httpRequestBase.getURI().getPath().contains( TIMEOUT_TRIGGER ) ) - { - throw new SocketTimeoutException( "Timeout triggered by request for '" + httpRequestBase.getURI().getPath() + "'" ); - } - else - { - return super.execute( httpRequestBase ); + protected CloseableHttpResponse execute(HttpUriRequest httpRequestBase) throws HttpException, IOException { + if (httpRequestBase.getURI().getPath().contains(TIMEOUT_TRIGGER)) { + throw new SocketTimeoutException("Timeout triggered by request for '" + + httpRequestBase.getURI().getPath() + "'"); + } else { + return super.execute(httpRequestBase); } } } - public void testWagonContinuesOnPutFailureIfPropertySet() - throws Exception - { + public void testWagonContinuesOnPutFailureIfPropertySet() throws Exception { setupWagonTestingFixtures(); setupRepositories(); @@ -394,139 +333,143 @@ public void testWagonContinuesOnPutFailureIfPropertySet() File testFile = getTempFile(); String continueOnFailureProperty = WebDavWagon.CONTINUE_ON_FAILURE_PROPERTY; - System.setProperty( continueOnFailureProperty, "true" ); + System.setProperty(continueOnFailureProperty, "true"); WebDavWagon wagon = new TimeoutSimulatingWagon(); - wagon.connect( testRepository, getAuthInfo() ); + wagon.connect(testRepository, getAuthInfo()); - try - { + try { String filename = TimeoutSimulatingWagon.TIMEOUT_TRIGGER + ".txt"; - wagon.put( testFile, filename ); - } - finally - { + wagon.put(testFile, filename); + } finally { wagon.disconnect(); - System.clearProperty( continueOnFailureProperty ); + System.clearProperty(continueOnFailureProperty); tearDownWagonTestingFixtures(); } } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return false; } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return false; } @Override - protected boolean supportProxyPreemptiveAuthentication() - { + protected boolean supportProxyPreemptiveAuthentication() { return true; } - protected void testPreemptiveAuthenticationGet( TestSecurityHandler sh, boolean preemptive ) - { - if ( preemptive ) - { - assertEquals( "testPreemptiveAuthenticationGet preemptive=true: expected 1 request, got " - + sh.handlerRequestResponses, 1, sh.handlerRequestResponses.size() ); - assertEquals( HttpServletResponse.SC_OK, sh.handlerRequestResponses.get( 0 ).responseCode ); - } - else - { - assertEquals( "testPreemptiveAuthenticationGet preemptive=false: expected 2 requests (401,200), got " - + sh.handlerRequestResponses, 2, sh.handlerRequestResponses.size() ); - assertEquals( HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( HttpServletResponse.SC_OK, sh.handlerRequestResponses.get( 1 ).responseCode ); + protected void testPreemptiveAuthenticationGet(TestSecurityHandler sh, boolean preemptive) { + if (preemptive) { + assertEquals( + "testPreemptiveAuthenticationGet preemptive=true: expected 1 request, got " + + sh.handlerRequestResponses, + 1, + sh.handlerRequestResponses.size()); + assertEquals(HttpServletResponse.SC_OK, sh.handlerRequestResponses.get(0).responseCode); + } else { + assertEquals( + "testPreemptiveAuthenticationGet preemptive=false: expected 2 requests (401,200), got " + + sh.handlerRequestResponses, + 2, + sh.handlerRequestResponses.size()); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get(0).responseCode); + assertEquals(HttpServletResponse.SC_OK, sh.handlerRequestResponses.get(1).responseCode); } } - protected void testPreemptiveAuthenticationPut( TestSecurityHandler sh, boolean preemptive ) - { - if ( preemptive ) - { - assertEquals( "testPreemptiveAuthenticationPut preemptive=true: expected 2 requests (200,201), got " - + sh.handlerRequestResponses, 2, sh.handlerRequestResponses.size() ); - assertEquals( HttpServletResponse.SC_OK, sh.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( HttpServletResponse.SC_CREATED, sh.handlerRequestResponses.get( 1 ).responseCode ); - } - else - { - assertEquals( "testPreemptiveAuthenticationPut preemptive=false: expected 3 requests (401,200,201), got " - + sh.handlerRequestResponses, 3, sh.handlerRequestResponses.size() ); - assertEquals( HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( HttpServletResponse.SC_OK, sh.handlerRequestResponses.get( 1 ).responseCode ); - assertEquals( HttpServletResponse.SC_CREATED, sh.handlerRequestResponses.get( 2 ).responseCode ); + protected void testPreemptiveAuthenticationPut(TestSecurityHandler sh, boolean preemptive) { + if (preemptive) { + assertEquals( + "testPreemptiveAuthenticationPut preemptive=true: expected 2 requests (200,201), got " + + sh.handlerRequestResponses, + 2, + sh.handlerRequestResponses.size()); + assertEquals(HttpServletResponse.SC_OK, sh.handlerRequestResponses.get(0).responseCode); + assertEquals(HttpServletResponse.SC_CREATED, sh.handlerRequestResponses.get(1).responseCode); + } else { + assertEquals( + "testPreemptiveAuthenticationPut preemptive=false: expected 3 requests (401,200,201), got " + + sh.handlerRequestResponses, + 3, + sh.handlerRequestResponses.size()); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get(0).responseCode); + assertEquals(HttpServletResponse.SC_OK, sh.handlerRequestResponses.get(1).responseCode); + assertEquals(HttpServletResponse.SC_CREATED, sh.handlerRequestResponses.get(2).responseCode); } } - /* This method cannot be reasonable used to represend GET and PUT for WebDAV, it would contain too much * duplicate code. Leave as-is, but don't use it. */ - protected void testPreemptiveAuthentication( TestSecurityHandler sh, boolean preemptive ) - { - if ( preemptive ) - { - assertEquals( "testPreemptiveAuthentication preemptive=false: expected 2 requests (200,.), got " - + sh.handlerRequestResponses, 2, sh.handlerRequestResponses.size() ); - assertEquals( HttpServletResponse.SC_OK, sh.handlerRequestResponses.get( 0 ).responseCode ); - } - else - { - assertEquals( "testPreemptiveAuthentication preemptive=false: expected 3 requests (401,200,200), got " - + sh.handlerRequestResponses, 3, sh.handlerRequestResponses.size() ); - assertEquals( HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( HttpServletResponse.SC_OK, sh.handlerRequestResponses.get( 1 ).responseCode ); - assertEquals( HttpServletResponse.SC_OK, sh.handlerRequestResponses.get( 2 ).responseCode ); - + protected void testPreemptiveAuthentication(TestSecurityHandler sh, boolean preemptive) { + if (preemptive) { + assertEquals( + "testPreemptiveAuthentication preemptive=false: expected 2 requests (200,.), got " + + sh.handlerRequestResponses, + 2, + sh.handlerRequestResponses.size()); + assertEquals(HttpServletResponse.SC_OK, sh.handlerRequestResponses.get(0).responseCode); + } else { + assertEquals( + "testPreemptiveAuthentication preemptive=false: expected 3 requests (401,200,200), got " + + sh.handlerRequestResponses, + 3, + sh.handlerRequestResponses.size()); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, sh.handlerRequestResponses.get(0).responseCode); + assertEquals(HttpServletResponse.SC_OK, sh.handlerRequestResponses.get(1).responseCode); + assertEquals(HttpServletResponse.SC_OK, sh.handlerRequestResponses.get(2).responseCode); } } @Override - protected void checkRequestResponseForRedirectPutWithFullUrl( RedirectHandler redirectHandler, - PutHandler putHandler ) - { - assertEquals( "found:" + putHandler.handlerRequestResponses, 1, putHandler.handlerRequestResponses.size() ); - assertEquals( "found:" + putHandler.handlerRequestResponses, HttpServletResponse.SC_CREATED, - putHandler.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( "found:" + redirectHandler.handlerRequestResponses, 2, - redirectHandler.handlerRequestResponses.size() ); - assertEquals( "found:" + redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER, - redirectHandler.handlerRequestResponses.get( 0 ).responseCode ); + protected void checkRequestResponseForRedirectPutWithFullUrl( + RedirectHandler redirectHandler, PutHandler putHandler) { + assertEquals("found:" + putHandler.handlerRequestResponses, 1, putHandler.handlerRequestResponses.size()); + assertEquals( + "found:" + putHandler.handlerRequestResponses, + HttpServletResponse.SC_CREATED, + putHandler.handlerRequestResponses.get(0).responseCode); + assertEquals( + "found:" + redirectHandler.handlerRequestResponses, 2, redirectHandler.handlerRequestResponses.size()); + assertEquals( + "found:" + redirectHandler.handlerRequestResponses, + HttpServletResponse.SC_SEE_OTHER, + redirectHandler.handlerRequestResponses.get(0).responseCode); } @Override - protected void checkRequestResponseForRedirectPutWithRelativeUrl( RedirectHandler redirectHandler, - PutHandler putHandler ) - { - assertEquals( "found:" + putHandler.handlerRequestResponses, 0, putHandler.handlerRequestResponses.size() ); - - assertEquals( "found:" + redirectHandler.handlerRequestResponses, 4, - redirectHandler.handlerRequestResponses.size() ); - assertEquals( "found:" + redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER, - redirectHandler.handlerRequestResponses.get( 0 ).responseCode ); - assertEquals( "found:" + redirectHandler.handlerRequestResponses, HttpServletResponse.SC_OK, - redirectHandler.handlerRequestResponses.get( 1 ).responseCode ); - assertEquals( "found:" + redirectHandler.handlerRequestResponses, HttpServletResponse.SC_SEE_OTHER, - redirectHandler.handlerRequestResponses.get( 2 ).responseCode ); - + protected void checkRequestResponseForRedirectPutWithRelativeUrl( + RedirectHandler redirectHandler, PutHandler putHandler) { + assertEquals("found:" + putHandler.handlerRequestResponses, 0, putHandler.handlerRequestResponses.size()); + + assertEquals( + "found:" + redirectHandler.handlerRequestResponses, 4, redirectHandler.handlerRequestResponses.size()); + assertEquals( + "found:" + redirectHandler.handlerRequestResponses, + HttpServletResponse.SC_SEE_OTHER, + redirectHandler.handlerRequestResponses.get(0).responseCode); + assertEquals( + "found:" + redirectHandler.handlerRequestResponses, + HttpServletResponse.SC_OK, + redirectHandler.handlerRequestResponses.get(1).responseCode); + assertEquals( + "found:" + redirectHandler.handlerRequestResponses, + HttpServletResponse.SC_SEE_OTHER, + redirectHandler.handlerRequestResponses.get(2).responseCode); } @Override - protected void verifyWagonExceptionMessage( Exception e, int forStatusCode, String forUrl, String forReasonPhrase ) - { - Repository repo = new Repository( "test-geturl", forUrl ); - String expectedMessageUrl = ( new WebDavWagon() ).getURL( repo ); - super.verifyWagonExceptionMessage( e, forStatusCode, expectedMessageUrl, forReasonPhrase ); + protected void verifyWagonExceptionMessage(Exception e, int forStatusCode, String forUrl, String forReasonPhrase) { + Repository repo = new Repository("test-geturl", forUrl); + String expectedMessageUrl = (new WebDavWagon()).getURL(repo); + super.verifyWagonExceptionMessage(e, forStatusCode, expectedMessageUrl, forReasonPhrase); } } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonPreemptiveTest.java b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonPreemptiveTest.java index c578c1639..9731c83dc 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonPreemptiveTest.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonPreemptiveTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.shared.http.HttpConfiguration; @@ -32,52 +31,44 @@ * @author Joakim Erdfelt * @author Carlos Sanchez */ -public class WebDavsWagonPreemptiveTest - extends WebDavWagonTest -{ - protected String getProtocol() - { +public class WebDavsWagonPreemptiveTest extends WebDavWagonTest { + protected String getProtocol() { return "davs"; } - protected ServerConnector addConnector( Server server ) - { - System.setProperty( "javax.net.ssl.trustStore", - getTestFile( "src/test/resources/ssl/keystore" ).getAbsolutePath() ); + protected ServerConnector addConnector(Server server) { + System.setProperty( + "javax.net.ssl.trustStore", + getTestFile("src/test/resources/ssl/keystore").getAbsolutePath()); SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setKeyStorePassword( "wagonhttp" ); - sslContextFactory.setKeyManagerPassword( "wagonhttp" ); - sslContextFactory.setTrustStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setTrustStorePassword( "wagonhttp" ); + sslContextFactory.setKeyStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setKeyStorePassword("wagonhttp"); + sslContextFactory.setKeyManagerPassword("wagonhttp"); + sslContextFactory.setTrustStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setTrustStorePassword("wagonhttp"); - ServerConnector serverConnector = new ServerConnector( server, sslContextFactory ); - server.addConnector( serverConnector ); + ServerConnector serverConnector = new ServerConnector(server, sslContextFactory); + server.addConnector(serverConnector); return serverConnector; } @Override - protected Wagon getWagon() - throws Exception - { + protected Wagon getWagon() throws Exception { WebDavWagon wagon = (WebDavWagon) super.getWagon(); wagon.setHttpConfiguration( - new HttpConfiguration() // - .setAll( new HttpMethodConfiguration().setUsePreemptive( true ) ) ); + new HttpConfiguration() // + .setAll(new HttpMethodConfiguration().setUsePreemptive(true))); return wagon; } @Override - protected boolean supportPreemptiveAuthenticationPut() - { + protected boolean supportPreemptiveAuthenticationPut() { return true; } @Override - protected boolean supportPreemptiveAuthenticationGet() - { + protected boolean supportPreemptiveAuthenticationGet() { return true; } - } diff --git a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonTest.java b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonTest.java index 3a89ef082..1c9464735 100644 --- a/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonTest.java +++ b/wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/WebDavsWagonTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.providers.webdav; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.providers.webdav; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; @@ -29,29 +28,25 @@ * @author Joakim Erdfelt * @author Carlos Sanchez */ -public class WebDavsWagonTest - extends WebDavWagonTest -{ - protected String getProtocol() - { +public class WebDavsWagonTest extends WebDavWagonTest { + protected String getProtocol() { return "davs"; } - protected ServerConnector addConnector( Server server ) - { - System.setProperty( "javax.net.ssl.trustStore", - getTestFile( "src/test/resources/ssl/keystore" ).getAbsolutePath() ); + protected ServerConnector addConnector(Server server) { + System.setProperty( + "javax.net.ssl.trustStore", + getTestFile("src/test/resources/ssl/keystore").getAbsolutePath()); SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setKeyStorePassword( "wagonhttp" ); - sslContextFactory.setKeyManagerPassword( "wagonhttp" ); - sslContextFactory.setTrustStorePath( getTestPath( "src/test/resources/ssl/keystore" ) ); - sslContextFactory.setTrustStorePassword( "wagonhttp" ); + sslContextFactory.setKeyStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setKeyStorePassword("wagonhttp"); + sslContextFactory.setKeyManagerPassword("wagonhttp"); + sslContextFactory.setTrustStorePath(getTestPath("src/test/resources/ssl/keystore")); + sslContextFactory.setTrustStorePassword("wagonhttp"); - ServerConnector serverConnector = new ServerConnector( server, sslContextFactory ); - server.addConnector( serverConnector ); + ServerConnector serverConnector = new ServerConnector(server, sslContextFactory); + server.addConnector(serverConnector); return serverConnector; } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/Assertions.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/Assertions.java index d0eb71905..35bda8d5f 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/Assertions.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/Assertions.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http; + +import javax.servlet.http.HttpServletResponse; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.TransferFailedException; @@ -28,11 +33,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - import static org.codehaus.plexus.util.FileUtils.fileRead; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -41,42 +41,36 @@ /** * */ -public final class Assertions -{ +public final class Assertions { public static final int NO_RESPONSE_STATUS_CODE = -1; - protected static final Logger LOGGER = LoggerFactory.getLogger( Assertions.class ); + protected static final Logger LOGGER = LoggerFactory.getLogger(Assertions.class); - public static void assertFileContentsFromResource( final String resourceBase, final String resourceName, - final File output, final String whyWouldItFail ) - throws IOException - { - String content = readResource( resourceBase, resourceName ); - String test = fileRead( output ); + public static void assertFileContentsFromResource( + final String resourceBase, final String resourceName, final File output, final String whyWouldItFail) + throws IOException { + String content = readResource(resourceBase, resourceName); + String test = fileRead(output); - assertEquals( whyWouldItFail, content, test ); + assertEquals(whyWouldItFail, content, test); } - private static String readResource( final String base, final String name ) - throws IOException - { + private static String readResource(final String base, final String name) throws IOException { String url = base; - if ( !url.endsWith( "/" ) && !name.startsWith( "/" ) ) - { + if (!url.endsWith("/") && !name.startsWith("/")) { url += "/"; } url += name; ClassLoader cloader = Thread.currentThread().getContextClassLoader(); - InputStream stream = cloader.getResourceAsStream( url ); + InputStream stream = cloader.getResourceAsStream(url); - if ( stream == null ) - { + if (stream == null) { return null; } - final String resource = IOUtil.toString( stream ); + final String resource = IOUtil.toString(stream); stream.close(); return resource; } @@ -93,113 +87,120 @@ private static String readResource( final String base, final String name ) * @param forUrl the url that triggered the exception * @param forReasonPhrase the optional status line reason phrase the server returned */ - public static void assertWagonExceptionMessage( Exception e, int forStatusCode, String forUrl, - String forReasonPhrase, ProxyInfo proxyInfo ) - { + public static void assertWagonExceptionMessage( + Exception e, int forStatusCode, String forUrl, String forReasonPhrase, ProxyInfo proxyInfo) { // TODO: handle AuthenticationException for Wagon.connect() calls - assertNotNull( e ); - try - { - assertTrue( "only verify instances of WagonException", e instanceof WagonException ); + assertNotNull(e); + try { + assertTrue("only verify instances of WagonException", e instanceof WagonException); String reasonPhrase; String assertMessageForBadMessage = "exception message not described properly"; - if ( proxyInfo != null ) - { - assertTrue( "message should end with proxy information if proxy was used", - e.getMessage().endsWith( proxyInfo.toString() ) ); + if (proxyInfo != null) { + assertTrue( + "message should end with proxy information if proxy was used", + e.getMessage().endsWith(proxyInfo.toString())); } - switch ( forStatusCode ) - { + switch (forStatusCode) { case HttpServletResponse.SC_NOT_FOUND: // TODO: add test for 410: Gone? - assertTrue( "404 not found response should throw ResourceDoesNotExistException", - e instanceof ResourceDoesNotExistException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - ? " Not Found" : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "resource missing at " + forUrl + ", status: 404" - + reasonPhrase, e.getMessage() ); + assertTrue( + "404 not found response should throw ResourceDoesNotExistException", + e instanceof ResourceDoesNotExistException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Not Found" + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "resource missing at " + forUrl + ", status: 404" + reasonPhrase, + e.getMessage()); break; case HttpServletResponse.SC_UNAUTHORIZED: // FIXME assumes Wagon.get()/put() returning 401 instead of Wagon.connect() - assertTrue( "401 Unauthorized should throw AuthorizationException since " + assertTrue( + "401 Unauthorized should throw AuthorizationException since " + " AuthenticationException is not explicitly declared as thrown from wagon " + "methods", - e instanceof AuthorizationException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - ? " Unauthorized" : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "authentication failed for " + forUrl + ", status: 401" - + reasonPhrase, e.getMessage() ); + e instanceof AuthorizationException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Unauthorized" + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "authentication failed for " + forUrl + ", status: 401" + reasonPhrase, + e.getMessage()); break; case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: - assertTrue( "407 Proxy authentication required should throw AuthorizationException", - e instanceof AuthorizationException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - + assertTrue( + "407 Proxy authentication required should throw AuthorizationException", + e instanceof AuthorizationException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) ? " Proxy Authentication Required" - : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "proxy authentication failed for " - + forUrl + ", status: 407" + reasonPhrase, e.getMessage() ); + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "proxy authentication failed for " + forUrl + ", status: 407" + reasonPhrase, + e.getMessage()); break; case HttpServletResponse.SC_FORBIDDEN: - assertTrue( "403 Forbidden should throw AuthorizationException", - e instanceof AuthorizationException ); - reasonPhrase = ( forReasonPhrase == null || forReasonPhrase.isEmpty() ) - ? " Forbidden" : ( " " + forReasonPhrase ); - assertEquals( assertMessageForBadMessage, "authorization failed for " + forUrl + ", status: 403" - + reasonPhrase, e.getMessage() ); + assertTrue( + "403 Forbidden should throw AuthorizationException", e instanceof AuthorizationException); + reasonPhrase = (forReasonPhrase == null || forReasonPhrase.isEmpty()) + ? " Forbidden" + : (" " + forReasonPhrase); + assertEquals( + assertMessageForBadMessage, + "authorization failed for " + forUrl + ", status: 403" + reasonPhrase, + e.getMessage()); break; default: - assertTrue( "transfer failures should at least be wrapped in a TransferFailedException", e - instanceof TransferFailedException ); + assertTrue( + "transfer failures should at least be wrapped in a TransferFailedException", + e instanceof TransferFailedException); // the status code and reason phrase cannot always be learned due to implementation limitations // so the message may not include them, but the implementation should use a consistent format - assertTrue( "message should always include url tried: " + e.getMessage(), - e.getMessage().startsWith( "transfer failed for " + forUrl ) ); + assertTrue( + "message should always include url tried: " + e.getMessage(), + e.getMessage().startsWith("transfer failed for " + forUrl)); - String statusCodeStr = forStatusCode == NO_RESPONSE_STATUS_CODE ? "" - : ", status: " + forStatusCode; - if ( forStatusCode != NO_RESPONSE_STATUS_CODE ) - { + String statusCodeStr = forStatusCode == NO_RESPONSE_STATUS_CODE ? "" : ", status: " + forStatusCode; + if (forStatusCode != NO_RESPONSE_STATUS_CODE) { - assertTrue( "if there was a response status line, the status code should be >= 400", - forStatusCode >= HttpServletResponse.SC_BAD_REQUEST ); + assertTrue( + "if there was a response status line, the status code should be >= 400", + forStatusCode >= HttpServletResponse.SC_BAD_REQUEST); - if ( e.getMessage().length() > ( "transfer failed for " + forUrl ).length() ) - { - assertTrue( "message should include url and status code: " + e.getMessage(), - e.getMessage().startsWith( "transfer failed for " + forUrl + statusCodeStr ) ); + if (e.getMessage().length() > ("transfer failed for " + forUrl).length()) { + assertTrue( + "message should include url and status code: " + e.getMessage(), + e.getMessage().startsWith("transfer failed for " + forUrl + statusCodeStr)); } reasonPhrase = forReasonPhrase == null ? "" : " " + forReasonPhrase; - if ( reasonPhrase.length() > 0 && e.getMessage().length() > ( "transfer failed for " + forUrl - + statusCodeStr ).length() ) - { - assertTrue( "message should include url and status code and reason phrase: " - + e.getMessage(), e.getMessage().startsWith( "transfer failed for " - + forUrl + statusCodeStr - + reasonPhrase ) ); + if (reasonPhrase.length() > 0 + && e.getMessage().length() + > ("transfer failed for " + forUrl + statusCodeStr).length()) { + assertTrue( + "message should include url and status code and reason phrase: " + e.getMessage(), + e.getMessage() + .startsWith( + "transfer failed for " + forUrl + statusCodeStr + reasonPhrase)); } - } break; } - } - catch ( AssertionError assertionError ) - { - LOGGER.error( "Exception which failed assertions: ", e ); + } catch (AssertionError assertionError) { + LOGGER.error("Exception which failed assertions: ", e); throw assertionError; } - } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/GetWagonTests.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/GetWagonTests.java index ac48636bd..688c16a7d 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/GetWagonTests.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/GetWagonTests.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http; + +import javax.servlet.Servlet; +import javax.servlet.http.HttpServletResponse; + +import java.io.File; +import java.io.IOException; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.ResourceDoesNotExistException; @@ -38,11 +43,6 @@ import org.junit.Ignore; import org.junit.Test; -import javax.servlet.Servlet; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; - import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.apache.maven.wagon.tck.http.Assertions.NO_RESPONSE_STATUS_CODE; @@ -50,258 +50,224 @@ import static org.apache.maven.wagon.tck.http.Assertions.assertWagonExceptionMessage; /** - * + * */ -public class GetWagonTests - extends HttpWagonTests -{ +public class GetWagonTests extends HttpWagonTests { private static final int TWO_SECONDS = 2000; private static final int ONE_MINUTE = 60000; @Test public void basic() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - testSuccessfulGet( "base.txt" ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + testSuccessfulGet("base.txt"); } @Test - @Ignore( "FIX ME!" ) + @Ignore("FIX ME!") public void proxied() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - getServerFixture().addFilter( "*", new ProxyConnectionVerifierFilter() ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + getServerFixture().addFilter("*", new ProxyConnectionVerifierFilter()); ProxyInfo info = newProxyInfo(); - if ( !initTest( null, info ) ) - { + if (!initTest(null, info)) { return; } File target = newTempFile(); - getWagon().get( "base.txt", target ); + getWagon().get("base.txt", target); - assertFileContentsFromResource( ServerFixture.SERVER_ROOT_RESOURCE_PATH, "base.txt", target, - "Downloaded file doesn't match original." ); + assertFileContentsFromResource( + ServerFixture.SERVER_ROOT_RESOURCE_PATH, "base.txt", target, "Downloaded file doesn't match original."); } @Test public void highLatencyHighTimeout() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - getServerFixture().addServlet( "/slow/*", new LatencyServlet( TWO_SECONDS ) ); - testSuccessfulGet( "slow/large.txt", "large.txt" ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + getServerFixture().addServlet("/slow/*", new LatencyServlet(TWO_SECONDS)); + testSuccessfulGet("slow/large.txt", "large.txt"); } @Test public void highLatencyLowTimeout() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Servlet servlet = new LatencyServlet( TWO_SECONDS ); - getServerFixture().addServlet( "/slow/*", servlet ); - testSuccessfulGet( "slow/large.txt", "large.txt" ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Servlet servlet = new LatencyServlet(TWO_SECONDS); + getServerFixture().addServlet("/slow/*", servlet); + testSuccessfulGet("slow/large.txt", "large.txt"); } @Test public void inifiniteLatencyTimeout() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( !isSupported() ) - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (!isSupported()) { return; } - final ValueHolder holder = new ValueHolder<>( null ); + final ValueHolder holder = new ValueHolder<>(null); - Runnable r = new Runnable() - { - public void run() - { - Servlet servlet = new LatencyServlet( -1 ); - addNotificationTarget( servlet ); + Runnable r = new Runnable() { + public void run() { + Servlet servlet = new LatencyServlet(-1); + addNotificationTarget(servlet); - getServerFixture().addServlet( "/infinite/*", servlet ); - try - { - if ( !initTest( null, null ) ) - { + getServerFixture().addServlet("/infinite/*", servlet); + try { + if (!initTest(null, null)) { return; } - if ( getWagon() instanceof StreamWagon ) - { - logger.info( "Connection timeout is: " + getWagon().getTimeout() ); + if (getWagon() instanceof StreamWagon) { + logger.info("Connection timeout is: " + getWagon().getTimeout()); } File target = newTempFile(); - getWagon().get( "infinite/", target ); - - fail( "Should have failed to transfer due to transaction timeout." ); - } - catch ( ConnectionException | AuthenticationException | ResourceDoesNotExistException - | AuthorizationException | ComponentConfigurationException | IOException e ) - { - throw new IllegalStateException( e ); - } - catch ( TransferFailedException e ) - { + getWagon().get("infinite/", target); + + fail("Should have failed to transfer due to transaction timeout."); + } catch (ConnectionException + | AuthenticationException + | ResourceDoesNotExistException + | AuthorizationException + | ComponentConfigurationException + | IOException e) { + throw new IllegalStateException(e); + } catch (TransferFailedException e) { // expected - holder.setValue( e ); + holder.setValue(e); } } }; - Thread t = new Thread( r ); + Thread t = new Thread(r); t.start(); - try - { - logger.info( "Waiting 60 seconds for wagon timeout." ); - t.join( ONE_MINUTE ); - } - catch ( InterruptedException e ) - { + try { + logger.info("Waiting 60 seconds for wagon timeout."); + t.join(ONE_MINUTE); + } catch (InterruptedException e) { e.printStackTrace(); } - logger.info( "Interrupting thread." ); + logger.info("Interrupting thread."); t.interrupt(); - assertTrue( "TransferFailedException should have been thrown.", holder.getValue() != null ); - assertWagonExceptionMessage( holder.getValue(), NO_RESPONSE_STATUS_CODE, getBaseUrl() + "infinite/", - "", null ); + assertTrue("TransferFailedException should have been thrown.", holder.getValue() != null); + assertWagonExceptionMessage(holder.getValue(), NO_RESPONSE_STATUS_CODE, getBaseUrl() + "infinite/", "", null); } @Test public void nonExistentHost() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + ResourceDoesNotExistException, AuthorizationException { // we use a invalid localhost URL since some Internet Service Providers lately // use funny 'search-DNS' which don't handle explicitly marked testing DNS properly. // According to RFC-2606 .test, .invalid TLDs etc should work, but in practice it doesn't :( - if ( !initTest( "http://localhost:65520", null, null ) ) - { + if (!initTest("http://localhost:65520", null, null)) { return; } File target = newTempFile(); - try - { - getWagon().get( "base.txt", target ); - fail( "Expected error related to host lookup failure." ); - } - catch ( TransferFailedException e ) - { + try { + getWagon().get("base.txt", target); + fail("Expected error related to host lookup failure."); + } catch (TransferFailedException e) { // expected - assertWagonExceptionMessage( e, NO_RESPONSE_STATUS_CODE, "http://localhost:65520/base.txt", - null, null ); + assertWagonExceptionMessage(e, NO_RESPONSE_STATUS_CODE, "http://localhost:65520/base.txt", null, null); } } @Test public void oneLevelPermanentMove() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - getServerFixture().addServlet( "/moved.txt", - new RedirectionServlet( HttpServletResponse.SC_MOVED_PERMANENTLY, - "/base.txt" ) ); - - testSuccessfulGet( "moved.txt" ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + getServerFixture() + .addServlet( + "/moved.txt", new RedirectionServlet(HttpServletResponse.SC_MOVED_PERMANENTLY, "/base.txt")); + + testSuccessfulGet("moved.txt"); } @Test public void oneLevelTemporaryMove() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - getServerFixture().addServlet( "/moved.txt", - new RedirectionServlet( HttpServletResponse.SC_MOVED_TEMPORARILY, - "/base.txt" ) ); - - testSuccessfulGet( "moved.txt" ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + getServerFixture() + .addServlet( + "/moved.txt", new RedirectionServlet(HttpServletResponse.SC_MOVED_TEMPORARILY, "/base.txt")); + + testSuccessfulGet("moved.txt"); } @Test public void sixLevelPermanentMove() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { String myPath = "moved.txt"; String targetPath = "/base.txt"; - getServerFixture().addServlet( "/" + myPath + "/*", - new RedirectionServlet( HttpServletResponse.SC_MOVED_PERMANENTLY, myPath, - targetPath, 6 ) ); + getServerFixture() + .addServlet( + "/" + myPath + "/*", + new RedirectionServlet(HttpServletResponse.SC_MOVED_PERMANENTLY, myPath, targetPath, 6)); - testSuccessfulGet( myPath ); + testSuccessfulGet(myPath); } @Test public void sixLevelTemporaryMove() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { String myPath = "moved.txt"; String targetPath = "/base.txt"; - getServerFixture().addServlet( "/" + myPath + "/*", - new RedirectionServlet( HttpServletResponse.SC_MOVED_TEMPORARILY, myPath, - targetPath, 6 ) ); + getServerFixture() + .addServlet( + "/" + myPath + "/*", + new RedirectionServlet(HttpServletResponse.SC_MOVED_TEMPORARILY, myPath, targetPath, 6)); - testSuccessfulGet( myPath ); + testSuccessfulGet(myPath); } @Test public void infinitePermanentMove() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { String myPath = "moved.txt"; String targetPath = "/base.txt"; - getServerFixture().addServlet( - "/" + myPath, - new RedirectionServlet( HttpServletResponse.SC_MOVED_PERMANENTLY, myPath, - targetPath, -1 ) ); + getServerFixture() + .addServlet( + "/" + myPath, + new RedirectionServlet(HttpServletResponse.SC_MOVED_PERMANENTLY, myPath, targetPath, -1)); - try - { - testSuccessfulGet( myPath ); - fail( "Expected failure as a result of too many redirects." ); - } - catch ( TransferFailedException e ) - { + try { + testSuccessfulGet(myPath); + fail("Expected failure as a result of too many redirects."); + } catch (TransferFailedException e) { // expected } } @Test public void infiniteTemporaryMove() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + ResourceDoesNotExistException, AuthorizationException { String myPath = "moved.txt"; String targetPath = "/base.txt"; - getServerFixture().addServlet( - "/" + myPath, - new RedirectionServlet( HttpServletResponse.SC_MOVED_TEMPORARILY, myPath, - targetPath, -1 ) ); + getServerFixture() + .addServlet( + "/" + myPath, + new RedirectionServlet(HttpServletResponse.SC_MOVED_TEMPORARILY, myPath, targetPath, -1)); - try - { - testSuccessfulGet( myPath ); - fail( "Expected failure as a result of too many redirects." ); - } - catch ( TransferFailedException e ) - { + try { + testSuccessfulGet(myPath); + fail("Expected failure as a result of too many redirects."); + } catch (TransferFailedException e) { // expected } } @@ -311,26 +277,22 @@ public void infiniteTemporaryMove() * case of the Sun HTTP implementation, this is the default limit. */ @Test - @SuppressWarnings( "checkstyle:methodname" ) + @SuppressWarnings("checkstyle:methodname") public void permanentMove_TooManyRedirects_limit20() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { String myPath = "moved.txt"; String targetPath = "/base.txt"; - getServerFixture().addServlet( - "/" + myPath, - new RedirectionServlet( HttpServletResponse.SC_MOVED_PERMANENTLY, myPath, - targetPath, -1 ) ); + getServerFixture() + .addServlet( + "/" + myPath, + new RedirectionServlet(HttpServletResponse.SC_MOVED_PERMANENTLY, myPath, targetPath, -1)); - try - { - testSuccessfulGet( myPath ); - fail( "Expected failure as a result of too many redirects." ); - } - catch ( TransferFailedException e ) - { + try { + testSuccessfulGet(myPath); + fail("Expected failure as a result of too many redirects."); + } catch (TransferFailedException e) { // expected } } @@ -340,208 +302,173 @@ public void permanentMove_TooManyRedirects_limit20() * case of the Sun HTTP implementation, this is the default limit. */ @Test - @SuppressWarnings( "checkstyle:methodname" ) + @SuppressWarnings("checkstyle:methodname") public void temporaryMove_TooManyRedirects_limit20() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + ResourceDoesNotExistException, AuthorizationException { String myPath = "moved.txt"; String targetPath = "/base.txt"; - getServerFixture().addServlet( - "/" + myPath, - new RedirectionServlet( HttpServletResponse.SC_MOVED_TEMPORARILY, myPath, - targetPath, -1 ) ); + getServerFixture() + .addServlet( + "/" + myPath, + new RedirectionServlet(HttpServletResponse.SC_MOVED_TEMPORARILY, myPath, targetPath, -1)); - try - { - testSuccessfulGet( myPath ); - fail( "Expected failure as a result of too many redirects." ); - } - catch ( TransferFailedException e ) - { + try { + testSuccessfulGet(myPath); + fail("Expected failure as a result of too many redirects."); + } catch (TransferFailedException e) { // expected } } @Test public void missing() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, AuthorizationException - { - if ( !initTest( null, null ) ) - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, AuthorizationException { + if (!initTest(null, null)) { return; } File target = newTempFile(); - try - { - getWagon().get( "404.txt", target ); - fail( "should have received a 404, meaning the resource doesn't exist." ); - } - catch ( ResourceDoesNotExistException e ) - { + try { + getWagon().get("404.txt", target); + fail("should have received a 404, meaning the resource doesn't exist."); + } catch (ResourceDoesNotExistException e) { // expected } } @Test public void error() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - AuthorizationException, ResourceDoesNotExistException - { - testErrorHandling( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + AuthorizationException, ResourceDoesNotExistException { + testErrorHandling(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void proxyTimeout() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - AuthorizationException, ResourceDoesNotExistException - { - testErrorHandling( HttpServletResponse.SC_GATEWAY_TIMEOUT ); + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + AuthorizationException, ResourceDoesNotExistException { + testErrorHandling(HttpServletResponse.SC_GATEWAY_TIMEOUT); } @Test public void forbidden() - throws ConnectionException, ComponentConfigurationException, IOException, ResourceDoesNotExistException, - TransferFailedException - { + throws ConnectionException, ComponentConfigurationException, IOException, ResourceDoesNotExistException, + TransferFailedException { AuthenticationInfo info = new AuthenticationInfo(); - info.setUserName( "user" ); - info.setPassword( "password" ); + info.setUserName("user"); + info.setPassword("password"); - getServerFixture().addUser( info.getUserName(), "password" ); + getServerFixture().addUser(info.getUserName(), "password"); - getServerFixture().addServlet( "/403.txt", - new ErrorCodeServlet( HttpServletResponse.SC_FORBIDDEN, "Expected 403" ) ); + getServerFixture() + .addServlet("/403.txt", new ErrorCodeServlet(HttpServletResponse.SC_FORBIDDEN, "Expected 403")); - testAuthFailure( "403.txt", info ); + testAuthFailure("403.txt", info); } @Test public void successfulAuthentication() - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { AuthenticationInfo info = new AuthenticationInfo(); - info.setUserName( "user" ); - info.setPassword( "password" ); + info.setUserName("user"); + info.setPassword("password"); - getServerFixture().addUser( info.getUserName(), info.getPassword() ); + getServerFixture().addUser(info.getUserName(), info.getPassword()); - if ( !initTest( info, null ) ) - { + if (!initTest(info, null)) { return; } File target = newTempFile(); - getWagon().get( "protected/base.txt", target ); + getWagon().get("protected/base.txt", target); - assertFileContentsFromResource( ServerFixture.SERVER_ROOT_RESOURCE_PATH, "base.txt", target, - "Downloaded file doesn't match original." ); + assertFileContentsFromResource( + ServerFixture.SERVER_ROOT_RESOURCE_PATH, "base.txt", target, "Downloaded file doesn't match original."); } @Test public void unsuccessfulAuthentication() - throws ConnectionException, ComponentConfigurationException, IOException, TransferFailedException, - ResourceDoesNotExistException - { + throws ConnectionException, ComponentConfigurationException, IOException, TransferFailedException, + ResourceDoesNotExistException { AuthenticationInfo info = new AuthenticationInfo(); - info.setUserName( "user" ); - info.setPassword( "password" ); + info.setUserName("user"); + info.setPassword("password"); - getServerFixture().addUser( info.getUserName(), "anotherPassword" ); + getServerFixture().addUser(info.getUserName(), "anotherPassword"); - testAuthFailure( "protected/base.txt", info ); + testAuthFailure("protected/base.txt", info); } - protected void testAuthFailure( final String path, final AuthenticationInfo info ) - throws ConnectionException, ComponentConfigurationException, IOException, TransferFailedException, - ResourceDoesNotExistException - { + protected void testAuthFailure(final String path, final AuthenticationInfo info) + throws ConnectionException, ComponentConfigurationException, IOException, TransferFailedException, + ResourceDoesNotExistException { boolean authFailure = false; - try - { - if ( !initTest( info, null ) ) - { + try { + if (!initTest(info, null)) { return; } - } - catch ( AuthenticationException e ) - { + } catch (AuthenticationException e) { // expected authFailure = true; } File target = newTempFile(); - try - { - getWagon().get( path, target ); - } - catch ( AuthorizationException e ) - { + try { + getWagon().get(path, target); + } catch (AuthorizationException e) { // expected authFailure = true; } - assertTrue( "Authentication/Authorization should have failed.", authFailure ); + assertTrue("Authentication/Authorization should have failed.", authFailure); } - protected void testSuccessfulGet( final String path ) - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - testSuccessfulGet( path, "base.txt" ); + protected void testSuccessfulGet(final String path) + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + testSuccessfulGet(path, "base.txt"); } - protected void testSuccessfulGet( final String path, final String checkPath ) - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - if ( !initTest( null, null ) ) - { + protected void testSuccessfulGet(final String path, final String checkPath) + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (!initTest(null, null)) { return; } - if ( getWagon() instanceof StreamWagon ) - { - logger.info( "Connection timeout is: " + getWagon().getTimeout() ); + if (getWagon() instanceof StreamWagon) { + logger.info("Connection timeout is: " + getWagon().getTimeout()); } File target = newTempFile(); - getWagon().get( path, target ); + getWagon().get(path, target); - assertFileContentsFromResource( ServerFixture.SERVER_ROOT_RESOURCE_PATH, checkPath, target, - "Downloaded file doesn't match original." ); + assertFileContentsFromResource( + ServerFixture.SERVER_ROOT_RESOURCE_PATH, checkPath, target, "Downloaded file doesn't match original."); } - protected void testErrorHandling( final int code ) - throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, - AuthorizationException, ResourceDoesNotExistException - { - if ( code == HttpServletResponse.SC_INTERNAL_SERVER_ERROR ) - { - getServerFixture().addServlet( "/" + code + ".txt", new ServletExceptionServlet( "Expected " + code ) ); - } - else - { - getServerFixture().addServlet( "/" + code + ".txt", new ErrorCodeServlet( code, "Expected " + code ) ); + protected void testErrorHandling(final int code) + throws ConnectionException, AuthenticationException, ComponentConfigurationException, IOException, + AuthorizationException, ResourceDoesNotExistException { + if (code == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { + getServerFixture().addServlet("/" + code + ".txt", new ServletExceptionServlet("Expected " + code)); + } else { + getServerFixture().addServlet("/" + code + ".txt", new ErrorCodeServlet(code, "Expected " + code)); } - if ( !initTest( null, null ) ) - { + if (!initTest(null, null)) { return; } File target = newTempFile(); - try - { - getWagon().get( code + ".txt", target ); - fail( "should have received a " + code + " error code, meaning the resource doesn't exist." ); - } - catch ( TransferFailedException e ) - { + try { + getWagon().get(code + ".txt", target); + fail("should have received a " + code + " error code, meaning the resource doesn't exist."); + } catch (TransferFailedException e) { // expected } } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpWagonTests.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpWagonTests.java index b1e443550..8fcbd25c0 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpWagonTests.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpWagonTests.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http; import java.io.File; import java.io.IOException; @@ -40,16 +39,15 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; -import static org.apache.maven.wagon.tck.http.util.TestUtil.getResource; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.apache.maven.wagon.tck.http.util.TestUtil.getResource; + /** - * + * */ -public abstract class HttpWagonTests -{ +public abstract class HttpWagonTests { private ServerFixture serverFixture; @@ -68,104 +66,77 @@ public abstract class HttpWagonTests private final Set notificationTargets = new HashSet<>(); // CHECKSTYLE_OFF: ConstantName - protected static final Logger logger = LoggerFactory.getLogger( HttpWagonTests.class ); + protected static final Logger logger = LoggerFactory.getLogger(HttpWagonTests.class); // CHECKSTYLE_ON: ConstantName @Before - public void beforeEach() - throws Exception - { - serverFixture = new ServerFixture( isSsl() ); + public void beforeEach() throws Exception { + serverFixture = new ServerFixture(isSsl()); serverFixture.start(); - wagon = (Wagon) container.lookup( Wagon.ROLE, configurator.getWagonHint() ); + wagon = (Wagon) container.lookup(Wagon.ROLE, configurator.getWagonHint()); } @BeforeClass - public static void beforeAll() - throws Exception - { - File keystore = getResource( ServerFixture.SERVER_SSL_KEYSTORE_RESOURCE_PATH ); + public static void beforeAll() throws Exception { + File keystore = getResource(ServerFixture.SERVER_SSL_KEYSTORE_RESOURCE_PATH); - System.setProperty( "javax.net.ssl.keyStore", keystore.getAbsolutePath() ); - System.setProperty( "javax.net.ssl.keyStorePassword", ServerFixture.SERVER_SSL_KEYSTORE_PASSWORD ); - System.setProperty( "javax.net.ssl.trustStore", keystore.getAbsolutePath() ); - System.setProperty( "javax.net.ssl.trustStorePassword", ServerFixture.SERVER_SSL_KEYSTORE_PASSWORD ); + System.setProperty("javax.net.ssl.keyStore", keystore.getAbsolutePath()); + System.setProperty("javax.net.ssl.keyStorePassword", ServerFixture.SERVER_SSL_KEYSTORE_PASSWORD); + System.setProperty("javax.net.ssl.trustStore", keystore.getAbsolutePath()); + System.setProperty("javax.net.ssl.trustStorePassword", ServerFixture.SERVER_SSL_KEYSTORE_PASSWORD); container = new DefaultPlexusContainer(); - //container.initialize(); - //container.start(); + // container.initialize(); + // container.start(); - configurator = (WagonTestCaseConfigurator) container.lookup( WagonTestCaseConfigurator.class.getName() ); + configurator = (WagonTestCaseConfigurator) container.lookup(WagonTestCaseConfigurator.class.getName()); } @After - public void afterEach() - { - try - { + public void afterEach() { + try { wagon.disconnect(); - } - catch ( ConnectionException e ) - { + } catch (ConnectionException e) { e.printStackTrace(); } - for ( Object obj : notificationTargets ) - { - synchronized ( obj ) - { + for (Object obj : notificationTargets) { + synchronized (obj) { obj.notify(); } } - if ( serverFixture != null ) - { - try - { + if (serverFixture != null) { + try { serverFixture.stop(); - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); } } - try - { - container.release( wagon ); - } - catch ( ComponentLifecycleException e ) - { + try { + container.release(wagon); + } catch (ComponentLifecycleException e) { e.printStackTrace(); } } @AfterClass - public static void afterAll() - { - for ( File f : TMP_FILES ) - { - if ( f.exists() ) - { - try - { - FileUtils.forceDelete( f ); - } - catch ( IOException e ) - { + public static void afterAll() { + for (File f : TMP_FILES) { + if (f.exists()) { + try { + FileUtils.forceDelete(f); + } catch (IOException e) { e.printStackTrace(); } } } - if ( container != null ) - { - try - { - container.release( configurator ); - } - catch ( ComponentLifecycleException e ) - { + if (container != null) { + try { + container.release(configurator); + } catch (ComponentLifecycleException e) { e.printStackTrace(); } @@ -173,130 +144,103 @@ public static void afterAll() } } - protected void addNotificationTarget( final Object target ) - { - notificationTargets.add( target ); + protected void addNotificationTarget(final Object target) { + notificationTargets.add(target); } - protected File newTempFile() - throws IOException - { - File f = File.createTempFile( "wagon-target.", ".file" ); + protected File newTempFile() throws IOException { + File f = File.createTempFile("wagon-target.", ".file"); f.deleteOnExit(); return f; } - protected boolean isSsl() - { + protected boolean isSsl() { return false; } - protected ProxyInfo newProxyInfo() - { + protected ProxyInfo newProxyInfo() { ProxyInfo info = new ProxyInfo(); - info.setType( isSsl() ? "https" : "http" ); - info.setHost( ServerFixture.SERVER_HOST ); - info.setPort( getPort() ); + info.setType(isSsl() ? "https" : "http"); + info.setHost(ServerFixture.SERVER_HOST); + info.setPort(getPort()); return info; } - protected boolean isSupported() - { + protected boolean isSupported() { StackTraceElement[] elements = new Throwable().getStackTrace(); String testCaseId = null; String lastMethodName = null; - for ( StackTraceElement e : elements ) - { - if ( !e.getClassName().startsWith( getClass().getPackage().getName() ) ) - { + for (StackTraceElement e : elements) { + if (!e.getClassName().startsWith(getClass().getPackage().getName())) { testCaseId = lastMethodName; break; - } - else - { + } else { lastMethodName = e.getMethodName(); } } - if ( testCaseId == null || !configurator.isSupported( testCaseId ) ) - { - logger.error( "Cannot run test: " + testCaseId - + ". Wagon under test does not support this test case." ); + if (testCaseId == null || !configurator.isSupported(testCaseId)) { + logger.error("Cannot run test: " + testCaseId + ". Wagon under test does not support this test case."); return false; } return true; } - protected boolean initTest( final AuthenticationInfo auth, final ProxyInfo proxy ) - throws ComponentConfigurationException, ConnectionException, AuthenticationException - { - return initTest( getBaseUrl(), auth, proxy ); + protected boolean initTest(final AuthenticationInfo auth, final ProxyInfo proxy) + throws ComponentConfigurationException, ConnectionException, AuthenticationException { + return initTest(getBaseUrl(), auth, proxy); } - protected boolean initTest( final String baseUrl, final AuthenticationInfo auth, final ProxyInfo proxy ) - throws ComponentConfigurationException, ConnectionException, AuthenticationException - { + protected boolean initTest(final String baseUrl, final AuthenticationInfo auth, final ProxyInfo proxy) + throws ComponentConfigurationException, ConnectionException, AuthenticationException { StackTraceElement[] elements = new Throwable().getStackTrace(); String testCaseId = null; String lastMethodName = null; - for ( StackTraceElement e : elements ) - { - if ( !e.getClassName().startsWith( getClass().getPackage().getName() ) ) - { + for (StackTraceElement e : elements) { + if (!e.getClassName().startsWith(getClass().getPackage().getName())) { testCaseId = lastMethodName; break; - } - else - { + } else { lastMethodName = e.getMethodName(); } } - if ( testCaseId == null || !configurator.configureWagonForTest( wagon, testCaseId ) ) - { - logger.error( "Cannot run test: " + testCaseId - + ". Wagon under test does not support this test case." ); + if (testCaseId == null || !configurator.configureWagonForTest(wagon, testCaseId)) { + logger.error("Cannot run test: " + testCaseId + ". Wagon under test does not support this test case."); return false; } - try - { + try { serverFixture.start(); - } - catch ( Exception e ) - { - throw new IllegalStateException( "Failed to start: " + e.getMessage(), e ); + } catch (Exception e) { + throw new IllegalStateException("Failed to start: " + e.getMessage(), e); } - repo = new Repository( "test", baseUrl ); + repo = new Repository("test", baseUrl); - wagon.connect( repo, auth, proxy ); + wagon.connect(repo, auth, proxy); return true; } - protected int getPort() - { + protected int getPort() { return serverFixture.getHttpPort(); } - protected int getPortPropertyValue() - { - return Integer.parseInt( System.getProperty( "test.port", "-1" ) ); + protected int getPortPropertyValue() { + return Integer.parseInt(System.getProperty("test.port", "-1")); } - protected String getBaseUrl() - { - if ( baseUrl == null ) - { + protected String getBaseUrl() { + if (baseUrl == null) { StringBuilder sb = new StringBuilder(); - sb.append( isSsl() ? "https" : "http" ); - sb.append( "://" + ServerFixture.SERVER_HOST + ":" ); - sb.append( getPort() ); + sb.append(isSsl() ? "https" : "http"); + sb.append("://" + ServerFixture.SERVER_HOST + ":"); + sb.append(getPort()); baseUrl = sb.toString(); } @@ -304,34 +248,27 @@ protected String getBaseUrl() return baseUrl; } - protected ServerFixture getServerFixture() - { + protected ServerFixture getServerFixture() { return serverFixture; } - protected static PlexusContainer getContainer() - { + protected static PlexusContainer getContainer() { return container; } - protected Wagon getWagon() - { + protected Wagon getWagon() { return wagon; } - protected static WagonTestCaseConfigurator getConfigurator() - { + protected static WagonTestCaseConfigurator getConfigurator() { return configurator; } - protected static Set getTmpfiles() - { + protected static Set getTmpfiles() { return TMP_FILES; } - protected Repository getRepo() - { + protected Repository getRepo() { return repo; } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpsGetWagonTests.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpsGetWagonTests.java index 5fa14ee05..35e5d84e1 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpsGetWagonTests.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/HttpsGetWagonTests.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http; /** - * + * */ -public class HttpsGetWagonTests - extends GetWagonTests -{ +public class HttpsGetWagonTests extends GetWagonTests { @Override - protected boolean isSsl() - { + protected boolean isSsl() { return true; } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/WagonTestCaseConfigurator.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/WagonTestCaseConfigurator.java index 8d154cb02..190c9ba79 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/WagonTestCaseConfigurator.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/WagonTestCaseConfigurator.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http; import org.apache.maven.wagon.Wagon; import org.codehaus.plexus.PlexusConstants; @@ -30,16 +29,13 @@ import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ -public class WagonTestCaseConfigurator - implements Contextualizable -{ +public class WagonTestCaseConfigurator implements Contextualizable { private static final String UNSUPPORTED_ELEMENT = "unsupported"; private PlexusConfiguration useCaseConfigs; @@ -50,17 +46,14 @@ public class WagonTestCaseConfigurator private String wagonHint; - private static Logger logger = LoggerFactory.getLogger( WagonTestCaseConfigurator.class ); + private static Logger logger = LoggerFactory.getLogger(WagonTestCaseConfigurator.class); - public boolean isSupported( final String useCaseId ) - { - if ( useCaseConfigs != null ) - { - PlexusConfiguration config = useCaseConfigs.getChild( useCaseId, false ); + public boolean isSupported(final String useCaseId) { + if (useCaseConfigs != null) { + PlexusConfiguration config = useCaseConfigs.getChild(useCaseId, false); - if ( config != null && config.getChild( UNSUPPORTED_ELEMENT, false ) != null ) - { - logger.info( "Test case '" + useCaseId + "' is marked as unsupported by this wagon." ); + if (config != null && config.getChild(UNSUPPORTED_ELEMENT, false) != null) { + logger.info("Test case '" + useCaseId + "' is marked as unsupported by this wagon."); return false; } } @@ -68,72 +61,52 @@ public boolean isSupported( final String useCaseId ) return true; } - public boolean configureWagonForTest( final Wagon wagon, final String useCaseId ) - throws ComponentConfigurationException - { - if ( useCaseConfigs != null ) - { - PlexusConfiguration config = useCaseConfigs.getChild( useCaseId, false ); - - if ( config != null ) - { - if ( config.getChild( UNSUPPORTED_ELEMENT, false ) != null ) - { - logger.error( "Test case '" + useCaseId + "' is marked as unsupported by this wagon." ); + public boolean configureWagonForTest(final Wagon wagon, final String useCaseId) + throws ComponentConfigurationException { + if (useCaseConfigs != null) { + PlexusConfiguration config = useCaseConfigs.getChild(useCaseId, false); + + if (config != null) { + if (config.getChild(UNSUPPORTED_ELEMENT, false) != null) { + logger.error("Test case '" + useCaseId + "' is marked as unsupported by this wagon."); return false; + } else { + logger.info("Configuring wagon for test case: " + useCaseId + " with:\n\n" + config); + configurator.configureComponent(wagon, useCaseConfigs.getChild(useCaseId, false), realm); } - else - { - logger.info( "Configuring wagon for test case: " + useCaseId + " with:\n\n" + config ); - configurator.configureComponent( wagon, useCaseConfigs.getChild( useCaseId, false ), realm ); - } - } - else - { - logger.info( "No wagon configuration found for test case: " + useCaseId ); + } else { + logger.info("No wagon configuration found for test case: " + useCaseId); } - } - else - { - logger.info( "No test case configurations found." ); + } else { + logger.info("No test case configurations found."); } return true; } - public void contextualize( final Context context ) - throws ContextException - { - PlexusContainer container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); + public void contextualize(final Context context) throws ContextException { + PlexusContainer container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); this.realm = container.getContainerRealm(); - try - { - configurator = (ComponentConfigurator) container.lookup( ComponentConfigurator.ROLE ); - } - catch ( ComponentLookupException e ) - { - throw new ContextException( "Failed to lookup component configurator: " + e.getMessage(), e ); + try { + configurator = (ComponentConfigurator) container.lookup(ComponentConfigurator.ROLE); + } catch (ComponentLookupException e) { + throw new ContextException("Failed to lookup component configurator: " + e.getMessage(), e); } } - public PlexusConfiguration getUseCaseConfigs() - { + public PlexusConfiguration getUseCaseConfigs() { return useCaseConfigs; } - public void setUseCaseConfigs( final PlexusConfiguration useCaseConfigs ) - { + public void setUseCaseConfigs(final PlexusConfiguration useCaseConfigs) { this.useCaseConfigs = useCaseConfigs; } - public String getWagonHint() - { + public String getWagonHint() { return wagonHint; } - public void setWagonHint( final String wagonHint ) - { + public void setWagonHint(final String wagonHint) { this.wagonHint = wagonHint; } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/AuthSnoopFilter.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/AuthSnoopFilter.java index 79110aab3..efe8d6b16 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/AuthSnoopFilter.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/AuthSnoopFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import java.io.IOException; -import java.nio.charset.StandardCharsets; +package org.apache.maven.wagon.tck.http.fixture; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -30,6 +26,9 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + import org.codehaus.plexus.util.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,36 +36,26 @@ /** * */ -public class AuthSnoopFilter - implements Filter -{ - private static Logger logger = LoggerFactory.getLogger( AuthSnoopFilter.class ); +public class AuthSnoopFilter implements Filter { + private static Logger logger = LoggerFactory.getLogger(AuthSnoopFilter.class); - public void destroy() - { - } + public void destroy() {} - public void doFilter( final ServletRequest req, final ServletResponse response, final FilterChain chain ) - throws IOException, ServletException - { + public void doFilter(final ServletRequest req, final ServletResponse response, final FilterChain chain) + throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; - String authHeader = request.getHeader( "Authorization" ); + String authHeader = request.getHeader("Authorization"); - if ( authHeader != null ) - { - logger.info( "Authorization: " + authHeader ); - String data = authHeader.substring( "BASIC ".length() ); - String decoded = new String( Base64.decodeBase64( data.getBytes( StandardCharsets.US_ASCII ) ) ); - logger.info( decoded ); - String[] creds = decoded.split( ":" ); + if (authHeader != null) { + logger.info("Authorization: " + authHeader); + String data = authHeader.substring("BASIC ".length()); + String decoded = new String(Base64.decodeBase64(data.getBytes(StandardCharsets.US_ASCII))); + logger.info(decoded); + String[] creds = decoded.split(":"); - logger.info( "User: " + creds[0] + "\nPassword: " + creds[1] ); + logger.info("User: " + creds[0] + "\nPassword: " + creds[1]); } } - public void init( final FilterConfig filterConfig ) - throws ServletException - { - } - + public void init(final FilterConfig filterConfig) throws ServletException {} } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ErrorCodeServlet.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ErrorCodeServlet.java index 7055c1d50..110fb5888 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ErrorCodeServlet.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ErrorCodeServlet.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,20 +16,19 @@ * specific language governing permissions and limitations * under the License. */ - -import java.io.IOException; +package org.apache.maven.wagon.tck.http.fixture; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + /** - * + * */ -public class ErrorCodeServlet - extends HttpServlet -{ +public class ErrorCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; @@ -39,17 +36,14 @@ public class ErrorCodeServlet private final String message; - public ErrorCodeServlet( final int code, final String message ) - { + public ErrorCodeServlet(final int code, final String message) { this.code = code; this.message = message; } @Override - protected void service( final HttpServletRequest req, final HttpServletResponse resp ) - throws ServletException, IOException - { - resp.sendError( code, message ); + protected void service(final HttpServletRequest req, final HttpServletResponse resp) + throws ServletException, IOException { + resp.sendError(code, message); } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/LatencyServlet.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/LatencyServlet.java index 1760a75fa..28f58c6ca 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/LatencyServlet.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/LatencyServlet.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,29 +16,27 @@ * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; +package org.apache.maven.wagon.tck.http.fixture; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.codehaus.plexus.util.IOUtil; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; +import org.codehaus.plexus.util.IOUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ -public class LatencyServlet - extends HttpServlet -{ - private static Logger logger = LoggerFactory.getLogger( LatencyServlet.class ); +public class LatencyServlet extends HttpServlet { + private static Logger logger = LoggerFactory.getLogger(LatencyServlet.class); private static final long serialVersionUID = 1L; @@ -48,26 +44,19 @@ public class LatencyServlet private final int latencyMs; - public LatencyServlet( final int latencyMs ) - { + public LatencyServlet(final int latencyMs) { this.latencyMs = latencyMs; } @Override - protected void doGet( final HttpServletRequest req, final HttpServletResponse resp ) - throws ServletException, IOException - { - if ( latencyMs < 0 ) - { - logger.info( "Starting infinite wait." ); - synchronized ( this ) - { - try - { + protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) + throws ServletException, IOException { + if (latencyMs < 0) { + logger.info("Starting infinite wait."); + synchronized (this) { + try { wait(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // ignore } } @@ -79,50 +68,42 @@ protected void doGet( final HttpServletRequest req, final HttpServletResponse re // ignore the servlet's path here, since the servlet path is really only to provide a // binding for the servlet. - String realPath = getServletContext().getRealPath( path ); - File f = new File( realPath ); + String realPath = getServletContext().getRealPath(path); + File f = new File(realPath); FileInputStream in = null; long total = 0; long start = System.currentTimeMillis(); - try - { - in = new FileInputStream( f ); + try { + in = new FileInputStream(f); OutputStream out = resp.getOutputStream(); - logger.info( "Starting high-latency transfer. This should take about " - + ( ( f.length() / BUFFER_SIZE * latencyMs / 1000 ) + ( latencyMs / 1000 ) ) + " seconds." ); + logger.info("Starting high-latency transfer. This should take about " + + ((f.length() / BUFFER_SIZE * latencyMs / 1000) + (latencyMs / 1000)) + " seconds."); int read; byte[] buf = new byte[BUFFER_SIZE]; - while ( ( read = in.read( buf ) ) > -1 ) - { - try - { - Thread.sleep( latencyMs ); - } - catch ( InterruptedException e ) - { + while ((read = in.read(buf)) > -1) { + try { + Thread.sleep(latencyMs); + } catch (InterruptedException e) { e.printStackTrace(); } - logger.info( "Writing bytes " + total + "-" + ( total + read - 1 ) + " of " + f.length() - + ". Elapsed time so far: " + ( ( System.currentTimeMillis() - start ) / 1000 ) + " seconds" ); + logger.info("Writing bytes " + total + "-" + (total + read - 1) + " of " + f.length() + + ". Elapsed time so far: " + ((System.currentTimeMillis() - start) / 1000) + " seconds"); - out.write( buf, 0, read ); + out.write(buf, 0, read); total += read; } in.close(); in = null; - } - finally - { - IOUtil.close( in ); + } finally { + IOUtil.close(in); } - logger.info( "High-latency transfer done in " + ( System.currentTimeMillis() - start ) + "ms" ); + logger.info("High-latency transfer done in " + (System.currentTimeMillis() - start) + "ms"); } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyAuthenticationFilter.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyAuthenticationFilter.java index c851fee5a..a34b6ef88 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyAuthenticationFilter.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyAuthenticationFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import java.io.IOException; -import java.nio.charset.StandardCharsets; +package org.apache.maven.wagon.tck.http.fixture; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -31,60 +27,49 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + import org.codehaus.plexus.util.Base64; /** * */ -public class ProxyAuthenticationFilter - implements Filter -{ +public class ProxyAuthenticationFilter implements Filter { private final String username; private final String password; - public ProxyAuthenticationFilter( final String username, final String password ) - { + public ProxyAuthenticationFilter(final String username, final String password) { this.username = username; this.password = password; } - public void destroy() - { - } + public void destroy() {} - public void doFilter( final ServletRequest req, final ServletResponse resp, final FilterChain chain ) - throws IOException, ServletException - { + public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) + throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; - String header = request.getHeader( "Proxy-Authorization" ); - if ( header == null ) - { - response.setStatus( HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED ); - response.addHeader( "Proxy-Authenticate", "Basic realm=\"Squid proxy-caching web server\"" ); + String header = request.getHeader("Proxy-Authorization"); + if (header == null) { + response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); + response.addHeader("Proxy-Authenticate", "Basic realm=\"Squid proxy-caching web server\""); return; - } - else - { - String data = header.substring( "BASIC ".length() ); - data = new String( Base64.decodeBase64( data.getBytes( StandardCharsets.US_ASCII ) ) ); - String[] creds = data.split( ":" ); + } else { + String data = header.substring("BASIC ".length()); + data = new String(Base64.decodeBase64(data.getBytes(StandardCharsets.US_ASCII))); + String[] creds = data.split(":"); - if ( !creds[0].equals( username ) || !creds[1].equals( password ) ) - { - response.sendError( HttpServletResponse.SC_UNAUTHORIZED ); + if (!creds[0].equals(username) || !creds[1].equals(password)) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } - chain.doFilter( req, resp ); - } - - public void init( final FilterConfig filterConfig ) - throws ServletException - { + chain.doFilter(req, resp); } + public void init(final FilterConfig filterConfig) throws ServletException {} } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyConnectionVerifierFilter.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyConnectionVerifierFilter.java index 4d869bcbb..8844a1add 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyConnectionVerifierFilter.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ProxyConnectionVerifierFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import java.io.IOException; -import java.util.Collections; -import java.util.Enumeration; +package org.apache.maven.wagon.tck.http.fixture; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -31,52 +26,43 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Collections; +import java.util.Enumeration; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ -public class ProxyConnectionVerifierFilter - implements Filter -{ - private static Logger logger = LoggerFactory.getLogger( ProxyConnectionVerifierFilter.class ); +public class ProxyConnectionVerifierFilter implements Filter { + private static Logger logger = LoggerFactory.getLogger(ProxyConnectionVerifierFilter.class); - public void destroy() - { - } + public void destroy() {} - @SuppressWarnings( "unchecked" ) - public void doFilter( final ServletRequest req, final ServletResponse resp, final FilterChain chain ) - throws IOException, ServletException - { + @SuppressWarnings("unchecked") + public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) + throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) resp; Enumeration kEn = request.getHeaderNames(); - for ( String key : Collections.list( kEn ) ) - { - if ( key == null ) - { + for (String key : Collections.list(kEn)) { + if (key == null) { continue; } - Enumeration vEn = request.getHeaders( key ); - if ( vEn != null ) - { - for ( String val : Collections.list( vEn ) ) - { - logger.info( key + ": " + val ); + Enumeration vEn = request.getHeaders(key); + if (vEn != null) { + for (String val : Collections.list(vEn)) { + logger.info(key + ": " + val); } } } - chain.doFilter( req, resp ); - } - - public void init( final FilterConfig filterConfig ) - throws ServletException - { + chain.doFilter(req, resp); } + public void init(final FilterConfig filterConfig) throws ServletException {} } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/RedirectionServlet.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/RedirectionServlet.java index 0ff57526b..d87e2630b 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/RedirectionServlet.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/RedirectionServlet.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http.fixture; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; /** - * + * */ -public class RedirectionServlet - extends HttpServlet -{ +public class RedirectionServlet extends HttpServlet { private static final long serialVersionUID = 1L; @@ -44,53 +42,41 @@ public class RedirectionServlet private final String myPath; - public RedirectionServlet( final int code, final String targetPath ) - { + public RedirectionServlet(final int code, final String targetPath) { this.code = code; this.targetPath = targetPath; this.maxRedirects = 1; this.myPath = null; } - public RedirectionServlet( final int code, final String myPath, final String targetPath, final int maxRedirects ) - { + public RedirectionServlet(final int code, final String myPath, final String targetPath, final int maxRedirects) { this.code = code; this.myPath = myPath; this.targetPath = targetPath; this.maxRedirects = maxRedirects; } - public int getRedirectCount() - { + public int getRedirectCount() { return redirectCount; } @Override - protected void service( final HttpServletRequest req, final HttpServletResponse resp ) - throws ServletException, IOException - { + protected void service(final HttpServletRequest req, final HttpServletResponse resp) + throws ServletException, IOException { redirectCount++; - if ( myPath == null ) - { - resp.setStatus( code ); - resp.setHeader( "Location", targetPath ); - } - else if ( maxRedirects < 0 ) - { - resp.setStatus( code ); - resp.setHeader( "Location", myPath ); - } - else if ( redirectCount <= maxRedirects ) - { - resp.setStatus( code ); - resp.setHeader( "Location", myPath + "/" + redirectCount ); - } - else - { - resp.setStatus( code ); - resp.setHeader( "Location", targetPath ); + if (myPath == null) { + resp.setStatus(code); + resp.setHeader("Location", targetPath); + } else if (maxRedirects < 0) { + resp.setStatus(code); + resp.setHeader("Location", myPath); + } else if (redirectCount <= maxRedirects) { + resp.setStatus(code); + resp.setHeader("Location", myPath + "/" + redirectCount); + } else { + resp.setStatus(code); + resp.setHeader("Location", targetPath); } } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServerFixture.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServerFixture.java index e8ca1ed24..45029cbbb 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServerFixture.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServerFixture.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http.fixture; + +import javax.servlet.Filter; +import javax.servlet.Servlet; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; import org.eclipse.jetty.security.ConstraintMapping; import org.eclipse.jetty.security.ConstraintSecurityHandler; @@ -39,20 +45,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.Filter; -import javax.servlet.Servlet; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; - import static org.apache.maven.wagon.tck.http.util.TestUtil.getResource; /** * */ -public class ServerFixture -{ - private static Logger logger = LoggerFactory.getLogger( ServerFixture.class ); +public class ServerFixture { + private static Logger logger = LoggerFactory.getLogger(ServerFixture.class); public static final String SERVER_ROOT_RESOURCE_PATH = "default-server-root"; @@ -77,135 +76,116 @@ public class ServerFixture private int httpPort; - public ServerFixture( final boolean ssl ) - throws URISyntaxException, IOException - { + public ServerFixture(final boolean ssl) throws URISyntaxException, IOException { server = new Server(); - if ( ssl ) - { - String keystore = getResource( SERVER_SSL_KEYSTORE_RESOURCE_PATH ).getAbsolutePath(); + if (ssl) { + String keystore = getResource(SERVER_SSL_KEYSTORE_RESOURCE_PATH).getAbsolutePath(); - LoggerFactory.getLogger( ServerFixture.class ).info( "TCK Keystore path: " + keystore ); - System.setProperty( "javax.net.ssl.keyStore", keystore ); - System.setProperty( "javax.net.ssl.trustStore", keystore ); + LoggerFactory.getLogger(ServerFixture.class).info("TCK Keystore path: " + keystore); + System.setProperty("javax.net.ssl.keyStore", keystore); + System.setProperty("javax.net.ssl.trustStore", keystore); SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath( keystore ); - sslContextFactory.setKeyStorePassword( SERVER_SSL_KEYSTORE_PASSWORD ); - sslContextFactory.setKeyManagerPassword( SERVER_SSL_KEYSTORE_PASSWORD ); - serverConnector = new ServerConnector( server, sslContextFactory ); - server.addConnector( serverConnector ); - } - else - { - serverConnector = new ServerConnector( server ); - serverConnector.setHost( "localhost" ); - //connector.setPort( port ); - server.addConnector( serverConnector ); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword(SERVER_SSL_KEYSTORE_PASSWORD); + sslContextFactory.setKeyManagerPassword(SERVER_SSL_KEYSTORE_PASSWORD); + serverConnector = new ServerConnector(server, sslContextFactory); + server.addConnector(serverConnector); + } else { + serverConnector = new ServerConnector(server); + serverConnector.setHost("localhost"); + // connector.setPort( port ); + server.addConnector(serverConnector); } Constraint constraint = new Constraint(); - constraint.setName( Constraint.__BASIC_AUTH ); + constraint.setName(Constraint.__BASIC_AUTH); - constraint.setRoles( new String[]{ "allowed" } ); - constraint.setAuthenticate( true ); + constraint.setRoles(new String[] {"allowed"}); + constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); - cm.setConstraint( constraint ); - cm.setPathSpec( "/protected/*" ); + cm.setConstraint(constraint); + cm.setPathSpec("/protected/*"); securityHandler = new ConstraintSecurityHandler(); - loginService = new HashLoginService( "Test Server" ); + loginService = new HashLoginService("Test Server"); - securityHandler.setLoginService( loginService ); - securityHandler.setConstraintMappings( new ConstraintMapping[]{ cm } ); + securityHandler.setLoginService(loginService); + securityHandler.setConstraintMappings(new ConstraintMapping[] {cm}); webappContext = new WebAppContext(); - webappContext.setContextPath( "/" ); + webappContext.setContextPath("/"); - File base = getResource( SERVER_ROOT_RESOURCE_PATH ); - logger.info( "docroot: " + base ); - webappContext.setWar( base.getAbsolutePath() ); - webappContext.setHandler( securityHandler ); + File base = getResource(SERVER_ROOT_RESOURCE_PATH); + logger.info("docroot: " + base); + webappContext.setWar(base.getAbsolutePath()); + webappContext.setHandler(securityHandler); SessionHandler sessionHandler = webappContext.getSessionHandler(); - ( (AbstractSessionManager) sessionHandler.getSessionManager() ).setUsingCookies( false ); + ((AbstractSessionManager) sessionHandler.getSessionManager()).setUsingCookies(false); HandlerCollection handlers = new HandlerCollection(); - handlers.setHandlers( new Handler[]{ webappContext, new DefaultHandler() } ); + handlers.setHandlers(new Handler[] {webappContext, new DefaultHandler()}); - server.setHandler( handlers ); + server.setHandler(handlers); } - public void addFilter( final String pathSpec, final Filter filter ) - { + public void addFilter(final String pathSpec, final Filter filter) { String name = "filter" + filterCount++; FilterMapping fm = new FilterMapping(); - fm.setPathSpec( pathSpec ); - fm.setFilterName( name ); + fm.setPathSpec(pathSpec); + fm.setFilterName(name); - FilterHolder fh = new FilterHolder( filter ); - fh.setName( name ); + FilterHolder fh = new FilterHolder(filter); + fh.setName(name); - webappContext.getServletHandler().addFilter( fh, fm ); + webappContext.getServletHandler().addFilter(fh, fm); } - public void addServlet( final String pathSpec, final Servlet servlet ) - { - webappContext.getServletHandler().addServletWithMapping( new ServletHolder( servlet ), pathSpec ); + public void addServlet(final String pathSpec, final Servlet servlet) { + webappContext.getServletHandler().addServletWithMapping(new ServletHolder(servlet), pathSpec); } - public void addUser( final String user, final String password ) - { - loginService.putUser( user, new Password( password ), new String[] { "allowed" } ); + public void addUser(final String user, final String password) { + loginService.putUser(user, new Password(password), new String[] {"allowed"}); } - public Server getServer() - { + public Server getServer() { return server; } - public WebAppContext getWebappContext() - { + public WebAppContext getWebappContext() { return webappContext; } - public void stop() - throws Exception - { - if ( server != null ) - { + public void stop() throws Exception { + if (server != null) { server.stop(); } } - public void start() - throws Exception - { - if ( server.isStarted() || server.isRunning() ) - { + public void start() throws Exception { + if (server.isStarted() || server.isRunning()) { return; } server.start(); int total = 0; - while ( total < 3 * 1000 && !server.isStarted() ) - { - server.wait( 10 ); + while (total < 3 * 1000 && !server.isStarted()) { + server.wait(10); total += 10; } - if ( !server.isStarted() ) - { - throw new IllegalStateException( "Server didn't start in: " + total + "ms." ); + if (!server.isStarted()) { + throw new IllegalStateException("Server didn't start in: " + total + "ms."); } this.httpPort = serverConnector.getLocalPort(); } - public int getHttpPort() - { + public int getHttpPort() { return httpPort; } } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServletExceptionServlet.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServletExceptionServlet.java index 10820ef1d..adce6f51d 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServletExceptionServlet.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/ServletExceptionServlet.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.fixture; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,35 +16,31 @@ * specific language governing permissions and limitations * under the License. */ - -import java.io.IOException; +package org.apache.maven.wagon.tck.http.fixture; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + /** - * + * */ -public class ServletExceptionServlet - extends HttpServlet -{ +public class ServletExceptionServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final String message; - public ServletExceptionServlet( final String message ) - { + public ServletExceptionServlet(final String message) { this.message = message; } @Override - protected void service( final HttpServletRequest request, final HttpServletResponse response ) - throws ServletException, IOException - { - throw new ServletException( message ); + protected void service(final HttpServletRequest request, final HttpServletResponse response) + throws ServletException, IOException { + throw new ServletException(message); } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/TestUtil.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/TestUtil.java index 2314fc5c3..b810c01af 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/TestUtil.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/TestUtil.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http.util; import java.io.File; import java.io.FileOutputStream; @@ -33,123 +32,99 @@ import java.util.jar.JarFile; import org.codehaus.plexus.util.IOUtil; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ -public final class TestUtil -{ +public final class TestUtil { // CHECKSTYLE_OFF: ConstantName - private static final Logger logger = LoggerFactory.getLogger( TestUtil.class ); + private static final Logger logger = LoggerFactory.getLogger(TestUtil.class); // CHECKSTYLE_ON: ConstantName private static final Map BASES = new HashMap<>(); - private TestUtil() - { - } + private TestUtil() {} - public static File getResource( final String path ) - throws URISyntaxException, IOException - { - URL resource = Thread.currentThread().getContextClassLoader().getResource( path ); - if ( resource == null ) - { - throw new IllegalStateException( "Cannot find classpath resource: " + path ); + public static File getResource(final String path) throws URISyntaxException, IOException { + URL resource = Thread.currentThread().getContextClassLoader().getResource(path); + if (resource == null) { + throw new IllegalStateException("Cannot find classpath resource: " + path); } - if ( resource.getProtocol().startsWith( "jar" ) ) - { + if (resource.getProtocol().startsWith("jar")) { // File f = new File( path ); // f = File.createTempFile( f.getName() + ".", ".tmp" ); String url = resource.toExternalForm(); - int startIdx = url.lastIndexOf( ':' ) + 1; - int endIdx = url.indexOf( "!" ); - url = url.substring( startIdx, endIdx ); + int startIdx = url.lastIndexOf(':') + 1; + int endIdx = url.indexOf("!"); + url = url.substring(startIdx, endIdx); - File base = BASES.get( url ); - if ( base == null ) - { - File urlFile = new File( url ); + File base = BASES.get(url); + if (base == null) { + File urlFile = new File(url); - base = new File( "target/tck-resources/" + urlFile.getName() ); + base = new File("target/tck-resources/" + urlFile.getName()); base.getParentFile().mkdirs(); - logger.info( "unpacking test resources in jar: " + url ); + logger.info("unpacking test resources in jar: " + url); JarFile jf = null; - try - { - jf = new JarFile( urlFile ); + try { + jf = new JarFile(urlFile); InputStream in = null; OutputStream out = null; - for ( Enumeration en = jf.entries(); en.hasMoreElements(); ) - { + for (Enumeration en = jf.entries(); en.hasMoreElements(); ) { JarEntry je = en.nextElement(); - final File zipEntryFile = new File( base, je.getName() ); - if ( !zipEntryFile.toPath().normalize().startsWith( base.toPath().normalize() ) ) - { - throw new IOException( "Bad zip entry" ); + final File zipEntryFile = new File(base, je.getName()); + if (!zipEntryFile + .toPath() + .normalize() + .startsWith(base.toPath().normalize())) { + throw new IOException("Bad zip entry"); } File target = zipEntryFile.getAbsoluteFile(); - if ( je.isDirectory() ) - { + if (je.isDirectory()) { target.mkdirs(); - } - else - { + } else { target.getParentFile().mkdirs(); - try - { - in = jf.getInputStream( je ); - out = new FileOutputStream( target ); + try { + in = jf.getInputStream(je); + out = new FileOutputStream(target); - IOUtil.copy( in, out ); + IOUtil.copy(in, out); out.close(); out = null; in.close(); in = null; - } - finally - { - IOUtil.close( in ); - IOUtil.close( out ); + } finally { + IOUtil.close(in); + IOUtil.close(out); } } } - BASES.put( url, base ); - } - finally - { - if ( jf != null ) - { - try - { + BASES.put(url, base); + } finally { + if (jf != null) { + try { jf.close(); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } } } } - return new File( base, path ); - } - else - { - return new File( resource.toURI().normalize() ); + return new File(base, path); + } else { + return new File(resource.toURI().normalize()); } } - } diff --git a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/ValueHolder.java b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/ValueHolder.java index cc303bc28..1d3a581d1 100644 --- a/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/ValueHolder.java +++ b/wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/util/ValueHolder.java @@ -1,5 +1,3 @@ -package org.apache.maven.wagon.tck.http.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,31 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.wagon.tck.http.util; /** - * - * @param + * + * @param */ -public class ValueHolder -{ +public class ValueHolder { private T value; - public ValueHolder() - { - } + public ValueHolder() {} - public ValueHolder( final T initial ) - { + public ValueHolder(final T initial) { this.value = initial; } - public void setValue( final T value ) - { + public void setValue(final T value) { this.value = value; } - public T getValue() - { + public T getValue() { return value; } }