You are viewing a plain text version of this content. The canonical link for it is here.
Posted to ivy-commits@incubator.apache.org by xa...@apache.org on 2007/06/05 12:02:43 UTC
svn commit: r544459 [20/36] - in /incubator/ivy/core/trunk:
src/java/org/apache/ivy/ src/java/org/apache/ivy/ant/
src/java/org/apache/ivy/core/ src/java/org/apache/ivy/core/cache/
src/java/org/apache/ivy/core/check/ src/java/org/apache/ivy/core/deliver...
Modified: incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavConnectionManager.java
URL: http://svn.apache.org/viewvc/incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavConnectionManager.java?view=diff&rev=544459&r1=544458&r2=544459
==============================================================================
--- incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavConnectionManager.java (original)
+++ incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavConnectionManager.java Tue Jun 5 05:02:27 2007
@@ -25,40 +25,29 @@
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
-
/**
* Modified version of the WebdavConnectionManager from VFS which adds support for httpclient 3.x.
- * See http://issues.apache.org/jira/browse/VFS-74 for more info.
- *
- * A connection manager that provides access to a single HttpConnection. This
- * manager makes no attempt to provide exclusive access to the contained
- * HttpConnection.
- * <p/>
- * imario@apache.org: Keep connection in ThreadLocal.
- *
+ * See http://issues.apache.org/jira/browse/VFS-74 for more info. A connection manager that provides
+ * access to a single HttpConnection. This manager makes no attempt to provide exclusive access to
+ * the contained HttpConnection. <p/> imario@apache.org: Keep connection in ThreadLocal.
*/
class IvyWebdavConnectionManager implements HttpConnectionManager {
/**
- * Since the same connection is about to be reused, make sure the
- * previous request was completely processed, and if not
- * consume it now.
- *
- * @param conn The connection
+ * Since the same connection is about to be reused, make sure the previous request was
+ * completely processed, and if not consume it now.
+ *
+ * @param conn
+ * The connection
*/
- static void finishLastResponse(HttpConnection conn)
- {
+ static void finishLastResponse(HttpConnection conn) {
InputStream lastResponse = conn.getLastResponseInputStream();
- if (lastResponse != null)
- {
+ if (lastResponse != null) {
conn.setLastResponseInputStream(null);
- try
- {
+ try {
lastResponse.close();
- }
- catch (IOException ioe)
- {
- //FIXME: badness - close to force reconnect.
+ } catch (IOException ioe) {
+ // FIXME: badness - close to force reconnect.
conn.close();
}
}
@@ -67,10 +56,8 @@
/**
* The thread data
*/
- protected ThreadLocal localHttpConnection = new ThreadLocal()
- {
- protected Object initialValue()
- {
+ protected ThreadLocal localHttpConnection = new ThreadLocal() {
+ protected Object initialValue() {
return new Entry();
}
};
@@ -78,21 +65,18 @@
/**
* Collection of parameters associated with this connection manager.
*/
- private HttpConnectionManagerParams params = new HttpConnectionManagerParams();
+ private HttpConnectionManagerParams params = new HttpConnectionManagerParams();
/**
* release the connection of the current thread
*/
- public void releaseLocalConnection()
- {
- if (getLocalHttpConnection() != null)
- {
+ public void releaseLocalConnection() {
+ if (getLocalHttpConnection() != null) {
releaseConnection(getLocalHttpConnection());
}
}
- private static class Entry
- {
+ private static class Entry {
/**
* The http connection
*/
@@ -104,58 +88,50 @@
private long idleStartTime = Long.MAX_VALUE;
}
- public IvyWebdavConnectionManager()
- {
+ public IvyWebdavConnectionManager() {
}
- protected HttpConnection getLocalHttpConnection()
- {
+ protected HttpConnection getLocalHttpConnection() {
return ((Entry) localHttpConnection.get()).conn;
}
- protected void setLocalHttpConnection(HttpConnection conn)
- {
+ protected void setLocalHttpConnection(HttpConnection conn) {
((Entry) localHttpConnection.get()).conn = conn;
}
- protected long getIdleStartTime()
- {
+ protected long getIdleStartTime() {
return ((Entry) localHttpConnection.get()).idleStartTime;
}
- protected void setIdleStartTime(long idleStartTime)
- {
+ protected void setIdleStartTime(long idleStartTime) {
((Entry) localHttpConnection.get()).idleStartTime = idleStartTime;
}
/**
* @see HttpConnectionManager#getConnection(org.apache.commons.httpclient.HostConfiguration)
*/
- public HttpConnection getConnection(HostConfiguration hostConfiguration)
- {
+ public HttpConnection getConnection(HostConfiguration hostConfiguration) {
return getConnection(hostConfiguration, 0);
}
/**
* Gets the staleCheckingEnabled value to be set on HttpConnections that are created.
- *
+ *
* @return <code>true</code> if stale checking will be enabled on HttpConections
* @see HttpConnection#isStaleCheckingEnabled()
*/
- public boolean isConnectionStaleCheckingEnabled()
- {
+ public boolean isConnectionStaleCheckingEnabled() {
return this.params.isStaleCheckingEnabled();
}
/**
* Sets the staleCheckingEnabled value to be set on HttpConnections that are created.
- *
- * @param connectionStaleCheckingEnabled <code>true</code> if stale checking will be enabled
- * on HttpConections
+ *
+ * @param connectionStaleCheckingEnabled
+ * <code>true</code> if stale checking will be enabled on HttpConections
* @see HttpConnection#setStaleCheckingEnabled(boolean)
*/
- public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled)
- {
+ public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) {
this.params.setStaleCheckingEnabled(connectionStaleCheckingEnabled);
}
@@ -163,29 +139,22 @@
* @see HttpConnectionManager#getConnection(HostConfiguration, long)
* @since 3.0
*/
- public HttpConnection getConnectionWithTimeout(
- HostConfiguration hostConfiguration, long timeout)
- {
+ public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout) {
HttpConnection httpConnection = getLocalHttpConnection();
- if (httpConnection == null)
- {
+ if (httpConnection == null) {
httpConnection = new HttpConnection(hostConfiguration);
setLocalHttpConnection(httpConnection);
httpConnection.setHttpConnectionManager(this);
httpConnection.getParams().setDefaults(this.params);
- }
- else
- {
+ } else {
// make sure the host and proxy are correct for this connection
// close it and set the values if they are not
if (!hostConfiguration.hostEquals(httpConnection)
- || !hostConfiguration.proxyEquals(httpConnection))
- {
+ || !hostConfiguration.proxyEquals(httpConnection)) {
- if (httpConnection.isOpen())
- {
+ if (httpConnection.isOpen()) {
httpConnection.close();
}
@@ -196,9 +165,7 @@
httpConnection.setProxyHost(hostConfiguration.getProxyHost());
httpConnection.setProxyPort(hostConfiguration.getProxyPort());
- }
- else
- {
+ } else {
finishLastResponse(httpConnection);
}
}
@@ -213,19 +180,15 @@
* @see HttpConnectionManager#getConnection(HostConfiguration, long)
* @deprecated Use #getConnectionWithTimeout(HostConfiguration, long)
*/
- public HttpConnection getConnection(
- HostConfiguration hostConfiguration, long timeout)
- {
+ public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) {
return getConnectionWithTimeout(hostConfiguration, timeout);
}
/**
* @see HttpConnectionManager#releaseConnection(org.apache.commons.httpclient.HttpConnection)
*/
- public void releaseConnection(HttpConnection conn)
- {
- if (conn != getLocalHttpConnection())
- {
+ public void releaseConnection(HttpConnection conn) {
+ if (conn != getLocalHttpConnection()) {
throw new IllegalStateException("Unexpected release of an unknown connection.");
}
@@ -238,27 +201,25 @@
/**
* @since 3.0
*/
- public void closeIdleConnections(long idleTimeout)
- {
+ public void closeIdleConnections(long idleTimeout) {
long maxIdleTime = System.currentTimeMillis() - idleTimeout;
- if (getIdleStartTime() <= maxIdleTime)
- {
+ if (getIdleStartTime() <= maxIdleTime) {
getLocalHttpConnection().close();
}
}
-
+
/**
- * {@inheritDoc}
- */
- public HttpConnectionManagerParams getParams() {
- return params;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setParams(HttpConnectionManagerParams params) {
- this.params = params;
- }
+ * {@inheritDoc}
+ */
+ public HttpConnectionManagerParams getParams() {
+ return params;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void setParams(HttpConnectionManagerParams params) {
+ this.params = params;
+ }
}
Modified: incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileProvider.java
URL: http://svn.apache.org/viewvc/incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileProvider.java?view=diff&rev=544459&r1=544458&r2=544459
==============================================================================
--- incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileProvider.java (original)
+++ incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileProvider.java Tue Jun 5 05:02:27 2007
@@ -26,27 +26,23 @@
import org.apache.commons.vfs.provider.webdav.WebdavFileProvider;
/**
- * Modified version of the WebdavFileProvider from VFS which adds support for httpclient 3.x.
- * See http://issues.apache.org/jira/browse/VFS-74 for more info.
- *
- * A provider for WebDAV.
- *
+ * Modified version of the WebdavFileProvider from VFS which adds support for httpclient 3.x. See
+ * http://issues.apache.org/jira/browse/VFS-74 for more info. A provider for WebDAV.
*/
public class IvyWebdavFileProvider extends WebdavFileProvider {
- /***********************************************************************************************
- * Creates a filesystem.
- */
- protected FileSystem doCreateFileSystem(final FileName name,
- final FileSystemOptions fileSystemOptions) throws FileSystemException {
- // Create the file system
- final GenericFileName rootName = (GenericFileName) name;
+ /***********************************************************************************************
+ * Creates a filesystem.
+ */
+ protected FileSystem doCreateFileSystem(final FileName name,
+ final FileSystemOptions fileSystemOptions) throws FileSystemException {
+ // Create the file system
+ final GenericFileName rootName = (GenericFileName) name;
- HttpClient httpClient = IvyWebdavClientFactory.createConnection(rootName.getHostName(),
- rootName.getPort(), rootName.getUserName(), rootName.getPassword(),
- fileSystemOptions);
+ HttpClient httpClient = IvyWebdavClientFactory.createConnection(rootName.getHostName(),
+ rootName.getPort(), rootName.getUserName(), rootName.getPassword(), fileSystemOptions);
- return new IvyWebdavFileSystem(rootName, httpClient, fileSystemOptions);
- }
+ return new IvyWebdavFileSystem(rootName, httpClient, fileSystemOptions);
+ }
}
Modified: incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileSystem.java
URL: http://svn.apache.org/viewvc/incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileSystem.java?view=diff&rev=544459&r1=544458&r2=544459
==============================================================================
--- incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileSystem.java (original)
+++ incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/IvyWebdavFileSystem.java Tue Jun 5 05:02:27 2007
@@ -22,15 +22,13 @@
import org.apache.commons.vfs.provider.GenericFileName;
import org.apache.commons.vfs.provider.webdav.WebDavFileSystem;
-
/**
* This class extends from WebDavFileSystem because it doesn't provide an accessible constructor.
- *
*/
class IvyWebdavFileSystem extends WebDavFileSystem {
- protected IvyWebdavFileSystem(GenericFileName arg0, HttpClient arg1, FileSystemOptions arg2) {
- super(arg0, arg1, arg2);
- }
+ protected IvyWebdavFileSystem(GenericFileName arg0, HttpClient arg1, FileSystemOptions arg2) {
+ super(arg0, arg1, arg2);
+ }
}
Modified: incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java
URL: http://svn.apache.org/viewvc/incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java?view=diff&rev=544459&r1=544458&r2=544459
==============================================================================
--- incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java (original)
+++ incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java Tue Jun 5 05:02:27 2007
@@ -39,132 +39,134 @@
import org.apache.ivy.util.FileUtil;
import org.apache.ivy.util.Message;
-
-
/**
* Implementation of a VFS repository
- *
*/
public class VfsRepository extends AbstractRepository {
- /**
- * Name of the resource defining the Ivy VFS Repo configuration.
- */
- private static final String IVY_VFS_CONFIG = "ivy_vfs.xml";
- private StandardFileSystemManager _manager = null;
- private final CopyProgressListener _progress = new RepositoryCopyProgressListener(this);
-
-
- /**
- * Create a new Ivy VFS Repository Instance
- *
- */
- public VfsRepository() {
- }
-
- private FileSystemManager getVFSManager() throws IOException {
- synchronized (this) {
- if (_manager == null) {
- _manager = createVFSManager();
- }
- }
- return _manager;
- }
-
- private StandardFileSystemManager createVFSManager() throws IOException {
- StandardFileSystemManager result = null;
- try {
- /*
- * The DefaultFileSystemManager gets its configuration from the jakarta-vfs-common
- * implementation which includes the res and tmp schemes which are of no use to use here.
- * Using StandardFileSystemManager lets us specify which schemes to support as well as
- * providing a mechanism to change this support without recompilation.
- */
- result = new StandardFileSystemManager() {
- protected void configurePlugins() throws FileSystemException {
- // disable automatic loading potential unsupported extensions
- }
- };
- result.setConfiguration(getClass().getResource(IVY_VFS_CONFIG));
- result.init();
-
- // Generate and print a list of available schemes
- Message.verbose("Available VFS schemes...");
- String[] schemes = result.getSchemes();
- Arrays.sort(schemes);
- for (int i = 0; i < schemes.length; i++) {
- Message.verbose("VFS Supported Scheme: " + schemes[i]);
- }
- } catch (FileSystemException e) {
- /*
- * If our attempt to initialize a VFS Repository fails we log the failure
- * but continue on. Given that an Ivy instance may involve numerous
- * different repository types, it seems overly cautious to throw a runtime
- * exception on the initialization failure of just one repository type.
- */
- Message.error("Unable to initialize VFS repository manager!");
- Message.error(e.getLocalizedMessage());
- IOException error = new IOException(e.getLocalizedMessage());
- error.initCause(e);
- throw error;
- }
-
- return result;
- }
-
-
- protected void finalize() {
- if (_manager != null) {
- _manager.close();
- _manager = null;
- }
- }
-
- /**
- * Get a VfsResource
- *
- * @param source a <code>String</code> identifying a VFS Resource
- * @throws <code>IOException</code> on failure
- * @see "Supported File Systems in the jakarta-commons-vfs documentation"
- */
- public Resource getResource(String vfsURI) throws IOException {
- return new VfsResource(vfsURI, getVFSManager());
- }
-
- /**
- * Transfer a VFS Resource from the repository to the local file system.
- *
- * @param srcVfsURI a <code>String</code> identifying the VFS resource to be fetched
- * @param destination a <code>File</code> identifying the destination file
- * @throws <code>IOException</code> on failure
- * @see "Supported File Systems in the jakarta-commons-vfs documentation"
- */
- public void get(String srcVfsURI, File destination) throws IOException {
- VfsResource src = new VfsResource(srcVfsURI, getVFSManager());
- fireTransferInitiated(src, TransferEvent.REQUEST_GET);
- try {
- FileContent content = src.getContent();
+ /**
+ * Name of the resource defining the Ivy VFS Repo configuration.
+ */
+ private static final String IVY_VFS_CONFIG = "ivy_vfs.xml";
+
+ private StandardFileSystemManager _manager = null;
+
+ private final CopyProgressListener _progress = new RepositoryCopyProgressListener(this);
+
+ /**
+ * Create a new Ivy VFS Repository Instance
+ */
+ public VfsRepository() {
+ }
+
+ private FileSystemManager getVFSManager() throws IOException {
+ synchronized (this) {
+ if (_manager == null) {
+ _manager = createVFSManager();
+ }
+ }
+ return _manager;
+ }
+
+ private StandardFileSystemManager createVFSManager() throws IOException {
+ StandardFileSystemManager result = null;
+ try {
+ /*
+ * The DefaultFileSystemManager gets its configuration from the jakarta-vfs-common
+ * implementation which includes the res and tmp schemes which are of no use to use
+ * here. Using StandardFileSystemManager lets us specify which schemes to support as
+ * well as providing a mechanism to change this support without recompilation.
+ */
+ result = new StandardFileSystemManager() {
+ protected void configurePlugins() throws FileSystemException {
+ // disable automatic loading potential unsupported extensions
+ }
+ };
+ result.setConfiguration(getClass().getResource(IVY_VFS_CONFIG));
+ result.init();
+
+ // Generate and print a list of available schemes
+ Message.verbose("Available VFS schemes...");
+ String[] schemes = result.getSchemes();
+ Arrays.sort(schemes);
+ for (int i = 0; i < schemes.length; i++) {
+ Message.verbose("VFS Supported Scheme: " + schemes[i]);
+ }
+ } catch (FileSystemException e) {
+ /*
+ * If our attempt to initialize a VFS Repository fails we log the failure but continue
+ * on. Given that an Ivy instance may involve numerous different repository types, it
+ * seems overly cautious to throw a runtime exception on the initialization failure of
+ * just one repository type.
+ */
+ Message.error("Unable to initialize VFS repository manager!");
+ Message.error(e.getLocalizedMessage());
+ IOException error = new IOException(e.getLocalizedMessage());
+ error.initCause(e);
+ throw error;
+ }
+
+ return result;
+ }
+
+ protected void finalize() {
+ if (_manager != null) {
+ _manager.close();
+ _manager = null;
+ }
+ }
+
+ /**
+ * Get a VfsResource
+ *
+ * @param source
+ * a <code>String</code> identifying a VFS Resource
+ * @throws <code>IOException</code> on failure
+ * @see "Supported File Systems in the jakarta-commons-vfs documentation"
+ */
+ public Resource getResource(String vfsURI) throws IOException {
+ return new VfsResource(vfsURI, getVFSManager());
+ }
+
+ /**
+ * Transfer a VFS Resource from the repository to the local file system.
+ *
+ * @param srcVfsURI
+ * a <code>String</code> identifying the VFS resource to be fetched
+ * @param destination
+ * a <code>File</code> identifying the destination file
+ * @throws <code>IOException</code> on failure
+ * @see "Supported File Systems in the jakarta-commons-vfs documentation"
+ */
+ public void get(String srcVfsURI, File destination) throws IOException {
+ VfsResource src = new VfsResource(srcVfsURI, getVFSManager());
+ fireTransferInitiated(src, TransferEvent.REQUEST_GET);
+ try {
+ FileContent content = src.getContent();
if (content == null) {
- throw new IllegalArgumentException("invalid vfs uri "+srcVfsURI+": no content found");
+ throw new IllegalArgumentException("invalid vfs uri " + srcVfsURI
+ + ": no content found");
}
FileUtil.copy(content.getInputStream(), destination, _progress);
- } catch (IOException ex) {
- fireTransferError(ex);
- throw ex;
- } catch (RuntimeException ex) {
- fireTransferError(ex);
- throw ex;
- }
- }
-
- /**
- * Return a listing of the contents of a parent directory. Listing is a set
- * of strings representing VFS URIs.
- *
- * @param vfsURI providing identifying a VFS provided resource
- * @throws IOException on failure.
- * @see "Supported File Systems in the jakarta-commons-vfs documentation"
- */
- public List list(String vfsURI) throws IOException {
+ } catch (IOException ex) {
+ fireTransferError(ex);
+ throw ex;
+ } catch (RuntimeException ex) {
+ fireTransferError(ex);
+ throw ex;
+ }
+ }
+
+ /**
+ * Return a listing of the contents of a parent directory. Listing is a set of strings
+ * representing VFS URIs.
+ *
+ * @param vfsURI
+ * providing identifying a VFS provided resource
+ * @throws IOException
+ * on failure.
+ * @see "Supported File Systems in the jakarta-commons-vfs documentation"
+ */
+ public List list(String vfsURI) throws IOException {
ArrayList list = new ArrayList();
Message.debug("list called for URI" + vfsURI);
FileObject resourceImpl = getVFSManager().resolveFile(vfsURI);
@@ -172,7 +174,8 @@
Message.debug("resourceImpl.exists()" + resourceImpl.exists());
Message.debug("resourceImpl.getType()" + resourceImpl.getType());
Message.debug("FileType.FOLDER" + FileType.FOLDER);
- if ((resourceImpl != null) && resourceImpl.exists() && (resourceImpl.getType() == FileType.FOLDER)) {
+ if ((resourceImpl != null) && resourceImpl.exists()
+ && (resourceImpl.getType() == FileType.FOLDER)) {
FileObject[] children = resourceImpl.getChildren();
for (int i = 0; i < children.length; i++) {
FileObject child = children[i];
@@ -182,33 +185,32 @@
}
return list;
}
-
-
-
- /**
- * Transfer an Ivy resource to a VFS repository
- *
- * @param source a <code>File</code> indentifying the local file to transfer to the repository
- * @param vfsURI a <code>String</code> identifying the destination VFS Resource.
- * @param overwrite whether to overwrite an existing resource.
- * @throws <code>IOException</code> on failure.
- * @see "Supported File Systems in the jakarta-commons-vfs documentation"
- *
- */
- public void put(File source, String vfsURI, boolean overwrite) throws IOException {
- VfsResource dest = new VfsResource(vfsURI, getVFSManager());
- fireTransferInitiated(dest, TransferEvent.REQUEST_PUT);
- if (dest.physicallyExists() && ! overwrite) {
- throw new IOException("Cannot copy. Destination file: " + dest.getName() + " exists and overwrite not set.");
- }
+
+ /**
+ * Transfer an Ivy resource to a VFS repository
+ *
+ * @param source
+ * a <code>File</code> indentifying the local file to transfer to the repository
+ * @param vfsURI
+ * a <code>String</code> identifying the destination VFS Resource.
+ * @param overwrite
+ * whether to overwrite an existing resource.
+ * @throws <code>IOException</code> on failure.
+ * @see "Supported File Systems in the jakarta-commons-vfs documentation"
+ */
+ public void put(File source, String vfsURI, boolean overwrite) throws IOException {
+ VfsResource dest = new VfsResource(vfsURI, getVFSManager());
+ fireTransferInitiated(dest, TransferEvent.REQUEST_PUT);
+ if (dest.physicallyExists() && !overwrite) {
+ throw new IOException("Cannot copy. Destination file: " + dest.getName()
+ + " exists and overwrite not set.");
+ }
if (dest.getContent() == null) {
- throw new IllegalArgumentException("invalid vfs uri "+vfsURI+" to put data to: resource has no content");
+ throw new IllegalArgumentException("invalid vfs uri " + vfsURI
+ + " to put data to: resource has no content");
}
-
- FileUtil.copy(new FileInputStream(source),
- dest.getContent().getOutputStream(),
- _progress);
- }
-
+
+ FileUtil.copy(new FileInputStream(source), dest.getContent().getOutputStream(), _progress);
+ }
}
Modified: incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java
URL: http://svn.apache.org/viewvc/incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java?view=diff&rev=544459&r1=544458&r2=544459
==============================================================================
--- incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java (original)
+++ incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java Tue Jun 5 05:02:27 2007
@@ -31,109 +31,112 @@
import org.apache.ivy.plugins.resolver.VfsResolver;
import org.apache.ivy.util.Message;
-
/**
* VFS implementation of the Resource interface
- *
*/
-public class VfsResource implements Resource {
- private String _vfsURI;
- private FileSystemManager _fsManager;
-
+public class VfsResource implements Resource {
+ private String _vfsURI;
+
+ private FileSystemManager _fsManager;
+
private transient boolean _init = false;
+
private transient boolean _exists;
+
private transient long _lastModified;
+
private transient long _contentLength;
- private transient FileContent _content = null;
+ private transient FileContent _content = null;
+
private transient FileObject _resourceImpl;
-
+
// Constructor
public VfsResource(String vfsURI, FileSystemManager fsManager) {
- this._vfsURI = vfsURI;
- this._fsManager = fsManager;
- this._init = false;
+ this._vfsURI = vfsURI;
+ this._fsManager = fsManager;
+ this._init = false;
}
-
+
private void init() {
- if (!_init) {
- try {
- _resourceImpl = _fsManager.resolveFile(_vfsURI);
- _content = _resourceImpl.getContent();
-
- _exists = _resourceImpl.exists();
- _lastModified = _content.getLastModifiedTime();
- _contentLength = _content.getSize();
- } catch (FileSystemException e) {
- Message.verbose(e.getLocalizedMessage());
- _exists = false;
- _lastModified = 0;
- _contentLength = 0;
- }
-
- _init = true;
- }
- }
-
- /**
- * Get a list of direct descendents of the given resource.
- * Note that attempts to get a list of children does <emphasize>not</emphasize>
- * result in an error. Instead an error message is logged and an empty ArrayList returned.
+ if (!_init) {
+ try {
+ _resourceImpl = _fsManager.resolveFile(_vfsURI);
+ _content = _resourceImpl.getContent();
+
+ _exists = _resourceImpl.exists();
+ _lastModified = _content.getLastModifiedTime();
+ _contentLength = _content.getSize();
+ } catch (FileSystemException e) {
+ Message.verbose(e.getLocalizedMessage());
+ _exists = false;
+ _lastModified = 0;
+ _contentLength = 0;
+ }
+
+ _init = true;
+ }
+ }
+
+ /**
+ * Get a list of direct descendents of the given resource. Note that attempts to get a list of
+ * children does <emphasize>not</emphasize> result in an error. Instead an error message is
+ * logged and an empty ArrayList returned.
*
* @return A <code>ArrayList</code> of VFSResources
- *
*/
public List getChildren() {
- init();
- ArrayList list = new ArrayList();
- try {
- if ((_resourceImpl != null) && _resourceImpl.exists() && (_resourceImpl.getType() == FileType.FOLDER)) {
- FileObject[] children = _resourceImpl.getChildren();
- for (int i = 0; i < children.length; i++) {
- FileObject child = children[i];
- list.add(normalize(child.getName().getURI()));
- }
- }
- } catch (IOException e) {
- Message.verbose(e.getLocalizedMessage());
- }
- return list;
+ init();
+ ArrayList list = new ArrayList();
+ try {
+ if ((_resourceImpl != null) && _resourceImpl.exists()
+ && (_resourceImpl.getType() == FileType.FOLDER)) {
+ FileObject[] children = _resourceImpl.getChildren();
+ for (int i = 0; i < children.length; i++) {
+ FileObject child = children[i];
+ list.add(normalize(child.getName().getURI()));
+ }
+ }
+ } catch (IOException e) {
+ Message.verbose(e.getLocalizedMessage());
+ }
+ return list;
}
-
+
public FileContent getContent() {
- init();
- return _content;
+ init();
+ return _content;
}
-
- /**
+
+ /**
* Get the name of the resource.
*
* @return a <code>String</code> representing the Resource URL.
*/
public String getName() {
- return normalize(_vfsURI);
+ return normalize(_vfsURI);
}
-
+
public Resource clone(String cloneName) {
- return new VfsResource(cloneName, _fsManager);
+ return new VfsResource(cloneName, _fsManager);
}
-
+
/**
- * The VFS FileName getURI method seems to have a bug in it where
- * file: URIs will have 4 forward slashes instead of 3.
+ * The VFS FileName getURI method seems to have a bug in it where file: URIs will have 4 forward
+ * slashes instead of 3.
*
* @param vfsURI
* @return a normalized <class>String</class> representing the VFS URI
*/
public static String normalize(String vfsURI) {
- if (vfsURI == null) {
- return "";
- }
-
- if (vfsURI.startsWith("file:////")) {
- vfsURI = vfsURI.replaceFirst("////", "///");
- }
- return vfsURI;
+ if (vfsURI == null) {
+ return "";
+ }
+
+ if (vfsURI.startsWith("file:////")) {
+ vfsURI = vfsURI.replaceFirst("////", "///");
+ }
+ return vfsURI;
}
/**
@@ -141,51 +144,51 @@
*
* @return a <code>long</code> indicating last modified time.
*/
- public long getLastModified() {
- init();
- return _lastModified;
+ public long getLastModified() {
+ init();
+ return _lastModified;
}
- /**
- * Get the size of the resource
- *
- * @return a <code>long</code> representing the size of the resource (in bytes).
- */
+ /**
+ * Get the size of the resource
+ *
+ * @return a <code>long</code> representing the size of the resource (in bytes).
+ */
public long getContentLength() {
- init();
- return _contentLength;
+ init();
+ return _contentLength;
}
/**
* Flag indicating whether a resource is available for querying
*
- * @return <code>true</code> if the resource is available for querying,
- * <code>false</code> otherwise.
+ * @return <code>true</code> if the resource is available for querying, <code>false</code>
+ * otherwise.
*/
public boolean exists() {
- init();
- return _exists;
+ init();
+ return _exists;
}
-
+
/**
* Return a flag indicating whether a provided VFS resource physically exists
*
* @return <code>true</code> if the resource physically exists, <code>false</code>
* otherwise.
*/
- public boolean physicallyExists() {
- // TODO: there is no need for this method anymore, replace it by calling exists();
- init();
-
- try {
- return _resourceImpl.exists();
- // originally I only checked for a FileSystemException. I expanded it to
- // include all exceptions when I found it would throw a NPE exception when the query was
- // run on non-wellformed VFS URI.
- } catch (Exception e) {
- Message.verbose(e.getLocalizedMessage());
- return false;
- }
+ public boolean physicallyExists() {
+ // TODO: there is no need for this method anymore, replace it by calling exists();
+ init();
+
+ try {
+ return _resourceImpl.exists();
+ // originally I only checked for a FileSystemException. I expanded it to
+ // include all exceptions when I found it would throw a NPE exception when the query was
+ // run on non-wellformed VFS URI.
+ } catch (Exception e) {
+ Message.verbose(e.getLocalizedMessage());
+ return false;
+ }
}
public String toString() {
@@ -196,7 +199,7 @@
return getName().startsWith("file:");
}
- public InputStream openStream() throws IOException {
- return getContent().getInputStream();
- }
+ public InputStream openStream() throws IOException {
+ return getContent().getInputStream();
+ }
}
Modified: incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java
URL: http://svn.apache.org/viewvc/incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java?view=diff&rev=544459&r1=544458&r2=544459
==============================================================================
--- incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java (original)
+++ incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java Tue Jun 5 05:02:27 2007
@@ -40,327 +40,335 @@
import org.apache.ivy.plugins.repository.TransferEvent;
import org.apache.ivy.util.Message;
-
/**
- * Repository using SecureCRT vsftp command line program to access an sftp repository
- *
- * This is especially useful to leverage the gssapi authentication supported by SecureCRT.
- *
- * In caseswhere usual sftp is enough, prefer the 100% java solution of sftp repository.
- *
- * This requires SecureCRT to be in the PATH.
- *
- * Tested with SecureCRT 5.0.5
- *
- *
+ * Repository using SecureCRT vsftp command line program to access an sftp repository This is
+ * especially useful to leverage the gssapi authentication supported by SecureCRT. In caseswhere
+ * usual sftp is enough, prefer the 100% java solution of sftp repository. This requires SecureCRT
+ * to be in the PATH. Tested with SecureCRT 5.0.5
*/
public class VsftpRepository extends AbstractRepository {
- private static final String PROMPT = "vsftp> ";
+ private static final String PROMPT = "vsftp> ";
+
+ private static final SimpleDateFormat FORMAT = new SimpleDateFormat("MMM dd, yyyy HH:mm",
+ Locale.US);
+
+ private String _host;
+
+ private String _username;
+
+ private String _authentication = "gssapi";
+
+ private Reader _in;
- private static final SimpleDateFormat FORMAT = new SimpleDateFormat("MMM dd, yyyy HH:mm", Locale.US);
-
- private String _host;
- private String _username;
- private String _authentication = "gssapi";
-
- private Reader _in;
- private Reader _err;
- private PrintWriter _out;
-
- private volatile StringBuffer _errors = new StringBuffer();
+ private Reader _err;
- private long _readTimeout = 30000;
-
- private long _reuseConnection = 5 * 60 * 1000; // reuse connection during 5 minutes by default
+ private PrintWriter _out;
- private volatile long _lastCommand;
+ private volatile StringBuffer _errors = new StringBuffer();
- private volatile boolean _inCommand;
+ private long _readTimeout = 30000;
- private Process _process;
+ private long _reuseConnection = 5 * 60 * 1000; // reuse connection during 5 minutes by default
- private Thread _connectionCleaner;
+ private volatile long _lastCommand;
+
+ private volatile boolean _inCommand;
+
+ private Process _process;
+
+ private Thread _connectionCleaner;
+
+ private Thread _errorsReader;
- private Thread _errorsReader;
private volatile long _errorsLastUpdateTime;
-
- private Ivy _ivy = null;
- public Resource getResource(String source) throws IOException {
- initIvy();
- return new VsftpResource(this, source);
- }
-
- private void initIvy() {
- _ivy = IvyContext.getContext().getIvy();
- }
-
- protected Resource getInitResource(String source) throws IOException {
- try {
- return lslToResource(source, sendCommand("ls -l "+source, true, true));
- } catch (IOException ex) {
- cleanup(ex);
- throw ex;
- } finally {
- cleanup();
- }
- }
-
- public void get(final String source, File destination) throws IOException {
- initIvy();
- try {
- fireTransferInitiated(getResource(source), TransferEvent.REQUEST_GET);
- File destDir = destination.getParentFile();
- if (destDir != null) {
- sendCommand("lcd "+destDir.getAbsolutePath());
- }
- if (destination.exists()) {
- destination.delete();
- }
-
- int index = source.lastIndexOf('/');
- String srcName = index == -1?source:source.substring(index+1);
- final File to = destDir == null ? new File(srcName):new File(destDir, srcName);
-
- final IOException ex[] = new IOException[1];
- Thread get = new IvyThread() {
- public void run() {
- initContext();
- try {
- sendCommand("get "+source, getExpectedDownloadMessage(source, to), 0);
- } catch (IOException e) {
- ex[0] = e;
- }
- }
- };
- get.start();
-
- long prevLength = 0;
- long lastUpdate = System.currentTimeMillis();
- long timeout = _readTimeout;
- while (get.isAlive()) {
- checkInterrupted();
- long length = to.exists()?to.length():0;
- if (length > prevLength) {
- fireTransferProgress(length - prevLength);
- lastUpdate = System.currentTimeMillis();
- prevLength = length;
- } else {
- if (System.currentTimeMillis() - lastUpdate > timeout) {
- Message.verbose("download hang for more than "+timeout+"ms. Interrupting.");
- get.interrupt();
- if (to.exists()) to.delete();
- throw new IOException(source+" download timeout from "+getHost());
- }
- }
- try {
- get.join(100);
- } catch (InterruptedException e) {
- if (to.exists()) to.delete();
- return;
- }
- }
- if (ex[0] != null) {
- if (to.exists()) to.delete();
- throw ex[0];
- }
-
- to.renameTo(destination);
- fireTransferCompleted(destination.length());
- } catch (IOException ex) {
- fireTransferError(ex);
- cleanup(ex);
- throw ex;
- } finally {
- cleanup();
- }
- }
-
- public List list(String parent) throws IOException {
- initIvy();
- try {
- if (!parent.endsWith("/")) {
- parent = parent+"/";
- }
- String response = sendCommand("ls -l "+parent, true, true);
- if (response.startsWith("ls")) {
- return null;
- }
- String[] lines = response.split("\n");
- List ret = new ArrayList(lines.length);
- for (int i = 0; i < lines.length; i++) {
- while (lines[i].endsWith("\r") || lines[i].endsWith("\n")) {
- lines[i] = lines[i].substring(0, lines[i].length() -1);
- }
- if (lines[i].trim().length() != 0) {
- ret.add(parent+lines[i].substring(lines[i].lastIndexOf(' ')+1));
- }
- }
- return ret;
- } catch (IOException ex) {
- cleanup(ex);
- throw ex;
- } finally {
- cleanup();
- }
- }
-
- public void put(File source, String destination, boolean overwrite) throws IOException {
- initIvy();
- try {
- if (getResource(destination).exists()) {
- if (overwrite) {
- sendCommand("rm "+destination, getExpectedRemoveMessage(destination));
- } else {
- return;
- }
- }
- int index = destination.lastIndexOf('/');
- String destDir = null;
- if (index != -1) {
- destDir = destination.substring(0, index);
- mkdirs(destDir);
- sendCommand("cd "+destDir);
- }
- String to = destDir != null ? destDir+"/"+source.getName():source.getName();
- sendCommand("put "+source.getAbsolutePath(), getExpectedUploadMessage(source, to), 0);
- sendCommand("mv "+to+" "+destination);
- } catch (IOException ex) {
- cleanup(ex);
- throw ex;
- } finally {
- cleanup();
- }
- }
-
-
- private void mkdirs(String destDir) throws IOException {
- if (dirExists(destDir)) {
- return;
- }
- if (destDir.endsWith("/")) {
- destDir = destDir.substring(0, destDir.length() - 1);
- }
- int index = destDir.lastIndexOf('/');
- if (index != - 1) {
- mkdirs(destDir.substring(0, index));;
- }
- sendCommand("mkdir "+destDir);
- }
-
- private boolean dirExists(String dir) throws IOException {
- return !sendCommand("ls "+dir, true).startsWith("ls: ");
- }
-
- protected String sendCommand(String command) throws IOException {
- return sendCommand(command, false, _readTimeout);
- }
-
- protected void sendCommand(String command, Pattern expectedResponse) throws IOException {
- sendCommand(command, expectedResponse, _readTimeout);
- }
-
- /**
- * The behaviour of vsftp with some commands is to log the resulting message on the error stream,
- * even if everything is ok.
- *
- * So it's quite difficult if there was an error or not.
- *
- * Hence we compare the response with the expected message and deal with it.
- * The problem is that this is very specific to the version of vsftp used for the test,
- *
- * That's why expected messages are obtained using overridable protected methods.
- */
- protected void sendCommand(String command, Pattern expectedResponse, long timeout) throws IOException {
- String response = sendCommand(command, true, timeout);
- if (!expectedResponse.matcher(response).matches()) {
- Message.debug("invalid response from server:");
- Message.debug("expected: '"+expectedResponse+"'");
- Message.debug("was: '"+response+"'");
- throw new IOException(response);
- }
- }
- protected String sendCommand(String command, boolean sendErrorAsResponse) throws IOException {
- return sendCommand(command, sendErrorAsResponse, _readTimeout);
- }
-
- protected String sendCommand(String command, boolean sendErrorAsResponse, boolean single) throws IOException {
- return sendCommand(command, sendErrorAsResponse, single, _readTimeout);
- }
-
- protected String sendCommand(String command, boolean sendErrorAsResponse, long timeout) throws IOException {
- return sendCommand(command, sendErrorAsResponse, false, timeout);
- }
-
- protected String sendCommand(String command, boolean sendErrorAsResponse, boolean single, long timeout) throws IOException {
- single = false; // use of alone commands does not work properly due to a long delay between end of process and end of stream...
+ private Ivy _ivy = null;
- checkInterrupted();
- _inCommand = true;
+ public Resource getResource(String source) throws IOException {
+ initIvy();
+ return new VsftpResource(this, source);
+ }
+
+ private void initIvy() {
+ _ivy = IvyContext.getContext().getIvy();
+ }
+
+ protected Resource getInitResource(String source) throws IOException {
+ try {
+ return lslToResource(source, sendCommand("ls -l " + source, true, true));
+ } catch (IOException ex) {
+ cleanup(ex);
+ throw ex;
+ } finally {
+ cleanup();
+ }
+ }
+
+ public void get(final String source, File destination) throws IOException {
+ initIvy();
+ try {
+ fireTransferInitiated(getResource(source), TransferEvent.REQUEST_GET);
+ File destDir = destination.getParentFile();
+ if (destDir != null) {
+ sendCommand("lcd " + destDir.getAbsolutePath());
+ }
+ if (destination.exists()) {
+ destination.delete();
+ }
+
+ int index = source.lastIndexOf('/');
+ String srcName = index == -1 ? source : source.substring(index + 1);
+ final File to = destDir == null ? new File(srcName) : new File(destDir, srcName);
+
+ final IOException ex[] = new IOException[1];
+ Thread get = new IvyThread() {
+ public void run() {
+ initContext();
+ try {
+ sendCommand("get " + source, getExpectedDownloadMessage(source, to), 0);
+ } catch (IOException e) {
+ ex[0] = e;
+ }
+ }
+ };
+ get.start();
+
+ long prevLength = 0;
+ long lastUpdate = System.currentTimeMillis();
+ long timeout = _readTimeout;
+ while (get.isAlive()) {
+ checkInterrupted();
+ long length = to.exists() ? to.length() : 0;
+ if (length > prevLength) {
+ fireTransferProgress(length - prevLength);
+ lastUpdate = System.currentTimeMillis();
+ prevLength = length;
+ } else {
+ if (System.currentTimeMillis() - lastUpdate > timeout) {
+ Message.verbose("download hang for more than " + timeout
+ + "ms. Interrupting.");
+ get.interrupt();
+ if (to.exists())
+ to.delete();
+ throw new IOException(source + " download timeout from " + getHost());
+ }
+ }
+ try {
+ get.join(100);
+ } catch (InterruptedException e) {
+ if (to.exists())
+ to.delete();
+ return;
+ }
+ }
+ if (ex[0] != null) {
+ if (to.exists())
+ to.delete();
+ throw ex[0];
+ }
+
+ to.renameTo(destination);
+ fireTransferCompleted(destination.length());
+ } catch (IOException ex) {
+ fireTransferError(ex);
+ cleanup(ex);
+ throw ex;
+ } finally {
+ cleanup();
+ }
+ }
+
+ public List list(String parent) throws IOException {
+ initIvy();
+ try {
+ if (!parent.endsWith("/")) {
+ parent = parent + "/";
+ }
+ String response = sendCommand("ls -l " + parent, true, true);
+ if (response.startsWith("ls")) {
+ return null;
+ }
+ String[] lines = response.split("\n");
+ List ret = new ArrayList(lines.length);
+ for (int i = 0; i < lines.length; i++) {
+ while (lines[i].endsWith("\r") || lines[i].endsWith("\n")) {
+ lines[i] = lines[i].substring(0, lines[i].length() - 1);
+ }
+ if (lines[i].trim().length() != 0) {
+ ret.add(parent + lines[i].substring(lines[i].lastIndexOf(' ') + 1));
+ }
+ }
+ return ret;
+ } catch (IOException ex) {
+ cleanup(ex);
+ throw ex;
+ } finally {
+ cleanup();
+ }
+ }
+
+ public void put(File source, String destination, boolean overwrite) throws IOException {
+ initIvy();
+ try {
+ if (getResource(destination).exists()) {
+ if (overwrite) {
+ sendCommand("rm " + destination, getExpectedRemoveMessage(destination));
+ } else {
+ return;
+ }
+ }
+ int index = destination.lastIndexOf('/');
+ String destDir = null;
+ if (index != -1) {
+ destDir = destination.substring(0, index);
+ mkdirs(destDir);
+ sendCommand("cd " + destDir);
+ }
+ String to = destDir != null ? destDir + "/" + source.getName() : source.getName();
+ sendCommand("put " + source.getAbsolutePath(), getExpectedUploadMessage(source, to), 0);
+ sendCommand("mv " + to + " " + destination);
+ } catch (IOException ex) {
+ cleanup(ex);
+ throw ex;
+ } finally {
+ cleanup();
+ }
+ }
+
+ private void mkdirs(String destDir) throws IOException {
+ if (dirExists(destDir)) {
+ return;
+ }
+ if (destDir.endsWith("/")) {
+ destDir = destDir.substring(0, destDir.length() - 1);
+ }
+ int index = destDir.lastIndexOf('/');
+ if (index != -1) {
+ mkdirs(destDir.substring(0, index));
+ ;
+ }
+ sendCommand("mkdir " + destDir);
+ }
+
+ private boolean dirExists(String dir) throws IOException {
+ return !sendCommand("ls " + dir, true).startsWith("ls: ");
+ }
+
+ protected String sendCommand(String command) throws IOException {
+ return sendCommand(command, false, _readTimeout);
+ }
+
+ protected void sendCommand(String command, Pattern expectedResponse) throws IOException {
+ sendCommand(command, expectedResponse, _readTimeout);
+ }
+
+ /**
+ * The behaviour of vsftp with some commands is to log the resulting message on the error
+ * stream, even if everything is ok. So it's quite difficult if there was an error or not. Hence
+ * we compare the response with the expected message and deal with it. The problem is that this
+ * is very specific to the version of vsftp used for the test, That's why expected messages are
+ * obtained using overridable protected methods.
+ */
+ protected void sendCommand(String command, Pattern expectedResponse, long timeout)
+ throws IOException {
+ String response = sendCommand(command, true, timeout);
+ if (!expectedResponse.matcher(response).matches()) {
+ Message.debug("invalid response from server:");
+ Message.debug("expected: '" + expectedResponse + "'");
+ Message.debug("was: '" + response + "'");
+ throw new IOException(response);
+ }
+ }
+
+ protected String sendCommand(String command, boolean sendErrorAsResponse) throws IOException {
+ return sendCommand(command, sendErrorAsResponse, _readTimeout);
+ }
+
+ protected String sendCommand(String command, boolean sendErrorAsResponse, boolean single)
+ throws IOException {
+ return sendCommand(command, sendErrorAsResponse, single, _readTimeout);
+ }
+
+ protected String sendCommand(String command, boolean sendErrorAsResponse, long timeout)
+ throws IOException {
+ return sendCommand(command, sendErrorAsResponse, false, timeout);
+ }
+
+ protected String sendCommand(String command, boolean sendErrorAsResponse, boolean single,
+ long timeout) throws IOException {
+ single = false; // use of alone commands does not work properly due to a long delay between
+ // end of process and end of stream...
+
+ checkInterrupted();
+ _inCommand = true;
_errorsLastUpdateTime = 0;
- synchronized (this) {
- if (!single || _in != null) {
- ensureConnectionOpened();
- Message.debug("sending command '"+command+"' to "+getHost());
- updateLastCommandTime();
- _out.println(command);
- _out.flush();
- } else {
- sendSingleCommand(command);
- }
- }
-
- try {
- return readResponse(sendErrorAsResponse, timeout);
- } finally {
- _inCommand = false;
- if (single) {
- closeConnection();
- }
- }
- }
-
- protected String readResponse(boolean sendErrorAsResponse) throws IOException {
- return readResponse(sendErrorAsResponse, _readTimeout);
- }
-
- protected synchronized String readResponse(final boolean sendErrorAsResponse, long timeout) throws IOException {
- final StringBuffer response = new StringBuffer();
- final IOException[] exc = new IOException[1];
- final boolean[] done = new boolean[1];
- Runnable r = new Runnable() {
- public void run() {
- synchronized (VsftpRepository.this) {
- try {
- int c;
- boolean getPrompt = false;
- // the reading is done in a for loop making five attempts to read the stream if we do not reach the next prompt
- for (int attempts = 0; !getPrompt && attempts < 5; attempts++) {
- while ((c = _in.read()) != -1) {
- attempts = 0; // we manage to read something, reset numer of attempts
- response.append((char)c);
- if (response.length() >= PROMPT.length()
- && response.substring(response.length() - PROMPT.length(), response.length()).equals(PROMPT)) {
- response.setLength(response.length() - PROMPT.length());
- getPrompt = true;
- break;
- }
- }
- if (!getPrompt) {
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- break;
- }
- }
- }
+ synchronized (this) {
+ if (!single || _in != null) {
+ ensureConnectionOpened();
+ Message.debug("sending command '" + command + "' to " + getHost());
+ updateLastCommandTime();
+ _out.println(command);
+ _out.flush();
+ } else {
+ sendSingleCommand(command);
+ }
+ }
+
+ try {
+ return readResponse(sendErrorAsResponse, timeout);
+ } finally {
+ _inCommand = false;
+ if (single) {
+ closeConnection();
+ }
+ }
+ }
+
+ protected String readResponse(boolean sendErrorAsResponse) throws IOException {
+ return readResponse(sendErrorAsResponse, _readTimeout);
+ }
+
+ protected synchronized String readResponse(final boolean sendErrorAsResponse, long timeout)
+ throws IOException {
+ final StringBuffer response = new StringBuffer();
+ final IOException[] exc = new IOException[1];
+ final boolean[] done = new boolean[1];
+ Runnable r = new Runnable() {
+ public void run() {
+ synchronized (VsftpRepository.this) {
+ try {
+ int c;
+ boolean getPrompt = false;
+ // the reading is done in a for loop making five attempts to read the stream
+ // if we do not reach the next prompt
+ for (int attempts = 0; !getPrompt && attempts < 5; attempts++) {
+ while ((c = _in.read()) != -1) {
+ attempts = 0; // we manage to read something, reset numer of
+ // attempts
+ response.append((char) c);
+ if (response.length() >= PROMPT.length()
+ && response.substring(response.length() - PROMPT.length(),
+ response.length()).equals(PROMPT)) {
+ response.setLength(response.length() - PROMPT.length());
+ getPrompt = true;
+ break;
+ }
+ }
+ if (!getPrompt) {
+ try {
+ Thread.sleep(50);
+ } catch (InterruptedException e) {
+ break;
+ }
+ }
+ }
if (getPrompt) {
// wait enough for error stream to be fully read
if (_errorsLastUpdateTime == 0) {
// no error written yet, but it may be pending...
_errorsLastUpdateTime = _lastCommand;
}
-
+
while ((System.currentTimeMillis() - _errorsLastUpdateTime) < 50) {
try {
Thread.sleep(30);
@@ -369,42 +377,42 @@
}
}
}
- if (_errors.length() > 0) {
- if (sendErrorAsResponse) {
- response.append(_errors);
- _errors.setLength(0);
- } else {
- throw new IOException(chomp(_errors).toString());
- }
- }
- chomp(response);
- done[0] = true;
- } catch (IOException e) {
- exc[0] = e;
- } finally {
- VsftpRepository.this.notify();
+ if (_errors.length() > 0) {
+ if (sendErrorAsResponse) {
+ response.append(_errors);
+ _errors.setLength(0);
+ } else {
+ throw new IOException(chomp(_errors).toString());
+ }
+ }
+ chomp(response);
+ done[0] = true;
+ } catch (IOException e) {
+ exc[0] = e;
+ } finally {
+ VsftpRepository.this.notify();
}
- }
- }
- };
- Thread reader = null;
- if (timeout == 0) {
- r.run();
- } else {
- reader = new IvyThread(r);
- reader.start();
- try {
- wait(timeout);
- } catch (InterruptedException e) {
- }
- }
- updateLastCommandTime();
- if (exc[0] != null) {
- throw exc[0];
- } else if (!done[0]) {
- if (reader != null && reader.isAlive()) {
+ }
+ }
+ };
+ Thread reader = null;
+ if (timeout == 0) {
+ r.run();
+ } else {
+ reader = new IvyThread(r);
+ reader.start();
+ try {
+ wait(timeout);
+ } catch (InterruptedException e) {
+ }
+ }
+ updateLastCommandTime();
+ if (exc[0] != null) {
+ throw exc[0];
+ } else if (!done[0]) {
+ if (reader != null && reader.isAlive()) {
reader.interrupt();
- for (int i = 0; i<5 && reader.isAlive(); i++) {
+ for (int i = 0; i < 5 && reader.isAlive(); i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
@@ -414,270 +422,277 @@
if (reader.isAlive()) {
reader.stop(); // no way to interrupt it non abruptly
}
- }
- throw new IOException("connection timeout to "+getHost());
- } else {
- if ("Not connected.".equals(response)) {
- Message.info("vsftp connection to "+getHost()+" reset");
- closeConnection();
- throw new IOException("not connected to "+getHost());
- }
- Message.debug("received response '"+response+"' from "+getHost());
- return response.toString();
- }
- }
-
- private synchronized void sendSingleCommand(String command) throws IOException {
- exec(getSingleCommand(command));
- }
-
- protected synchronized void ensureConnectionOpened() throws IOException {
- if (_in == null) {
- Message.verbose("connecting to "+getUsername()+"@"+getHost()+"... ");
- String connectionCommand = getConnectionCommand();
- exec(connectionCommand);
-
- try {
- readResponse(false); // waits for first prompt
-
- if (_reuseConnection > 0) {
- _connectionCleaner = new IvyThread() {
- public void run() {
- initContext();
- try {
- long sleep = 10;
- while (_in != null && sleep > 0) {
- sleep(sleep);
- sleep = _reuseConnection - (System.currentTimeMillis() - _lastCommand);
- if (_inCommand) {
- sleep = sleep <= 0 ? _reuseConnection : sleep;
- }
- }
- } catch (InterruptedException e) {
- }
- disconnect();
- }
- };
- _connectionCleaner.start();
- }
-
- if (_ivy != null) {
- _ivy.getEventManager().addIvyListener(new IvyListener() {
- public void progress(IvyEvent event) {
- disconnect();
- event.getSource().removeIvyListener(this);
- }
- }, EndResolveEvent.NAME);
- }
-
-
- } catch (IOException ex) {
- closeConnection();
- throw new IOException("impossible to connect to "+getUsername()+"@"+getHost()+" using "+getAuthentication()+": "+ex.getMessage());
- }
- Message.verbose("connected to "+getHost());
- }
- }
-
- private void updateLastCommandTime() {
- _lastCommand = System.currentTimeMillis();
- }
-
- private void exec(String command) throws IOException {
- Message.debug("launching '"+command+"'");
- _process = Runtime.getRuntime().exec(command);
- _in = new InputStreamReader(_process.getInputStream());
- _err = new InputStreamReader(_process.getErrorStream());
- _out = new PrintWriter(_process.getOutputStream());
-
- _errorsReader = new IvyThread() {
- public void run() {
- initContext();
- int c;
- try {
- while (_err != null && (c = _err.read()) != -1) {
- _errors.append((char)c);
- _errorsLastUpdateTime = System.currentTimeMillis();
- }
- } catch (IOException e) {
- }
- }
- };
- _errorsReader.start();
- }
-
-
- private void checkInterrupted() {
- if (_ivy != null) {
- _ivy.checkInterrupted();
- }
- }
-
- /**
- * Called whenever an api level method end
- */
- private void cleanup(Exception ex) {
- if (ex.getMessage().equals("connection timeout to "+getHost())) {
- closeConnection();
- } else {
- disconnect();
- }
- }
-
- /**
- * Called whenever an api level method end
- */
- private void cleanup() {
- if (_reuseConnection == 0) {
- disconnect();
- }
- }
-
- public synchronized void disconnect() {
- if (_in != null) {
- Message.verbose("disconnecting from "+getHost()+"... ");
- try {
- sendCommand("exit", false, 300);
- } catch (IOException e) {
- } finally {
- closeConnection();
- Message.verbose("disconnected of "+getHost());
- }
- }
- }
-
- private synchronized void closeConnection() {
- if (_connectionCleaner != null) {
- _connectionCleaner.interrupt();
- }
- if (_errorsReader != null) {
- _errorsReader.interrupt();
- }
- try {
- _process.destroy();
- } catch (Exception ex) {}
- try {
- _in.close();
- } catch (Exception e) {}
- try {
- _err.close();
- } catch (Exception e) {}
- try {
- _out.close();
- } catch (Exception e) {}
-
- _connectionCleaner = null;
- _errorsReader = null;
- _process = null;
- _in = null;
- _out = null;
- _err = null;
- Message.debug("connection to "+getHost()+" closed");
- }
-
- /**
- * Parses a ls -l line and transforms it in a resource
- * @param file
- * @param responseLine
- * @return
- */
- protected Resource lslToResource(String file, String responseLine) {
- if (responseLine == null || responseLine.startsWith("ls")) {
- return new BasicResource(file, false, 0, 0, false);
- } else {
- String[] parts = responseLine.split("\\s+");
- if (parts.length != 9) {
- Message.debug("unrecognized ls format: "+responseLine);
- return new BasicResource(file, false, 0, 0, false);
- } else {
- try {
- long contentLength = Long.parseLong(parts[3]);
- String date = parts[4]+" "+parts[5]+" "+parts[6]+" "+parts[7];
- return new BasicResource(file, true, contentLength, FORMAT.parse(date).getTime(), false);
- } catch (Exception ex) {
- Message.warn("impossible to parse server response: "+responseLine+": "+ex);
- return new BasicResource(file, false, 0, 0, false);
- }
- }
- }
- }
-
- protected String getSingleCommand(String command) {
- return "vsh -noprompt -auth "+_authentication+" "+_username+"@"+_host+" "+command;
- }
-
- protected String getConnectionCommand() {
- return "vsftp -noprompt -auth "+_authentication+" "+_username+"@"+_host;
- }
-
- protected Pattern getExpectedDownloadMessage(String source, File to) {
- return Pattern.compile("Downloading "+to.getName()+" from [^\\s]+");
- }
-
- protected Pattern getExpectedRemoveMessage(String destination) {
- return Pattern.compile("Removing [^\\s]+");
- }
-
- protected Pattern getExpectedUploadMessage(File source, String to) {
- return Pattern.compile("Uploading "+source.getName()+" to [^\\s]+");
- }
-
-
- public String getAuthentication() {
- return _authentication;
- }
-
- public void setAuthentication(String authentication) {
- _authentication = authentication;
- }
-
- public String getHost() {
- return _host;
- }
-
- public void setHost(String host) {
- _host = host;
- }
-
- public String getUsername() {
- return _username;
- }
-
- public void setUsername(String username) {
- _username = username;
- }
-
- private static StringBuffer chomp(StringBuffer str) {
- if (str == null || str.length() == 0) {
- return str;
- }
- while ("\n".equals(str.substring(str.length() - 1)) || "\r".equals(str.substring(str.length() - 1))) {
- str.setLength(str.length() - 1);
- }
- return str;
- }
-
- public String toString() {
- return getName()+" "+getUsername()+"@"+getHost()+" ("+getAuthentication()+")";
- }
-
- /**
- * Sets the reuse connection time.
- * The same connection will be reused if the time here does not last
- * between two commands.
- * O indicates that the connection should never be reused
- *
- * @param time
- */
- public void setReuseConnection(long time) {
- _reuseConnection = time;
- }
-
- public long getReadTimeout() {
- return _readTimeout;
- }
-
- public void setReadTimeout(long readTimeout) {
- _readTimeout = readTimeout;
- }
+ }
+ throw new IOException("connection timeout to " + getHost());
+ } else {
+ if ("Not connected.".equals(response)) {
+ Message.info("vsftp connection to " + getHost() + " reset");
+ closeConnection();
+ throw new IOException("not connected to " + getHost());
+ }
+ Message.debug("received response '" + response + "' from " + getHost());
+ return response.toString();
+ }
+ }
+
+ private synchronized void sendSingleCommand(String command) throws IOException {
+ exec(getSingleCommand(command));
+ }
+
+ protected synchronized void ensureConnectionOpened() throws IOException {
+ if (_in == null) {
+ Message.verbose("connecting to " + getUsername() + "@" + getHost() + "... ");
+ String connectionCommand = getConnectionCommand();
+ exec(connectionCommand);
+
+ try {
+ readResponse(false); // waits for first prompt
+
+ if (_reuseConnection > 0) {
+ _connectionCleaner = new IvyThread() {
+ public void run() {
+ initContext();
+ try {
+ long sleep = 10;
+ while (_in != null && sleep > 0) {
+ sleep(sleep);
+ sleep = _reuseConnection
+ - (System.currentTimeMillis() - _lastCommand);
+ if (_inCommand) {
+ sleep = sleep <= 0 ? _reuseConnection : sleep;
+ }
+ }
+ } catch (InterruptedException e) {
+ }
+ disconnect();
+ }
+ };
+ _connectionCleaner.start();
+ }
+
+ if (_ivy != null) {
+ _ivy.getEventManager().addIvyListener(new IvyListener() {
+ public void progress(IvyEvent event) {
+ disconnect();
+ event.getSource().removeIvyListener(this);
+ }
+ }, EndResolveEvent.NAME);
+ }
+
+ } catch (IOException ex) {
+ closeConnection();
+ throw new IOException("impossible to connect to " + getUsername() + "@" + getHost()
+ + " using " + getAuthentication() + ": " + ex.getMessage());
+ }
+ Message.verbose("connected to " + getHost());
+ }
+ }
+
+ private void updateLastCommandTime() {
+ _lastCommand = System.currentTimeMillis();
+ }
+
+ private void exec(String command) throws IOException {
+ Message.debug("launching '" + command + "'");
+ _process = Runtime.getRuntime().exec(command);
+ _in = new InputStreamReader(_process.getInputStream());
+ _err = new InputStreamReader(_process.getErrorStream());
+ _out = new PrintWriter(_process.getOutputStream());
+
+ _errorsReader = new IvyThread() {
+ public void run() {
+ initContext();
+ int c;
+ try {
+ while (_err != null && (c = _err.read()) != -1) {
+ _errors.append((char) c);
+ _errorsLastUpdateTime = System.currentTimeMillis();
+ }
+ } catch (IOException e) {
+ }
+ }
+ };
+ _errorsReader.start();
+ }
+
+ private void checkInterrupted() {
+ if (_ivy != null) {
+ _ivy.checkInterrupted();
+ }
+ }
+
+ /**
+ * Called whenever an api level method end
+ */
+ private void cleanup(Exception ex) {
+ if (ex.getMessage().equals("connection timeout to " + getHost())) {
+ closeConnection();
+ } else {
+ disconnect();
+ }
+ }
+
+ /**
+ * Called whenever an api level method end
+ */
+ private void cleanup() {
+ if (_reuseConnection == 0) {
+ disconnect();
+ }
+ }
+
+ public synchronized void disconnect() {
+ if (_in != null) {
+ Message.verbose("disconnecting from " + getHost() + "... ");
+ try {
+ sendCommand("exit", false, 300);
+ } catch (IOException e) {
+ } finally {
+ closeConnection();
+ Message.verbose("disconnected of " + getHost());
+ }
+ }
+ }
+
+ private synchronized void closeConnection() {
+ if (_connectionCleaner != null) {
+ _connectionCleaner.interrupt();
+ }
+ if (_errorsReader != null) {
+ _errorsReader.interrupt();
+ }
+ try {
+ _process.destroy();
+ } catch (Exception ex) {
+ }
+ try {
+ _in.close();
+ } catch (Exception e) {
+ }
+ try {
+ _err.close();
+ } catch (Exception e) {
+ }
+ try {
+ _out.close();
+ } catch (Exception e) {
+ }
+
+ _connectionCleaner = null;
+ _errorsReader = null;
+ _process = null;
+ _in = null;
+ _out = null;
+ _err = null;
+ Message.debug("connection to " + getHost() + " closed");
+ }
+
+ /**
+ * Parses a ls -l line and transforms it in a resource
+ *
+ * @param file
+ * @param responseLine
+ * @return
+ */
+ protected Resource lslToResource(String file, String responseLine) {
+ if (responseLine == null || responseLine.startsWith("ls")) {
+ return new BasicResource(file, false, 0, 0, false);
+ } else {
+ String[] parts = responseLine.split("\\s+");
+ if (parts.length != 9) {
+ Message.debug("unrecognized ls format: " + responseLine);
+ return new BasicResource(file, false, 0, 0, false);
+ } else {
+ try {
+ long contentLength = Long.parseLong(parts[3]);
+ String date = parts[4] + " " + parts[5] + " " + parts[6] + " " + parts[7];
+ return new BasicResource(file, true, contentLength, FORMAT.parse(date)
+ .getTime(), false);
+ } catch (Exception ex) {
+ Message
+ .warn("impossible to parse server response: " + responseLine + ": "
+ + ex);
+ return new BasicResource(file, false, 0, 0, false);
+ }
+ }
+ }
+ }
+
+ protected String getSingleCommand(String command) {
+ return "vsh -noprompt -auth " + _authentication + " " + _username + "@" + _host + " "
+ + command;
+ }
+
+ protected String getConnectionCommand() {
+ return "vsftp -noprompt -auth " + _authentication + " " + _username + "@" + _host;
+ }
+
+ protected Pattern getExpectedDownloadMessage(String source, File to) {
+ return Pattern.compile("Downloading " + to.getName() + " from [^\\s]+");
+ }
+
+ protected Pattern getExpectedRemoveMessage(String destination) {
+ return Pattern.compile("Removing [^\\s]+");
+ }
+
+ protected Pattern getExpectedUploadMessage(File source, String to) {
+ return Pattern.compile("Uploading " + source.getName() + " to [^\\s]+");
+ }
+
+ public String getAuthentication() {
+ return _authentication;
+ }
+
+ public void setAuthentication(String authentication) {
+ _authentication = authentication;
+ }
+
+ public String getHost() {
+ return _host;
+ }
+
+ public void setHost(String host) {
+ _host = host;
+ }
+
+ public String getUsername() {
+ return _username;
+ }
+
+ public void setUsername(String username) {
+ _username = username;
+ }
+
+ private static StringBuffer chomp(StringBuffer str) {
+ if (str == null || str.length() == 0) {
+ return str;
+ }
+ while ("\n".equals(str.substring(str.length() - 1))
+ || "\r".equals(str.substring(str.length() - 1))) {
+ str.setLength(str.length() - 1);
+ }
+ return str;
+ }
+
+ public String toString() {
+ return getName() + " " + getUsername() + "@" + getHost() + " (" + getAuthentication() + ")";
+ }
+
+ /**
+ * Sets the reuse connection time. The same connection will be reused if the time here does not
+ * last between two commands. O indicates that the connection should never be reused
+ *
+ * @param time
+ */
+ public void setReuseConnection(long time) {
+ _reuseConnection = time;
+ }
+
+ public long getReadTimeout() {
+ return _readTimeout;
+ }
+
+ public void setReadTimeout(long readTimeout) {
+ _readTimeout = readTimeout;
+ }
}
Modified: incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpResource.java
URL: http://svn.apache.org/viewvc/incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpResource.java?view=diff&rev=544459&r1=544458&r2=544459
==============================================================================
--- incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpResource.java (original)
+++ incubator/ivy/core/trunk/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpResource.java Tue Jun 5 05:02:27 2007
@@ -24,34 +24,33 @@
import org.apache.ivy.plugins.repository.Resource;
import org.apache.ivy.util.Message;
-
public class VsftpResource extends LazyResource {
- private VsftpRepository _repository;
-
- public VsftpResource(VsftpRepository repository, String file) {
- super(file);
- _repository = repository;
- }
+ private VsftpRepository _repository;
+
+ public VsftpResource(VsftpRepository repository, String file) {
+ super(file);
+ _repository = repository;
+ }
protected void init() {
- try {
- init(_repository.getInitResource(getName()));
- } catch (IOException e) {
- Message.verbose(e.toString());
- }
+ try {
+ init(_repository.getInitResource(getName()));
+ } catch (IOException e) {
+ Message.verbose(e.toString());
+ }
+ }
+
+ public InputStream openStream() throws IOException {
+ throw new UnsupportedOperationException(
+ "vsftp resource does not support openStream operation");
}
-
- public InputStream openStream() throws IOException {
- throw new UnsupportedOperationException("vsftp resource does not support openStream operation");
+ public Resource clone(String cloneName) {
+ try {
+ return _repository.getResource(cloneName);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
}
-
- public Resource clone(String cloneName) {
- try {
- return _repository.getResource(cloneName);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
}