1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package net.sf.hermesftp.cmd;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.io.OutputStreamWriter;
30 import java.io.PrintWriter;
31 import java.net.Socket;
32
33 import net.sf.hermesftp.common.FtpSessionContext;
34 import net.sf.hermesftp.exception.FtpCmdException;
35 import net.sf.hermesftp.utils.IOUtils;
36
37 /***
38 * Abstract precursor for commands that handle LIST or NLST.
39 *
40 * @author Lars Behnke
41 */
42 public abstract class AbstractFtpCmdList extends AbstractFtpCmd {
43
44
45
46 /***
47 * {@inheritDoc}
48 */
49 public void execute() throws FtpCmdException {
50 msgOut(MSG150);
51 String charset = getCtx().getCharset();
52 PrintWriter dataOut = null;
53 try {
54 Socket dataSocket = getCtx().getDataSocketProvider().provideSocket();
55 dataOut = new PrintWriter(new OutputStreamWriter(dataSocket.getOutputStream(), charset));
56
57 String args = getArguments();
58 String[] argParts = args.split(" ");
59
60
61 File dir;
62 if (argParts[0].trim().startsWith("-")) {
63 dir = new File(getAbsPath(""));
64 } else {
65 dir = new File(getPathArg());
66 }
67
68
69
70 if (!dir.exists()) {
71 msgOut(MSG550);
72 return;
73 }
74
75 if (dir.isDirectory()) {
76 File[] files = dir.listFiles();
77 dataOut.println("total " + files.length);
78
79 for (int i = 0; i < files.length; i++) {
80 doPrintFileInfo(dataOut, files[i], getCtx());
81 }
82 } else {
83 doPrintFileInfo(dataOut, dir, getCtx());
84 }
85
86 msgOut(MSG226);
87 } catch (IOException e) {
88 msgOut(MSG550);
89 } catch (Exception e) {
90 msgOut(MSG550);
91 } finally {
92 IOUtils.closeGracefully(dataOut);
93 getCtx().closeSockets();
94 }
95 }
96
97 /***
98 * Prints information about a single file or directory.
99 *
100 * @param out The output stream.
101 * @param file The file.
102 * @param ctx The FTP context.
103 * @throws IOException Error on data transfer.
104 */
105 protected abstract void doPrintFileInfo(PrintWriter out, File file, FtpSessionContext ctx)
106 throws IOException;
107 }