File: ExportWizard.java

package info (click to toggle)
cronometer 0.9.9%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 8,752 kB
  • sloc: java: 17,382; xml: 909; makefile: 19; sh: 18
file content (347 lines) | stat: -rw-r--r-- 12,677 bytes parent folder | download | duplicates (2)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package ca.spaz.cron;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

import java.util.Base64;
import ca.spaz.cron.datasource.Datasources;
import ca.spaz.cron.datasource.FoodProxy;
import ca.spaz.cron.metrics.Metric;
import ca.spaz.cron.user.User;
import ca.spaz.cron.user.UserManager;
import ca.spaz.gui.ErrorReporter;
 
public class ExportWizard extends JFrame {
   
   private static String  hostname = "cronometer.com";
   private static int     port     = 80;
   private static boolean testing  = false;           // if true, data is not committed

   private JTextField      username = new JTextField(24);
   private JPasswordField  password = new JPasswordField(); 
   private JPanel          loginPanel;

   private String          token;
   private JPanel          panel;
   private JTextPane       text;
   private JButton         importBtn; 
   private JCheckBox       importDiary = new JCheckBox("Import Diary", true);
   
   public ExportWizard() {
      super("Export to cronometer.com");
      setIconImage(CRONOMETER.getWindowIcon());
      setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
      
      text = new JTextPane();      
      
      panel = new JPanel(new BorderLayout(4,4));
      panel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
      panel.setPreferredSize(new Dimension(600,300));
      
      importBtn = new JButton("Upload Data");
      importBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            importBtn.setEnabled(false);
            Thread t = new Thread(new Runnable() {
               public void run() {
                  doLogin();                  
               }
            });
            t.start();
         }
      });
         
      panel.add(new JScrollPane(text), BorderLayout.CENTER); 
      panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
      
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(getLoginPanel(), BorderLayout.SOUTH);
      getContentPane().add(panel, BorderLayout.CENTER);

      println("This will upload all of your custom foods & recipes, and all of your diary entries " +
      		  "except for exercises and biometrics other than weight. It will not import your nutritional targets.\n");
      println("To upload your data to cronometer.com, enter your cronometer.com username and password.\n");
      println("If you use facebook, google, or yahoo to login to cronometer.com, you must first set a " +
      		  "username and pasword under the Profile tab of cronometer.com.\n");
      println("Time Zone:\n\t " + TimeZone.getDefault().getID()); 
      println("Data:\n\t" + UserManager.getUserDirectory(UserManager.getCurrentUser()));
      println("");
      
      pack();
   }
 
   public JPanel getLoginPanel() {
      if (loginPanel == null) {
         loginPanel = new JPanel();
         loginPanel.setBorder(new EmptyBorder(8, 8, 18, 8));
         loginPanel.setLayout(new GridLayout(4,3,4,4));

         loginPanel.add(importDiary); 
         loginPanel.add(Box.createGlue()); 
         loginPanel.add(Box.createGlue());

         loginPanel.add(new JLabel("Username:", JLabel.RIGHT));
         loginPanel.add(username);
         loginPanel.add(Box.createGlue());
         
         loginPanel.add(new JLabel("Password:", JLabel.RIGHT));
         loginPanel.add(password);
         loginPanel.add(Box.createGlue());
         
         loginPanel.add(Box.createGlue());
         loginPanel.add(importBtn);        
         loginPanel.add(Box.createGlue()); 
      }
      return loginPanel;
   }  
 
   private String encodeCredentials() {
      try {
         return Base64.getEncoder().encodeToString((username.getText() + '\n' + new String(password.getPassword())).getBytes("UTF-8"));
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
      return null;
   }
 
   private void doLogin() {
      try { 
         println("Logging in as '" + username.getText()+"'");
         URL url = new URL("http://"+hostname+"/migrate"); 
         URLConnection conn = url.openConnection();
         conn.setDoOutput(true);
         OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
         wr.write(URLEncoder.encode("login", "UTF-8") + "=" + encodeCredentials());
         wr.flush();
           
         BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document doc = db.parse(in);
         Element root = doc.getDocumentElement();        
         in.close();
        
         if (root.getAttribute("success").equals("false")) {
            println("Login Failed: " + getTextContent(root));
            JOptionPane.showMessageDialog(this, "Login Failed: " + getTextContent(root), "Login Failed", JOptionPane.ERROR_MESSAGE);
         } else {
            token = root.hasAttribute("token") ? root.getAttribute("token") : null;
            if (token != null) { 
               startImport();
            }
         }         
     } catch (Exception e) {
        ErrorReporter.showError(e, this);
        println(e.toString());
     } 
   }      
    
   public void startImport() {
      Thread t = new Thread(new Runnable() {
         public void run() {
            try {
               println("Loading data files...");
               String xmldata = getImportXML();
               println("Validating data..."); 
               System.out.println(xmldata);
               if (token != null) {
                  valdiate(xmldata);
                  if (xmldata != null) {
                     importData(xmldata, token);
                  } else {
                     println("Your data appears corrupted and cannot be imported.");
                     println("Email help@cronometer.com for assistance.");
                  }
               }
            } catch (Exception e) {
               e.printStackTrace();
               print(e.getMessage());
               ErrorReporter.showError(e, ExportWizard.this);
            }
         }   
      });     
      t.run();
   } 

   private void println(final String str) {
      print(str+"\n");
   }
   
   private void print(final String str) {
      System.out.print(str);
      if (text != null) {
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               try {
                  text.getDocument().insertString(text.getDocument().getLength(), str, null);
               } catch (BadLocationException e) {
                  e.printStackTrace();
               }                  
            }
         });
      }
   }
   
   public void importData(String xml, String token) throws IOException {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            importBtn.setEnabled(false);
         }
      });
      
      println("Connecting to "+hostname+"...");
      Socket sock = new Socket(hostname, port);

      // Send header
      String path = "http://"+hostname+"/migrate?token="+token;
      OutputStreamWriter wr = new OutputStreamWriter(new BufferedOutputStream(sock.getOutputStream()), "UTF-8");
      wr.write("POST " + path + " HTTP/1.0\r\n");
      wr.write("Content-Length: " +xml.length() + "\r\n");
      wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
      wr.write("\r\n");

      println("Submitting data...");

      // Send data
      wr.write(xml);
      wr.flush();

      // Response
      StringBuffer sb = new StringBuffer();
      try {
         BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
         String line;
         while ((line = rd.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
         }
      } catch (IOException ex) {
         print(ex.getMessage());
      }
      println("\nFinished writing data.");
      
      parseResponse(sb.toString());

      wr.close(); 
   }
 
   private void parseResponse(String string) {
      if (testing) {
         println(string);
      }
      string = string.replaceFirst("(?s).*\\n\\n", "");
      try {         
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document doc = db.parse(new ByteArrayInputStream(string.getBytes()));
         Element root = doc.getDocumentElement();        
         handleResponse(root);
      } catch (Exception ex) {
         print(ex.getMessage());
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               importBtn.setEnabled(true);
            }
         });
      }
   }

   private void handleResponse(Element root) {
      if (root.getAttribute("success").equals("false")) {
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               importBtn.setEnabled(true);
            }
         });            
         println("\nImport Failed: " + getTextContent(root));
         JOptionPane.showMessageDialog(this, "Import Failed: " + getTextContent(root), "Import Failed", JOptionPane.ERROR_MESSAGE);
      } else {
         JOptionPane.showMessageDialog(this, "Import Succeeded!");
         println("\nImport Succeeded!"); 
         dispose();
      }
   }
   
   public static String getTextContent(Node e) {
      StringBuffer sb = new StringBuffer();
      NodeList nl = e.getChildNodes();
      for (int n = 0; n<nl.getLength(); n++) {
         sb.append(nl.item(n).getTextContent());
      }
      return sb.toString();
   }
   

   public void valdiate(String xmldata) throws IOException {
      try {         
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         db.parse(new ByteArrayInputStream(xmldata.getBytes("UTF-8")));
      } catch (Exception e) {
         throw new IOException(e);
      } 
   }

   public String getImportXML() throws IOException {
      StringBuilder sb = new StringBuilder();

      User user = UserManager.getCurrentUser();
      println("Importing " + UserManager.getUserDirectory(user));

      // wrap it all in a root tag for importing
      sb.append(String.format("<import testing=\"%b\" timezone=\"%s\" version=\"%s\">", testing, TimeZone.getDefault().getID(), CRONOMETER.BUILD));
      
      List<FoodProxy> foods = Datasources.getUserFoods().getAllFoods();
      Collections.sort(foods, new Comparator<FoodProxy>() {
         public int compare(FoodProxy o1, FoodProxy o2) {
            return Integer.parseInt(o1.getSourceID()) - Integer.parseInt(o2.getSourceID());
         }
      });
      
      sb.append("<foods>");
      for (FoodProxy fp : foods) { 
         sb.append(fp.getFood().toXML().toString());
      }
      sb.append("</foods>");

      if (importDiary.isSelected()) { 
         if (user.getBiometricsHistory().getMetricsOfType("Weight").size() > 0) {
            String[] values = { "lbs", "kg", "Don't Import" };
            String weightUnit = (String)JOptionPane.showInputDialog(this, "In order to import your Weight measurements,\n we need to know what unit the data is in", "Weight Import", JOptionPane.QUESTION_MESSAGE, null, values, values[0]);
            if (!weightUnit.equals(values[2])) {
               Metric.WEIGHT_UNIT = weightUnit;
            }
         }
          
         sb.append(user.getFoodHistory().toXML());         
         sb.append(user.getBiometricsHistory().toXML());
         sb.append(user.getNotesHistory().toXML()); 
      }
      
      sb.append("</import>");
    
      return sb.toString();
   }
   
   public static void doExport() {
      ExportWizard ex = new ExportWizard();
      ex.setVisible(true);
   }

}