KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > drftpd > master > command > plugins > TransferStatistics


1 /*
2  * This file is part of DrFTPD, Distributed FTP Daemon.
3  *
4  * DrFTPD is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * DrFTPD is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with DrFTPD; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18 package net.sf.drftpd.master.command.plugins;
19
20 import java.io.IOException JavaDoc;
21 import java.util.Collections JavaDoc;
22 import java.util.Date JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.StringTokenizer JavaDoc;
26
27 import net.sf.drftpd.Bytes;
28 import net.sf.drftpd.event.listeners.Trial;
29 import net.sf.drftpd.master.BaseFtpConnection;
30 import net.sf.drftpd.master.FtpReply;
31 import net.sf.drftpd.master.FtpRequest;
32 import net.sf.drftpd.master.command.CommandManager;
33 import net.sf.drftpd.master.command.CommandManagerFactory;
34 import net.sf.drftpd.master.config.FtpConfig;
35 import net.sf.drftpd.master.config.Permission;
36 import net.sf.drftpd.master.usermanager.NoSuchUserException;
37 import net.sf.drftpd.master.usermanager.User;
38 import net.sf.drftpd.master.usermanager.UserFileException;
39 import net.sf.drftpd.master.usermanager.UserManager;
40 import net.sf.drftpd.util.UserComparator;
41
42 import org.apache.log4j.Level;
43 import org.apache.log4j.Logger;
44 import org.drftpd.commands.CommandHandler;
45 import org.drftpd.commands.CommandHandlerFactory;
46 import org.drftpd.commands.UnhandledCommandException;
47 import org.tanesha.replacer.ReplacerEnvironment;
48
49 /**
50  * @version $Id: TransferStatistics.java,v 1.21.2.1 2004/06/19 23:37:26 mog Exp $
51  */

52 public class TransferStatistics implements CommandHandlerFactory, CommandHandler {
53
54     private static final Logger logger =
55         Logger.getLogger(TransferStatistics.class);
56
57     public static long getStats(String JavaDoc command, User user) {
58         // AL MONTH WK DAY
59
String JavaDoc period = command.substring(0, command.length() - 2).toUpperCase();
60         // UP DN
61
String JavaDoc updn = command.substring(command.length() - 2).toUpperCase();
62         if (updn.equals("UP")) {
63             if (period.equals("AL"))
64                 return user.getUploadedBytes();
65             if (period.equals("DAY"))
66                 return user.getUploadedBytesDay();
67             if (period.equals("WK"))
68                 return user.getUploadedBytesWeek();
69             if (period.equals("MONTH"))
70                 return user.getUploadedBytesMonth();
71         } else if (updn.equals("DN")) {
72             if (period.equals("AL"))
73                 return user.getDownloadedBytes();
74             if (period.equals("DAY"))
75                 return user.getDownloadedBytesDay();
76             if (period.equals("WK"))
77                 return user.getDownloadedBytesWeek();
78             if (period.equals("MONTH"))
79                 return user.getDownloadedBytesMonth();
80         }
81         throw new RuntimeException JavaDoc(
82             UnhandledCommandException.create(
83                 TransferStatistics.class,
84                 command));
85     }
86     public static long getFiles(String JavaDoc command, User user) {
87         // AL MONTH WK DAY
88
String JavaDoc period = command.substring(0, command.length() - 2);
89         // UP DN
90
String JavaDoc updn = command.substring(command.length() - 2);
91         if (updn.equals("UP")) {
92             if (period.equals("AL"))
93                 return user.getUploadedFiles();
94             if (period.equals("DAY"))
95                 return user.getUploadedFilesDay();
96             if (period.equals("WK"))
97                 return user.getUploadedFilesWeek();
98             if (period.equals("MONTH"))
99                 return user.getUploadedFilesMonth();
100         } else if (updn.equals("DN")) {
101             if (period.equals("AL"))
102                 return user.getDownloadedFiles();
103             if (period.equals("DAY"))
104                 return user.getDownloadedFilesDay();
105             if (period.equals("WK"))
106                 return user.getDownloadedFilesWeek();
107             if (period.equals("MONTH"))
108                 return user.getDownloadedFilesMonth();
109         }
110         throw new RuntimeException JavaDoc(
111             UnhandledCommandException.create(
112                 TransferStatistics.class,
113                 command));
114     }
115
116
117     public static int getStatsPlace(
118         String JavaDoc command,
119         User user, UserManager userman) {
120         // AL MONTH WK DAY
121

122         int place = 1;
123         long bytes = getStats(command, user);
124         List JavaDoc users;
125         try {
126             users = userman.getAllUsers();
127         } catch (UserFileException e) {
128             logger.error("IO error:", e);
129             return 0;
130         }
131         for (Iterator JavaDoc iter = users.iterator(); iter.hasNext();) {
132             User tempUser = (User) iter.next();
133             long tempBytes = getStats(command, tempUser);
134             if (tempBytes > bytes)
135                 place++;
136         }
137         return place;
138     }
139
140     /**
141      * USAGE: site stats [<user>]
142      * Display a user's upload/download statistics.
143      */

144     public FtpReply doSITE_STATS(BaseFtpConnection conn) {
145         FtpRequest request = conn.getRequest();
146
147         if (!request.hasArgument()) {
148             return FtpReply.RESPONSE_501_SYNTAX_ERROR;
149         }
150
151         User user;
152         if (!request.hasArgument()) {
153             user = conn.getUserNull();
154         } else {
155             try {
156                 user =
157                     conn.getConnectionManager().getUserManager().getUserByName(request.getArgument());
158             } catch (NoSuchUserException e) {
159                 return new FtpReply(200, "No such user: " + e.getMessage());
160             } catch (UserFileException e) {
161                 logger.log(Level.WARN, "", e);
162                 return new FtpReply(200, e.getMessage());
163             }
164         }
165
166         if (conn.getUserNull().isGroupAdmin()
167             && !conn.getUserNull().getGroupName().equals(user.getGroupName())) {
168             return FtpReply.RESPONSE_530_ACCESS_DENIED;
169         } else if (
170             !conn.getUserNull().isAdmin()
171                 && !user.equals(conn.getUserNull())) {
172             return FtpReply.RESPONSE_530_ACCESS_DENIED;
173         }
174         FtpReply response = (FtpReply) FtpReply.RESPONSE_200_COMMAND_OK.clone();
175         UserManager userman = conn.getConnectionManager().getUserManager();
176         response.addComment("created: " + new Date JavaDoc(user.getCreated()));
177         response.addComment("rank alup: " + getStatsPlace("ALUP", user, userman));
178         response.addComment("rank aldn: " + getStatsPlace("ALDN", user, userman));
179         response.addComment(
180             "rank monthup: " + getStatsPlace("MONTHUP", user, userman));
181         response.addComment(
182             "rank monthdn: " + getStatsPlace("MONTHDN", user, userman));
183         response.addComment("rank wkup: " + getStatsPlace("WKUP", user, userman));
184         response.addComment("rank wkdn: " + getStatsPlace("WKDN", user, userman));
185         response.addComment("races won: " + user.getRacesWon());
186         response.addComment("races lost: " + user.getRacesLost());
187         response.addComment("races helped: " + user.getRacesParticipated());
188         response.addComment("requests made: " + user.getRequests());
189         response.addComment("requests filled: " + user.getRequestsFilled());
190         response.addComment(
191             "nuked "
192                 + user.getTimesNuked()
193                 + " times for "
194                 + user.getNukedBytes()
195                 + " bytes");
196         response.addComment(" FILES BYTES");
197         response.addComment(
198             "ALUP "
199                 + user.getUploadedFiles()
200                 + " "
201                 + Bytes.formatBytes(user.getUploadedBytes()));
202         response.addComment(
203             "ALDN "
204                 + user.getDownloadedFiles()
205                 + " "
206                 + Bytes.formatBytes(user.getDownloadedBytes()));
207         response.addComment(
208             "MNUP "
209                 + user.getUploadedFilesMonth()
210                 + " "
211                 + Bytes.formatBytes(user.getUploadedBytesMonth()));
212         response.addComment(
213             "MNDN "
214                 + user.getDownloadedFilesMonth()
215                 + " "
216                 + Bytes.formatBytes(user.getDownloadedBytesMonth()));
217         response.addComment(
218             "WKUP "
219                 + user.getUploadedFilesWeek()
220                 + " "
221                 + Bytes.formatBytes(user.getUploadedBytesWeek()));
222         response.addComment(
223             "WKDN "
224                 + user.getDownloadedFilesWeek()
225                 + " "
226                 + Bytes.formatBytes(user.getDownloadedBytesWeek()));
227         return response;
228     }
229     public FtpReply execute(BaseFtpConnection conn)
230         throws UnhandledCommandException {
231         FtpRequest request = conn.getRequest();
232         if (request.getCommand().equals("SITE STATS")) {
233             return doSITE_STATS(conn);
234         }
235         List JavaDoc users;
236         try {
237             users = conn.getConnectionManager().getUserManager().getAllUsers();
238         } catch (UserFileException e) {
239             logger.warn("", e);
240             return new FtpReply(200, "IO error: " + e.getMessage());
241         }
242         int count = 10; // default # of users to list
243
request = conn.getRequest();
244         if (request.hasArgument()) {
245             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(request.getArgument());
246
247             try {
248                 count = Integer.parseInt(st.nextToken());
249             } catch (NumberFormatException JavaDoc ex) {
250                 st = new StringTokenizer JavaDoc(request.getArgument());
251             }
252
253             if (st.hasMoreTokens()) {
254                 Permission perm = new Permission(FtpConfig.makeUsers(st));
255                 for (Iterator JavaDoc iter = users.iterator(); iter.hasNext();) {
256                     User user = (User) iter.next();
257                     if (!perm.check(user))
258                         iter.remove();
259                 }
260             }
261         }
262         final String JavaDoc command = request.getCommand();
263         FtpReply response = new FtpReply(200);
264         String JavaDoc type = command.substring("SITE ".length()).toLowerCase();
265         Collections.sort(users, new UserComparator(type));
266
267         try {
268             Textoutput.addTextToResponse(response, type + "_header");
269         } catch (IOException JavaDoc ioe) {
270             logger.warn("Error reading " + type + "_header", ioe);
271         }
272
273         int i = 0;
274         for (Iterator JavaDoc iter = users.iterator(); iter.hasNext();) {
275             if (++i > count)
276                 break;
277             User user = (User) iter.next();
278             ReplacerEnvironment env = new ReplacerEnvironment();
279             env.add("pos", "" + i);
280
281             env.add(
282                 "upbytesday",
283                 Bytes.formatBytes(user.getUploadedBytesDay()));
284             env.add("upfilesday", "" + user.getUploadedFilesDay());
285             env.add("uprateday", getUpRate(user, Trial.PERIOD_DAILY));
286             env.add(
287                 "upbytesweek",
288                 Bytes.formatBytes(user.getUploadedBytesWeek()));
289             env.add("upfilesweek", "" + user.getUploadedFilesWeek());
290             env.add("uprateweek", getUpRate(user, Trial.PERIOD_WEEKLY));
291             env.add(
292                 "upbytesmonth",
293                 Bytes.formatBytes(user.getUploadedBytesMonth()));
294             env.add("upfilesmonth", "" + user.getUploadedFilesMonth());
295             env.add("upratemonth", getUpRate(user, Trial.PERIOD_MONTHLY));
296             env.add("upbytes", Bytes.formatBytes(user.getUploadedBytes()));
297             env.add("upfiles", "" + user.getUploadedFiles());
298             env.add("uprate", getUpRate(user, Trial.PERIOD_ALL));
299
300             env.add(
301                 "dnbytesday",
302                 Bytes.formatBytes(user.getDownloadedBytesDay()));
303             env.add("dnfilesday", "" + user.getDownloadedFilesDay());
304             env.add("dnrateday", getDownRate(user, Trial.PERIOD_DAILY));
305             env.add(
306                 "dnbytesweek",
307                 Bytes.formatBytes(user.getDownloadedBytesWeek()));
308             env.add("dnfilesweek", "" + user.getDownloadedFilesWeek());
309             env.add("dnrateweek", getDownRate(user, Trial.PERIOD_WEEKLY));
310             env.add(
311                 "dnbytesmonth",
312                 Bytes.formatBytes(user.getDownloadedBytesMonth()));
313             env.add("dnfilesmonth", "" + user.getDownloadedFilesMonth());
314             env.add("dnratemonth", getDownRate(user, Trial.PERIOD_MONTHLY));
315             env.add("dnbytes", Bytes.formatBytes(user.getDownloadedBytes()));
316             env.add("dnfiles", "" + user.getDownloadedFiles());
317             env.add("dnrate", getDownRate(user, Trial.PERIOD_ALL));
318
319             response.addComment(
320                 BaseFtpConnection.jprintf(
321                     TransferStatistics.class.getName(),
322                     "transferstatistics" + type,
323                     env,
324                     user));
325             // response.addComment(
326
// user.getUsername()
327
// + " "
328
// + Bytes.formatBytes(
329
// getStats(command.substring("SITE ".length()), user)));
330
}
331         try {
332             Textoutput.addTextToResponse(response, type + "_footer");
333         } catch (IOException JavaDoc ioe) {
334             logger.warn("Error reading " + type + "_footer", ioe);
335         }
336         return response;
337     }
338
339     public static String JavaDoc getUpRate(User user, int period) {
340         double s =
341             user.getUploadedMillisecondsForPeriod(period) / (double) 1000.0;
342         if (s <= 0) {
343             return "- k/s";
344         }
345
346         double rate = user.getUploadedBytesForPeriod(period) / s;
347         return Bytes.formatBytes((long) rate) + "/s";
348     }
349
350     public static String JavaDoc getDownRate(User user, int period) {
351         double s =
352             user.getDownloadedMillisecondsForPeriod(period) / (double) 1000.0;
353         if (s <= 0) {
354             return "- k/s";
355         }
356
357         double rate = user.getDownloadedBytesForPeriod(period) / s;
358         return Bytes.formatBytes((long) rate) + "/s";
359     }
360
361     public String JavaDoc[] getFeatReplies() {
362         return null;
363     }
364
365     public CommandHandler initialize(
366         BaseFtpConnection conn,
367         CommandManager initializer) {
368         return this;
369     }
370     public void load(CommandManagerFactory initializer) {
371     }
372
373     public void unload() {
374     }
375
376 }
377
378
Popular Tags