View Javadoc

1   /*
2    * Copyright (c) 2002 Peter Antman, Teknik i Media  <peter.antman@tim.se>
3    *
4    * $Id: FtpAgent.java,v 1.1.1.1 2004/05/19 12:33:41 pra Exp $
5    *
6    * This library is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public
8    * License as published by the Free Software Foundation; either
9    * version 2 of the License, or (at your option) any later version
10   * 
11   * This library is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   * Lesser General Public License for more details.
15   * 
16   * You should have received a copy of the GNU Lesser General Public
17   * License along with this library; if not, write to the Free Software
18   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   */
20  package org.backsource.alert.agent;
21  import java.util.Date;
22  import java.util.Calendar;
23  import java.util.Vector;
24  import java.io.IOException;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  
29  import org.backsource.alert.PropertyConstants;
30  import org.backsource.alert.AlertError;
31  
32  import org.apache.commons.net.ftp.FTPClient;
33  import org.apache.commons.net.ftp.FTPReply;
34  import org.apache.commons.net.ftp.FTPFile;
35  
36  /***
37   * FTP agent to check sanity of a dir on an ftp server.
38   *
39   * <p>The FtpAgent checks if it is possible to login to the given ftp server. 
40   * It may also optionally check if there are to many files at the server, 
41   * or if any of the files are to old. The following properties are possible to specify:</p>
42   * <ul>
43   <li>{@link org.backsource.alert.PropertyConstants#FTP_TIMEOUT},the socket timeout.</li>
44       <li>{@link org.backsource.alert.PropertyConstants#FTP_HOST}, the ftp host</li>
45       <li>{@link org.backsource.alert.PropertyConstants#FTP_USER}, the user to login as</li>
46       <li>{@link org.backsource.alert.PropertyConstants#FTP_PWD},the password</li>
47       <li>{@link org.backsource.alert.PropertyConstants#FTP_DIR},an optional directory to check. if not specfifyed the check will be done in the cwd given byte login. 
48       </li>
49       <li>{@link org.backsource.alert.PropertyConstants#FTP_FILE_AGE}, an optional age of the files int the checked directory, given in miliseconds.</li>
50       <li>{@link org.backsource.alert.PropertyConstants#FTP_NO_FILES}, an optial maximal number of files available in the checked directory.</li>
51      </ul>
52   * @author <a href="mailto:pra@tim.se">Peter Antman</a>
53   * @version $Revision: 1.1.1.1 $
54   */
55  
56  public class FtpAgent extends BaseCase{
57     static final Log log = LogFactory.getLog( FtpAgent.class);
58     final int DEFAULT_TIMEOUT =  3000;
59     int timeOut = DEFAULT_TIMEOUT;
60     String host;
61     String dir;
62     String user;
63     String pwd;
64     int noFiles = -1;
65     long age = -1;
66     public FtpAgent (String name){
67        super(name);
68     }
69  
70     protected void setUp() throws Exception{
71        super.setUp();
72        String t = prop.getProperty(PropertyConstants.FTP_TIMEOUT);
73        if ( t != null) {
74           timeOut = Integer.parseInt( t );
75        } // end of if ()
76        host= prop.getProperty(PropertyConstants.FTP_HOST);
77        user =prop.getProperty(PropertyConstants.FTP_USER);
78        pwd = prop.getProperty(PropertyConstants.FTP_PWD);
79        dir =  prop.getProperty(PropertyConstants.FTP_DIR);
80        
81        String l = prop.getProperty(PropertyConstants.FTP_FILE_AGE);
82        if (l != null ) {
83           age = Long.parseLong(l);
84        } // end of if ()
85        String n = prop.getProperty(PropertyConstants.FTP_NO_FILES);
86        if ( n != null) {
87           noFiles = Integer.parseInt( n );
88        } // end of if ()
89        
90     }
91     
92     /***
93      * Test log in to the given ftp host.
94      *
95      *<p>if no.files and/or fileage is set, these will also be checked.</p>
96      */
97     public void testFtpFiles() throws Exception {
98        FTPClient ftp = new FTPClient();
99        try {
100          ftp.setDefaultTimeout(timeOut);
101          
102 
103          int reply;
104          // Local version of dir, to be able to show it as / if dir is null
105          String cwd = null;
106          ftp.connect( host );
107          reply = ftp.getReplyCode();
108          
109          if(!FTPReply.isPositiveCompletion(reply)) {
110             ftp.disconnect();
111             log.error("FTP server refused connection.");
112             throw new AlertError("Could not login to ftp server " + host+": "+ftp.getReplyString());
113          }
114          if ( !ftp.login(user,pwd)) {
115             throw new AlertError("Could not login to ftp server " + host + " as user " + user); 
116          } // end of if ()
117          
118          log.debug("Logged in to ftp host " + host);
119          // OK,do work
120 
121          //if we have dir, go to that
122          if ( dir != null) {
123             log.debug("Changing working directory to dir " + dir);
124             if ( !ftp.changeWorkingDirectory(dir)) {
125                throw new AlertError("Could not change to dir: " + dir);
126             } 
127             cwd = dir;
128          } else {
129             cwd = "/";
130          } // end of else
131          
132 
133          // Get a file listing
134          //FTPFile[] files =  ftp.listFiles();
135          FTPFile[] files =  getFiles(ftp);
136          // We only want files, no dirs
137          if ( files != null) {
138             // Check that files is not bigger than noFiles
139             if ( noFiles > -1) {
140                if ( files.length > noFiles) {
141                   String m = "The number of files on ftp host "+ host+ " is larger than the specifyed maximum " + noFiles+": "+ files.length;
142                   log.error(m);
143                   throw new AlertError(m);
144                } 
145                
146             }
147             
148             // Check if any of the files is older than age
149             if ( age > -1) {
150                long now = new Date().getTime();
151 
152                for (int i =0; i<files.length;i++) {
153                   log.debug("Checking file " + files[i].getName() + " on host " + host + " in dir " + cwd);
154                   Calendar cal = files[i].getTimestamp();
155                   if ( cal != null ) {
156                      long mod = cal.getTime().getTime();
157                      if ( (now - mod) > age) {
158                         String m = "Channel seems to be dead. File " + files[i].getName() + " (" + files[i]+") on " + host + "in dir " + cwd +" is older than " + age;
159                         log.error(m);
160                         throw new AlertError(m);
161                      } 
162                   } 
163                   
164                }
165                
166             } 
167             
168             
169          } else {
170             log.info("No files found on host " + host + " in dir " + cwd);
171          } // end of else
172          
173          
174          
175          
176       } catch(Exception e) {
177          
178          if(ftp != null && ftp.isConnected()) {
179             try {
180                ftp.disconnect();
181             } catch(IOException f) {
182                // do nothing
183             }
184          }
185          log.error("Could not login to ftp server",e);
186          e.printStackTrace();
187          throw new AlertError("Could not login to ftp server " + host+": "+ftp.getReplyString());
188       }
189    }
190    
191    /***
192     * Return a listing with only files, no dirs.
193     */
194    protected FTPFile[] getFiles(FTPClient ftp) throws Exception{
195       FTPFile[] files =  ftp.listFiles();
196       FTPFile[] ret = null;
197       if ( files != null) {
198          Vector v = new Vector();
199          for ( int i =0;i<files.length;i++) {
200             if ( files[i].isFile()) {
201                v.add(files[i]);
202             } // end of if ()
203             
204          } // end of for ()
205          
206          ret = (FTPFile[])v.toArray( new FTPFile[ v.size()] );
207       } 
208       return ret;
209    }
210 
211 
212    public static void main(String[] args){
213       
214 
215 
216    }
217 } // FtpAgent