KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > protocol > ftp > sampler > FtpClient


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/ftp/org/apache/jmeter/protocol/ftp/sampler/FtpClient.java,v 1.8 2004/02/11 23:59:31 sebb Exp $
2
/*
3  * Copyright 2001-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jmeter.protocol.ftp.sampler;
20
21 import java.io.BufferedInputStream JavaDoc;
22 import java.io.BufferedReader JavaDoc;
23 import java.io.BufferedWriter JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.io.OutputStreamWriter JavaDoc;
28 import java.net.InetAddress JavaDoc;
29 import java.net.ServerSocket JavaDoc;
30 import java.net.Socket JavaDoc;
31
32 import org.apache.jorphan.logging.LoggingManager;
33 import org.apache.log.Logger;
34
35 /**
36  * Simple FTP client (non-passive transfers don't work yet).
37  * Kind of a hack, lots of room for optimizations.
38  *
39  * @author mike
40  * Created August 31, 2001
41  * @version $Revision: 1.8 $ Last updated: $Date: 2004/02/11 23:59:31 $
42  */

43 public class FtpClient
44 {
45     transient private static Logger log = LoggingManager.getLoggerForClass();
46     //File f = new File("e:\\");
47
BufferedWriter JavaDoc out;
48     BufferedReader JavaDoc in;
49     Socket JavaDoc s;
50     boolean passive = false;
51     static int port = 21;
52     static int dataPort = 4096;
53
54     /**
55      * Constructor for the FtpClient object.
56      */

57     public FtpClient()
58     {
59     }
60
61     /**
62      * Set passive mode.
63      *
64      *@param flag the new Passive value
65      */

66     public void setPassive(boolean flag)
67     {
68         passive = flag;
69     }
70
71     /**
72      * Get a file from the server.
73      *
74      * @return the Response value
75      */

76     public String JavaDoc getResponse() throws IOException JavaDoc
77     {
78         StringBuffer JavaDoc response = new StringBuffer JavaDoc();
79         String JavaDoc line = in.readLine();
80         response.append(line);
81         log.info("FtpClient.getResponse(): #" + line + "#");
82         while (line.charAt(3) == '-')
83         {
84             line = in.readLine();
85             response.append("\n");
86             response.append(line);
87             log.info("FtpClient.getResponse(): #" + line + "#");
88         }
89         log.info("return response");
90         return response.toString();
91     }
92
93     /**
94      * Get a file from the server.
95      */

96     public String JavaDoc get(String JavaDoc file) throws Exception JavaDoc
97     {
98         send("SYST");
99         getResponse();
100         send("PWD");
101         getResponse();
102         send("TYPE I");
103         getResponse();
104         String JavaDoc data = "";
105         if (!passive)
106         {
107             dataPort++;
108             int upper = getUpper(dataPort);
109             int lower = getLower(dataPort);
110             String JavaDoc ip =
111                 InetAddress.getLocalHost().getHostAddress().replace('.', ',');
112             String JavaDoc port = ip + "," + upper + "," + lower;
113             log.info("port:" + port);
114             send("PORT " + port);
115             getResponse();
116             dataGrabber grab = new dataGrabber(ip, dataPort);
117             while (!grab.isPortCreated())
118             {
119             }
120             send("RETR " + file);
121             String JavaDoc response = in.readLine();
122             log.info(response);
123             log.info("" + dataPort);
124             data = "FTP client - File Not Found";
125             if (!response.startsWith("5"))
126             {
127                 while (!grab.isDone())
128                 {
129                 }
130                 data = grab.getData();
131             }
132         }
133         else
134         {
135             send("PASV");
136             String JavaDoc port = getResponse();
137             while (!port.startsWith("227"))
138             {
139                 port = getResponse();
140             }
141             int start = port.indexOf('(');
142             int end = port.indexOf(')');
143             port = port.substring(start + 1, end);
144             int a = port.indexOf(',');
145             int b = port.indexOf(',', a + 1);
146             int c = port.indexOf(',', b + 1);
147             int d = port.indexOf(',', c + 1);
148             int e = port.indexOf(',', d + 1);
149             String JavaDoc ip =
150                 port.substring(0, a)
151                     + "."
152                     + port.substring(a + 1, b)
153                     + "."
154                     + port.substring(b + 1, c)
155                     + "."
156                     + port.substring(c + 1, d);
157             int upper = Integer.parseInt(port.substring(d + 1, e));
158             int lower = Integer.parseInt(port.substring(e + 1));
159             int dataPort = getPort(upper, lower);
160             send("RETR " + file);
161             dataGrabber grab = new dataGrabber(ip, dataPort);
162             getResponse();
163             while (!grab.isDone())
164             {
165             }
166             data = grab.getData();
167         }
168         return data;
169     }
170
171     /**
172      * Connect to server.
173      */

174     public void connect(String JavaDoc host, String JavaDoc username, String JavaDoc password)
175         throws Exception JavaDoc
176     {
177         InetAddress JavaDoc addr = InetAddress.getByName(host);
178         s = new Socket JavaDoc(addr, port);
179         out = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(s.getOutputStream()));
180
181         InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(s.getInputStream());
182         in = new BufferedReader JavaDoc(isr);
183         send("USER " + username);
184         send("PASS " + password);
185     }
186
187     /**
188      * Disconnect from the server
189      */

190     public void disconnect()
191     {
192         try
193         {
194             send("QUIT");
195             getResponse();
196         }
197         catch (Exception JavaDoc e)
198         {
199             log.error("FTP client - ", e);
200         }
201         try
202         {
203             in.close();
204             out.close();
205             s.close();
206         }
207         catch (Exception JavaDoc e)
208         {
209             log.error("FTP client - ", e);
210         }
211     }
212
213     /**
214      * Send a command to the server.
215      */

216     public void send(String JavaDoc command) throws IOException JavaDoc
217     {
218         for (int i = 0; i < command.length(); i++)
219         {
220             out.write(command.charAt(i));
221         }
222         out.write('\r');
223         out.write('\n');
224         out.flush();
225     }
226
227     /**
228      * Gets the Port attribute of the FtpClient class.
229      * @return the Port value
230      */

231     public static int getPort(int upper, int lower)
232     {
233         return upper * 256 + lower;
234     }
235
236     /**
237      * Gets the Upper attribute of the FtpClient class.
238      * @return the Upper value
239      */

240     public static int getUpper(int port)
241     {
242         return port / 256;
243     }
244
245     /**
246      * Gets the Lower attribute of the FtpClient class.
247      *
248      * @return the Lower value
249      */

250     public static int getLower(int port)
251     {
252         return port % 256;
253     }
254
255     /**
256      * Grabs the data from the dataport.
257      *
258      * @author mike
259      * Created August 31, 2001
260      * @version $Revision: 1.8 $ Last updated: $Date: 2004/02/11 23:59:31 $
261      */

262     public class dataGrabber implements Runnable JavaDoc
263     {
264         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
265         Socket JavaDoc s;
266         boolean done = false;
267         boolean portCreated = false;
268         String JavaDoc host = "";
269         int port = 22;
270
271         /**
272          * Constructor for the dataGrabber object.
273          */

274         public dataGrabber(String JavaDoc host, int port) throws Exception JavaDoc
275         {
276             this.host = host;
277             this.port = port;
278             new Thread JavaDoc((Runnable JavaDoc) this).start();
279         }
280
281         /**
282          * Gets the Done attribute of the dataGrabber object.
283          *
284          * @return the Done value
285          */

286         public boolean isDone()
287         {
288             return done;
289         }
290
291         /**
292          * Gets the Data attribute of the dataGrabber object.
293          *
294          * @return the Data value
295          */

296         public String JavaDoc getData()
297         {
298             return buffer.toString();
299         }
300
301         /**
302          * Gets the PortCreated attribute of the dataGrabber object.
303          *
304          * @return the PortCreated value
305          */

306         public boolean isPortCreated()
307         {
308             return portCreated;
309         }
310
311         /**
312          * Main processing method for the dataGrabber object.
313          */

314         public void run()
315         {
316             try
317             {
318                 if (passive)
319                 {
320                     s = new Socket JavaDoc(host, port);
321                 }
322                 else
323                 {
324                     log.info("creating socket on " + port);
325                     ServerSocket JavaDoc server = new ServerSocket JavaDoc(port);
326                     log.info("accepting...");
327                     portCreated = true;
328                     s = server.accept();
329                     log.info("accepted");
330                 }
331             }
332             catch (Exception JavaDoc e)
333             {
334             }
335             try
336             {
337                 InputStream JavaDoc in = s.getInputStream();
338                 BufferedInputStream JavaDoc dataIn = new BufferedInputStream JavaDoc(in);
339                 int bufferSize = 4096;
340                 byte[] inputBuffer = new byte[bufferSize];
341                 int i = 0;
342                 while ((i = dataIn.read(inputBuffer, 0, bufferSize)) != -1)
343                 {
344                     buffer.append((char) i);
345                 }
346                 dataIn.close();
347                 s.close();
348             }
349             catch (Exception JavaDoc e)
350             {
351                 log.error("FTP client: dataGrabber", e);
352             }
353             done = true;
354         }
355     }
356 }
357
Popular Tags