1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.vfs2.provider.ftp;
18
19 import java.io.IOException;
20 import java.util.Collection;
21 import java.util.concurrent.atomic.AtomicReference;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.apache.commons.vfs2.Capability;
26 import org.apache.commons.vfs2.FileObject;
27 import org.apache.commons.vfs2.FileSystemException;
28 import org.apache.commons.vfs2.FileSystemOptions;
29 import org.apache.commons.vfs2.VfsLog;
30 import org.apache.commons.vfs2.provider.AbstractFileName;
31 import org.apache.commons.vfs2.provider.AbstractFileSystem;
32 import org.apache.commons.vfs2.provider.GenericFileName;
33
34
35
36
37 public class FtpFileSystem extends AbstractFileSystem {
38
39 private static final Log LOG = LogFactory.getLog(FtpFileSystem.class);
40
41
42
43
44
45
46
47 private final AtomicReference<FtpClient> idleClient = new AtomicReference<>();
48
49
50
51
52
53
54
55 public FtpFileSystem(final GenericFileName rootName, final FtpClient ftpClient,
56 final FileSystemOptions fileSystemOptions) {
57 super(rootName, null, fileSystemOptions);
58
59
60
61 idleClient.set(ftpClient);
62 }
63
64
65
66
67 @Override
68 protected void addCapabilities(final Collection<Capability> caps) {
69 caps.addAll(FtpFileProvider.CAPABILITIES);
70 }
71
72
73
74
75
76
77 private void closeConnection(final FtpClient client) {
78 try {
79
80 if (client.isConnected()) {
81 client.disconnect();
82 }
83 } catch (final IOException e) {
84
85 VfsLog.warn(getLogger(), LOG, "vfs.provider.ftp/close-connection.error", e);
86 }
87 }
88
89
90
91
92 @Override
93 protected FileObject createFile(final AbstractFileName name) throws FileSystemException {
94 return new FtpFileObject(name, this, getRootName());
95 }
96
97
98
99
100
101
102
103
104 protected FTPClientWrapper createWrapper() throws FileSystemException {
105 return new FTPClientWrapper((GenericFileName) getRoot().getName(), getFileSystemOptions());
106 }
107
108 @Override
109 protected void doCloseCommunicationLink() {
110 final FtpClient idle = idleClient.getAndSet(null);
111
112 if (idle != null) {
113 closeConnection(idle);
114 }
115 }
116
117
118
119
120
121
122
123 public FtpClient getClient() throws FileSystemException {
124 FtpClient client = idleClient.getAndSet(null);
125
126 if (client == null || !client.isConnected()) {
127 client = createWrapper();
128 }
129
130 return client;
131 }
132
133
134
135
136
137
138 public void putClient(final FtpClient client) {
139
140 if (!idleClient.compareAndSet(null, client)) {
141
142 closeConnection(client);
143 }
144 }
145 }