Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
ServerSubmitter.java
1 package ij;
2 import javax.swing.*;
3 import java.awt.*;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.net.*;
7 import ij.plugin.JpegWriter;
8 import java.io.*;
9 import java.util.*;
10 import ij.io.*;
11 import java.beans.*; //property change stuff
12 
13 public class ServerSubmitter implements ActionListener
14 {
15  public static final String CONFIRM_PREFIX = "OK";
16  public static final String ERROR_PREFIX = "ERROR";
17 
18  /* The ImageJ instance we were fired from */
19  private ImageJ ij;
20 
21  /* How many bytes we've uploaded, or -1 if we're finished and have received the server response */
22  private int progress = 0;
23 
24  private String tempFileName = null;
25 
30  {
31  this.ij = ij;
32 
33  }//end ServerSubmitter()
34 
35 
39  public void actionPerformed(ActionEvent ev)
40  {
41 
42  // get the file data to send
43  byte[] fileData = null;
44  String fileType = ij.getFileType();
45  if (fileType == ".gif") {
46  fileData = getGif(ij.getImagePlus());
47  } else if (fileType == ".jpg") {
48  fileData = getJpeg(ij.getImagePlus());
49  } else {
50  showError("Undefined file type " + fileType);
51  }
52  String fileName = ij.getFilename();
53  if (fileName.length() < 5) {
54  showError("You must give a filename before committing");
55  return;
56  }
57  final int length = fileData.length;
58 
59  // Figure out where to send it
60  URL submitURL = null;
61  try {
62  submitURL = new URL(ij.getParameter("SUBMIT_URL"));
63  } catch (MalformedURLException e) {
64  showError("Malformed URL: "+ij.getParameter("SUBMIT_URL"));
65  return;
66  } catch (Exception e) {
67  showError("Problem getting SUBMIT_URL parameter");
68  return;
69  }
70 
71  // Start showing progress
72  Thread progressThread = new Thread() {
73  public void run() {
74  ServerSubmitProgressDialog progressDialog = new ServerSubmitProgressDialog(length);
75  int p = getProgress();
76  while (p < length) {
77  progressDialog.setValue(p);
78  try { sleep(50); } catch (Exception e) {}
79  p = getProgress();
80  }
81  progressDialog.setTitle("Waiting for server response...");
82  progressDialog.goIndeterminate();
83  while (progress != -1) {
84  try { sleep(100); } catch (Exception e) {}
85  }
86  progressDialog.setVisible(false);
87  }
88  };
89  progressThread.start();
90 
91  // Start sending the data
92  ServerSubmitterThread submitterThread = new ServerSubmitterThread(this, fileData, fileName, submitURL);
93  submitterThread.start();
94 
95  }//end actionPerformed()
96 
97 
101  public String getParameter(String name)
102  {
103  return ij.getParameter(name);
104  }
105 
106 
110  public byte[] getGif(ImagePlus imp)
111  {
112  try {
113  FileInfo fi = imp.getFileInfo();
114  byte[] pixels = (byte[])imp.getProcessor().getPixels();
115  GifEncoder encoder = new GifEncoder(fi.width, fi.height, pixels, fi.reds, fi.greens, fi.blues);
116  ByteArrayOutputStream baos = new ByteArrayOutputStream();
117  OutputStream output = new BufferedOutputStream(baos);
118  encoder.write(output);
119  return baos.toByteArray();
120  }
121  catch (IOException e) {
122  showError(e.getMessage());
123  return null;
124  }
125 
126  }//end getGif()
127 
128 
132  public byte[] getJpeg(ImagePlus imp)
133  {
134  JpegWriter jpr = new JpegWriter();
135  return jpr.getJpegContents(imp);
136 
137  }//end getJpeg()
138 
139 
143  void showError(String msg)
144  {
145  JOptionPane.showMessageDialog(ij, msg, "Upload Error", JOptionPane.ERROR_MESSAGE);
146 
147  }//end showError()
148 
149 
153  synchronized void setProgress(int val)
154  {
155  progress = val;
156 
157  }//end setProgress()
158 
159 
163  synchronized int getProgress()
164  {
165  return progress;
166 
167  }//end setProgress()
168 
169 
173  synchronized void finish(String tempFileName)
174  {
175  progress = -1;
176  this.tempFileName = tempFileName;
177 
178  }//end finish()
179 
180  String getTempFileName()
181  {
182  while (getProgress() != -1) try { Thread.sleep(333); } catch (Exception e) {}
183  return this.tempFileName;
184  }
185 
186 
187 
188 }//end class
189 
190 
191 
192 class ServerSubmitterThread extends Thread
193 {
194  /* The ServerSubmitter that created us */
195  ServerSubmitter ms;
196 
197  /* The data to upload */
198  byte[] fileData;
199 
200  /* What to call the uploaded file */
201  String fileName;
202 
203  /* The string to use to mark the boundaries between parts of the HTTP message */
204  String boundary;
205 
206  /* The URL to submit to */
207  URL submitURL;
208 
209 
213  ServerSubmitterThread(ServerSubmitter ms, byte[] fileData, String fileName, URL submitURL)
214  {
215  this.ms = ms;
216  this.fileData = fileData;
217  this.fileName = fileName;
218  this.submitURL = submitURL;
219  this.boundary = getBoundary();
220 
221  }//end ServerSubmitterThread
222 
223 
227  private String getPostComponent(String name, String val)
228  {
229  return "\r\n--"+boundary+"\r\nContent-Disposition: form-data; name=\""+name+"\"\r\n\r\n"+val;
230 
231  }//end getPostComponent()
232 
233 
237  public void run()
238  {
239  // get the file component head
240  String fileFieldName = ms.getParameter("FILE_FIELD_NAME");
241  if (fileFieldName == null) fileFieldName = "file_0";
242  StringBuffer fileHeader = new StringBuffer();
243  fileHeader.append("--" + boundary + "\r\n");
244  fileHeader.append("Content-Disposition: form-data; name=\""+fileFieldName+"\"; fileName=\""+fileName+"\"\r\n");
245  fileHeader.append("Content-Type: application/octet-stream");
246  fileHeader.append("\r\n\r\n");
247 
248  // get the other POST components and the tail
249  StringBuffer tail = new StringBuffer();
250  int i = 0;
251  String fieldName = ms.getParameter("FIELD_NAME_"+i);
252  String fieldValue = ms.getParameter("FIELD_VALUE_"+i);
253  while (fieldName != null) {
254  //ms.showError("Field "+fieldName+" set to "+fieldValue);
255  tail.append(getPostComponent(fieldName, fieldValue));
256  i++;
257  fieldName = ms.getParameter("FIELD_NAME_"+i);
258  fieldValue = ms.getParameter("FIELD_VALUE_"+i);
259  }
260  tail.append("\r\n--");
261  tail.append(boundary);
262  tail.append("--\r\n");
263 
264  // get the request header
265  StringBuffer header = new StringBuffer();
266  header.append("POST "+submitURL.getPath()+"?"+submitURL.getQuery()+" HTTP/1.1\r\n");
267  header.append("Host: "+submitURL.getHost()+"\r\n");
268  header.append("Content-type: multipart/form-data; boundary="+boundary+"\r\n");
269  header.append("Content-length: "+((int)(fileData.length + fileHeader.length() + tail.length()))+"\r\n");
270  header.append("Connection: Keep-Alive\r\n");
271  header.append("\r\n");
272  //JOptionPane.showMessageDialog(ms.ij, "HEADER: "+header);
273 
274  Socket sock = null;
275  DataOutputStream dataout = null;
276  BufferedReader datain = null;
277 
278  try {
279 
280  sock = new Socket(submitURL.getHost(), (-1 == submitURL.getPort())?80:submitURL.getPort());
281  dataout = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
282  datain = new BufferedReader(new InputStreamReader(sock.getInputStream()));
283 
284  // send the header
285  dataout.writeBytes(header.toString());
286 
287  // send the file
288  dataout.writeBytes(fileHeader.toString());
289  byte[] byteBuff = new byte[1024];
290  int numBytes = 0;
291  int totalBytes = 0;
292  ByteArrayInputStream is = new ByteArrayInputStream(fileData);
293  while(-1 != (numBytes = is.read(byteBuff))) {
294  //JOptionPane.showMessageDialog(ij, "Wrote "+numBytes+" bytes");
295  dataout.write(byteBuff, 0, numBytes);
296  totalBytes += numBytes;
297  ms.setProgress(totalBytes);
298  try { Thread.sleep(20); } catch (Exception e) {}
299  }
300 
301  // wind it up
302  dataout.writeBytes(tail.toString());
303  dataout.flush();
304 
305  } catch (Exception e) {
306  ms.showError("Error while writing to server: "+e.getMessage());
307  e.printStackTrace();
308  return;
309  }
310 
311  try {
312  // get the server's response
313  String line = datain.readLine();
314  String confirmLine = null;
315  URL redirectLocation;
316  String error = null;
317  //StringBuffer sb = new StringBuffer();
318  while ((line != null)) {
319  //sb.append(line + "\n");
320  if (line.indexOf("403 Forbidden") != -1) {
321  error = "Server returned 403 forbidden. You don't seem to have access to the system";
322  break;
323  }
324  if (line.indexOf("MySource Warning") != -1) {
325  error = "MySource Warning: \n" + getMysourceMessage(datain);
326  break;
327  }
328  if (line.indexOf("MySource Error") != -1) {
329  error = "MySource Error: \n" + getMysourceMessage(datain);
330  break;
331  }
332  if (line.trim().startsWith(ServerSubmitter.CONFIRM_PREFIX)) {
333  confirmLine = line.trim();
334  break;
335  }
336  if (line.trim().startsWith(ServerSubmitter.ERROR_PREFIX)) {
337  error = line;
338  confirmLine = "";
339  break;
340  }
341  line = datain.readLine();
342  }
343  //ms.showError(sb.toString());
344 
345  if (error != null) {
346  ms.showError(error);
347  ms.finish(null);
348  return;
349  }
350  if (confirmLine == null) {
351  ms.showError("No confirm line found");
352  ms.finish(null);
353  return;
354  }
355  ms.finish(confirmLine.substring(ms.CONFIRM_PREFIX.length()+1));
356  } catch (Exception e) {
357  ms.showError("Error while reading server response: "+e.getMessage());
358  e.printStackTrace();
359  ms.finish(null);
360  return;
361  }
362 
363  }//end run()
364 
365  private String getMysourceMessage(BufferedReader datain)
366  {
367  StringBuffer msg = new StringBuffer();
368  try {
369  String line = datain.readLine();
370  while (line.indexOf("File:</td>") == -1) {
371  line = datain.readLine();
372  }
373  line = datain.readLine(); // file line
374  line = line.substring(0, line.lastIndexOf("</td>")); // strip close td
375  line = line.substring(line.lastIndexOf(">")+1); // strip everything before the filename
376  msg.append("File: ");
377  msg.append(line);
378  msg.append(" ");
379 
380  while (line.indexOf("Line:</td>") == -1) {
381  line = datain.readLine();
382  }
383  line = datain.readLine(); // line line
384  line = line.substring(0, line.lastIndexOf("</td>")); // strip close td
385  line = line.substring(line.lastIndexOf(">")+1); // strip everything before the line
386  msg.append("Line: ");
387  msg.append(line);
388  msg.append("\n");
389 
390  while (line.indexOf("Message:</td>") == -1) {
391  line = datain.readLine();
392  }
393  line = datain.readLine(); // message line
394  line = line.substring(0, line.lastIndexOf("</td>")); // strip close td
395  line = line.substring(line.lastIndexOf(">")+1); // strip everything before the message
396  msg.append("Message: ");
397  msg.append(line.replaceAll("&quot;", "\""));
398  } catch (Exception e) {
399  msg.append("...Exception reading error response...");
400  }
401  return msg.toString();
402  }
403 
404 
405 
409  private String getBoundary()
410  {
411  char[] allChars = new String("1234567890abcdefghijklmnopqrstuvwxyz").toCharArray();
412  int len = allChars.length - 1;
413  return "-----------------------------"
414  + allChars[(int)(Math.random() * len)]
415  + allChars[(int)(Math.random() * len)]
416  + allChars[(int)(Math.random() * len)]
417  + allChars[(int)(Math.random() * len)]
418  + allChars[(int)(Math.random() * len)]
419  + allChars[(int)(Math.random() * len)]
420  + allChars[(int)(Math.random() * len)]
421  + allChars[(int)(Math.random() * len)]
422  + allChars[(int)(Math.random() * len)]
423  + allChars[(int)(Math.random() * len)]
424  + allChars[(int)(Math.random() * len)];
425 
426  }//end getBoundary()
427 
428 
429 }//end class
430 
431 
432 
433 class ServerSubmitProgressDialog extends JFrame
434 {
435  /* Progress bar to show */
436  JProgressBar progressBar;
437 
443  ServerSubmitProgressDialog(int max)
444  {
445  super();
446  progressBar = new JProgressBar(0, max);
447  progressBar.setStringPainted(true);
448  progressBar.setValue(0);
449  getContentPane().add(progressBar);
450  setSize(400, 80);
451  validate();
452  Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
453  setLocation((screen.width / 2) - 200, (screen.height / 2) - 40);
454  setVisible(true);
455  toFront();
456  repaint();
457 
458  }//end ServerSubmitProgressDialog()
459 
460 
464  void setValue(int val)
465  {
466  progressBar.setValue(val);
467  repaint();
468 
469  }//end setValue()
470 
471 
475  void goIndeterminate()
476  {
477  progressBar.setIndeterminate(true);
478  progressBar.setStringPainted(false);
479 
480  }//end goIndeterminate()
481 
482 
483 
484 }//end class