View Javadoc

1   package org.paneris.jammyjoes.upload;
2   
3   import java.text.SimpleDateFormat;
4   import java.util.Calendar;
5   import java.util.Date;
6   
7   import org.melati.LogicalDatabase;
8   //import org.melati.MelatiConfig;
9   import org.melati.poem.AccessToken;
10  import org.melati.poem.PoemTask;
11  import org.melati.util.DatabaseInitException;
12  import org.paneris.jammyjoes.model.JammyjoesDatabase;
13  
14  import com.cqs.ftp.FTP;
15  
16  /**
17   * The Warden is a Thread which waits for 24 hours before generating and
18   * uploading new data for ecentives
19   *
20   * This thread becomes an org.melati.PoemThread by doing all its work
21   * inside a database.inSession() call. This ensures that there is a
22   * org.melati.PoemTransaction (think of sql transactions) available which
23   * can be commited or rolled back at any point by calling
24   * org.melati.PoremThread.commit() or org.melati.PoremThread.rollback()
25   *
26   * @see org.melati.poem.PoemThread#commit()
27   * @see org.melati.poem.PoemThread#rollback()
28   * @see org.melati.poem.Database#inSession()
29   */
30  
31  public class Warden implements Runnable {
32  
33    private JammyjoesDatabase database;
34    private WardenLauncher launcher = null;
35    //private MelatiConfig melatiConfig;
36  
37    SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
38    private String uploadDir;
39  
40    private static String databaseName = "jammyjoes";
41    private static long pausetime = 1000 * 60 * 60; // 1 hour
42    private static int runHour = 19; // run at 7pm or thereabouts
43    private static String ftphost = "hedwig.google.com";
44    private static String ftpuser = "timj";
45    private static String ftppass = "camel55";
46    private String filename = "jammyjoes.txt";
47  
48    /**
49     * Constructor
50     * <p>
51     * Allows the WardenLauncher to pass on parameters
52     * objects.
53     */
54  
55    public Warden(WardenLauncher launcher) {
56      this.launcher = launcher;
57      /*
58      try {
59        melatiConfig = new MelatiConfig();
60      } catch (Exception e) {
61        e.printStackTrace(System.err);
62      }
63      */
64    }
65  
66    /**
67     * Thread run method. Creates a transaction in our database, in which
68     * the warden does the rounds, and has a rest.
69     */
70    public void run() {
71      if (database == null) {
72        try {
73          database = (JammyjoesDatabase) LogicalDatabase.getDatabase(databaseName);
74        } catch (DatabaseInitException e) {
75          e.printStackTrace();
76        }
77      }
78      final Thread myThread = Thread.currentThread();
79      // die when WardenLauncher is 'destroy'ed
80      // (and sets its warden to null)
81      while (launcher.warden == myThread) {
82        database.inSession(AccessToken.root, new PoemTask() {
83          public void run() {
84            uploadDir = database.getSettingTable().get("UploadDir") + "/../";
85            doUploading();
86          }
87        });
88        try {
89          // Take a coffee break
90          Thread.sleep(pausetime);
91        } catch (InterruptedException e) {
92        }
93      }
94    }
95  
96    /**
97     * Check the directory for new data. It tries to enter
98     * any it finds into the database. It reports any exceptions and error
99     * conditions to an error file.
100    * <p>
101    */
102 
103   void doUploading() {
104     try {
105       Calendar rightNow = Calendar.getInstance();
106       if (rightNow.get(Calendar.HOUR_OF_DAY) == runHour) {
107         // time to run
108         System.err.println(new Date() + " Generating files for JammyJoes");
109         generateFiles();
110         System.err.println(new Date() + " Generated files for JammyJoes");
111         ftpUpload();
112         System.err.println(new Date() + " Uploaded Product file to Froogle");
113       }
114     } catch (Exception e) {
115       e.printStackTrace(System.err);
116     }
117   }
118 
119   public void generateFiles() throws Exception {
120     Froogle froogle = new Froogle(database);
121     froogle.writeFile(uploadDir, filename);
122   }
123 
124   public void ftpUpload() {
125     FTP ftp = new FTP(ftphost, 21);
126     ftp.setLogFile(uploadDir + "/ftp.log");
127 
128     int i = 0;
129     boolean connected = false;
130     while (!connected && i < 20) {
131       try {
132         Thread.sleep(1000*30);
133       } catch (InterruptedException e) {
134         e.printStackTrace();
135       }
136       i++;
137       connected = connect(ftp);
138     }
139     if (connected) {
140 
141       ftp.setTransfer(FTP.TRANSFER_PASV);
142       ftp.setMode(FTP.MODE_AUTO);
143 
144       ftp.upload(uploadDir + "/" + filename, filename);
145       System.err.print(ftp.lastReply());
146       if (ftp.lastCode() != FTP.CODE_TRANSFER_OK) {
147         System.err.println("error while uploading.");
148         ftp.disconnect();
149         return;
150       }
151 
152       ftp.disconnect();
153       System.err.print(ftp.lastReply());
154       if (ftp.lastCode() != FTP.CODE_DISCONNECT_OK) {
155         System.err.println("disconnection failed.");
156         return;
157       }
158 
159       ftp.closeLogFile();
160       System.err.println("OK.");
161     }
162   }
163 
164   private boolean connect(FTP ftp) {
165     ftp.connect();
166     System.err.print(ftp.lastReply());
167     if (ftp.lastCode() != FTP.CODE_CONNECT_OK) {
168       System.err.println("Connection failed.");
169       return false;
170     }
171 
172     ftp.login(ftpuser, ftppass);
173     System.err.print(ftp.lastReply());
174     if (ftp.lastCode() != FTP.CODE_LOGGEDIN) {
175       System.err.println("incorrect login.");
176       ftp.disconnect();
177       return false;
178     }
179     return true;
180 
181   }
182 }