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