KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > applet > upload > FileUploadApplet


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-components/org/opencms/applet/upload/FileUploadApplet.java,v $
3  * Date : $Date: 2006/10/17 13:33:11 $
4  * Version: $Revision: 1.20 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.applet.upload;
33
34 import java.awt.Color JavaDoc;
35 import java.awt.Font JavaDoc;
36 import java.awt.FontMetrics JavaDoc;
37 import java.awt.Graphics JavaDoc;
38 import java.awt.Image JavaDoc;
39 import java.io.File JavaDoc;
40 import java.io.FileInputStream JavaDoc;
41 import java.io.FileOutputStream JavaDoc;
42 import java.io.IOException JavaDoc;
43 import java.net.MalformedURLException JavaDoc;
44 import java.net.URL JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.StringTokenizer JavaDoc;
47 import java.util.zip.ZipEntry JavaDoc;
48 import java.util.zip.ZipOutputStream JavaDoc;
49
50 import javax.swing.JApplet JavaDoc;
51 import javax.swing.JFileChooser JavaDoc;
52 import javax.swing.JOptionPane JavaDoc;
53
54 import org.apache.commons.httpclient.Cookie;
55 import org.apache.commons.httpclient.HttpClient;
56 import org.apache.commons.httpclient.HttpState;
57 import org.apache.commons.httpclient.HttpStatus;
58 import org.apache.commons.httpclient.URI;
59 import org.apache.commons.httpclient.cookie.CookiePolicy;
60 import org.apache.commons.httpclient.methods.PostMethod;
61 import org.apache.commons.httpclient.methods.multipart.FilePart;
62 import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
63 import org.apache.commons.httpclient.methods.multipart.Part;
64 import org.apache.commons.httpclient.methods.multipart.StringPart;
65 import org.apache.commons.httpclient.params.HttpConnectionParams;
66 import org.apache.commons.httpclient.params.HttpMethodParams;
67
68 /**
69  * File Upload Applet, displays a file selector box to upload multiple resources into OpenCms.<p>
70  *
71  * @author Michael Emmerich
72  *
73  * @version $Revision: 1.20 $
74  *
75  * @since 6.0.0
76  */

77 public class FileUploadApplet extends JApplet JavaDoc implements Runnable JavaDoc {
78
79     /** The JSESSIONID cookie header name. */
80     public static final String JavaDoc C_JSESSIONID = "JSESSIONID";
81
82     /** Serial version UID required for safe serialization. */
83     private static final long serialVersionUID = -3710093915699772778L;
84
85     /** Applet thread. */
86     Thread JavaDoc m_runner;
87
88     /** The URL of the OpenCms instance. */
89     private String JavaDoc m_opencms = "";
90
91     /** The URL to send the uploaded files to. */
92     private String JavaDoc m_targetUrl = "";
93
94     /** The URL to return to after uploading the files. */
95     private String JavaDoc m_redirectUrl = "";
96
97     /** The Target Frame to return to after uploading the files. */
98     private String JavaDoc m_redirectTargetFrame = "";
99
100     /** The URL to return to after an error. */
101     private String JavaDoc m_errorUrl = "";
102
103     /** The name of the folder to upload to. */
104     private String JavaDoc m_uploadFolder = "";
105
106     /** Maximum file upload size. */
107     private long m_maxsize = -1;
108
109     /** Number of resources to upload. */
110     private int m_resources;
111
112     /** File extensions, used to find the correct icons for the selectbox. */
113     private String JavaDoc m_fileExtensions = "";
114
115     /** Color defintions. */
116     private HashMap JavaDoc m_colors = new HashMap JavaDoc();
117
118     /** Output string for action messages. */
119     private String JavaDoc m_action = "";
120
121     /** Output string for loggin messages. */
122     private String JavaDoc m_message = "";
123
124     /** Output mode selector. */
125     private int m_outputMode;
126
127     /** Counter for creating the progress bar. */
128     private int m_step;
129     
130     /** Definition of the images during upload. */
131     private Image JavaDoc m_source;
132     private Image JavaDoc m_target;
133     private Image JavaDoc m_floater;
134
135     /** Image position for the floater during upload. */
136     private int m_floaterPos = 50;
137     
138     /** Defintion of output strings.*/
139     private String JavaDoc m_actionOutputSelect = "Seleting files for upload....";
140     private String JavaDoc m_actionOutputCount = "Counting resources ....";
141     private String JavaDoc m_actionOutputCreate = "Creating Zip-File...";
142     private String JavaDoc m_actionOutputUpload = "Upload Zip-File";
143     private String JavaDoc m_actionOutputError = "Error";
144     private String JavaDoc m_messageNoPreview = "no preview available";
145     private String JavaDoc m_errorLine1 = "An error has occurred on the server:";
146     private String JavaDoc m_messageOutputUpload = "Please wait, uploading data...";
147     private String JavaDoc m_messageOutputAdding = "Adding ";
148     private String JavaDoc m_messageOutputErrorSize = "Zip file too big:";
149     private String JavaDoc m_messageOutputErrorZip = "Error creating Zip-File, see Java Console.";
150     private String JavaDoc m_certificateErrorTitle = "Error initializing the OpenCms Upload Applet";
151     private String JavaDoc m_certificateErrorMessage = "The required Applet certificate has not been accepted!";
152
153     /** Definition variables for graphics output. */
154     private Font JavaDoc m_font;
155     private FontMetrics JavaDoc m_metrics;
156     private Image JavaDoc m_offscreen;
157     private Graphics JavaDoc m_offgraphics;
158
159     /** The file selector. */
160     private JFileChooser JavaDoc m_fileSelector;
161
162     /** Indicates if the applet certificate has been accepted. */
163     private boolean m_certificateAccepted;
164
165     /**
166      * @see java.applet.Applet#destroy()
167      */

168     public void destroy() {
169
170         // NOOP
171
}
172
173     /**
174      * Displays an error message in case the applet could not be initialized.<p>
175      */

176     public void displayError() {
177
178         m_outputMode = 5;
179         m_action = m_certificateErrorTitle;
180         m_message = m_certificateErrorMessage;
181
182         JOptionPane.showMessageDialog(this, m_message, m_action, JOptionPane.ERROR_MESSAGE);
183
184         try {
185             // redirect back to the server
186
getAppletContext().showDocument(new URL JavaDoc(m_redirectUrl), m_redirectTargetFrame);
187         } catch (MalformedURLException JavaDoc e) {
188             // this should never happen
189
e.printStackTrace();
190         }
191
192         stop();
193     }
194
195     /**
196      * @see java.applet.Applet#init()
197      */

198     public void init() {
199
200         m_opencms = getParameter("opencms");
201         m_targetUrl = getParameter("target");
202         m_redirectUrl = getParameter("redirect");
203         m_redirectTargetFrame = getParameter("targetframe");
204         if ((m_redirectTargetFrame == null) || m_redirectTargetFrame.equals("")) {
205             m_redirectTargetFrame = "explorer_files";
206         }
207         m_errorUrl = getParameter("error");
208         m_uploadFolder = getParameter("filelist");
209         String JavaDoc tmpSize = getParameter("maxsize");
210         if ((tmpSize != null) && (tmpSize.length() > 0)) {
211             m_maxsize = Long.parseLong(tmpSize);
212         }
213         m_fileExtensions = getParameter("fileExtensions");
214         m_colors = extractColors(getParameter("colors"));
215
216         // setup the applet output
217
m_font = new java.awt.Font JavaDoc(null, Font.BOLD, 12);
218         m_metrics = getFontMetrics(m_font);
219         m_source = getImage(getCodeBase(), "org/opencms/applet/upload/applet_source.png");
220         m_target = getImage(getCodeBase(), "org/opencms/applet/upload/applet_target.png");
221         m_floater = getImage(getCodeBase(), "org/opencms/applet/upload/floater.gif");
222
223         // get the output massages in the correct language
224
if (getParameter("actionOutputSelect") != null) {
225             m_actionOutputSelect = getParameter("actionOutputSelect");
226         }
227         if (getParameter("actionOutputCount") != null) {
228             m_actionOutputCount = getParameter("actionOutputCount");
229         }
230         if (getParameter("actionOutputCreate") != null) {
231             m_actionOutputCreate = getParameter("actionOutputCreate");
232         }
233         if (getParameter("actionOutputUpload") != null) {
234             m_actionOutputUpload = getParameter("actionOutputUpload");
235         }
236         if (getParameter("actionOutputError") != null) {
237             m_actionOutputError = getParameter("actionOutputError");
238         }
239         if (getParameter("messageOutputUpload") != null) {
240             m_messageOutputUpload = getParameter("messageOutputUpload");
241         }
242         if (getParameter("messageOutputAdding") != null) {
243             m_messageOutputAdding = getParameter("messageOutputAdding");
244         }
245         if (getParameter("messageOutputErrorZip") != null) {
246             m_messageOutputErrorZip = getParameter("messageOutputErrorZip");
247         }
248         if (getParameter("messageOutputErrorSize") != null) {
249             m_messageOutputErrorSize = getParameter("messageOutputErrorSize");
250         }
251         if (getParameter("messageNoPreview") != null) {
252             m_messageNoPreview = getParameter("messageNoPreview");
253         }
254         if (getParameter("errorLine1") != null) {
255             m_errorLine1 = getParameter("errorLine1");
256         }
257         if (getParameter("certificateErrorTitle") != null) {
258             m_certificateErrorTitle = getParameter("certificateErrorTitle");
259         }
260         if (getParameter("certificateErrorMessage") != null) {
261             m_certificateErrorMessage = getParameter("certificateErrorMessage");
262         }
263
264         m_certificateAccepted = true;
265         try {
266             // set log factory to default log factory, otherwise commons logging detection will fail with an exception
267
System.setProperty(
268                 org.apache.commons.logging.LogFactory.FACTORY_PROPERTY,
269                 org.apache.commons.logging.LogFactory.FACTORY_DEFAULT);
270         } catch (SecurityException JavaDoc e) {
271             // this indicates the applet certificate has not been accepted
272
m_certificateAccepted = false;
273             e.printStackTrace();
274         }
275     }
276
277     /**
278      * Move the floating upload image to right, wrap around on right side.<p>
279      */

280     public void moveFloater() {
281
282         m_floaterPos += 10;
283         if ((m_floaterPos) > 430) {
284             m_floaterPos = 50;
285         }
286         repaint();
287     }
288
289     /**
290      * @see java.awt.Component#paint(Graphics)
291      */

292     public void paint(Graphics JavaDoc g) {
293
294         // create the box
295
m_offscreen = createImage(getSize().width, getSize().height);
296         m_offgraphics = m_offscreen.getGraphics();
297         m_offgraphics.setColor(getColor("bgColor"));
298         m_offgraphics.fillRect(0, 0, getSize().width, getSize().height);
299         m_offgraphics.setColor(getColor("outerBorderRightBottom"));
300         m_offgraphics.drawLine(0, getSize().height - 1, getSize().width - 1, getSize().height - 1);
301         m_offgraphics.drawLine(getSize().width - 1, 0, getSize().width - 1, getSize().height - 1);
302         m_offgraphics.setColor(getColor("outerBorderLeftTop"));
303         m_offgraphics.drawLine(0, 0, getSize().width - 1, 0);
304         m_offgraphics.drawLine(0, 0, 0, getSize().height - 1);
305         m_offgraphics.setColor(getColor("innerBorderRightBottom"));
306         m_offgraphics.drawLine(1, getSize().height - 2, getSize().width - 2, getSize().height - 2);
307         m_offgraphics.drawLine(getSize().width - 2, 1, getSize().width - 2, getSize().height - 2);
308         m_offgraphics.setColor(getColor("innerBorderLeftTop"));
309         m_offgraphics.drawLine(1, 1, getSize().width - 2, 1);
310         m_offgraphics.drawLine(1, 1, 1, getSize().height - 2);
311         m_offgraphics.setColor(getColor("bgHeadline"));
312         m_offgraphics.fillRect(4, 4, getSize().width - 5, 18);
313
314         m_offgraphics.setColor(getColor("innerBorderRightBottom"));
315         m_offgraphics.drawLine(10, getSize().height - 11, getSize().width - 11, getSize().height - 11);
316         m_offgraphics.drawLine(getSize().width - 11, 25, getSize().width - 11, getSize().height - 11);
317         m_offgraphics.setColor(getColor("innerBorderLeftTop"));
318         m_offgraphics.drawLine(10, 25, getSize().width - 11, 25);
319         m_offgraphics.drawLine(10, 25, 10, getSize().height - 11);
320
321         // draw title
322
int cx = 10;
323         int cy = 17;
324         m_offgraphics.setFont(m_font);
325         m_offgraphics.setColor(getColor("colorHeadline"));
326         m_offgraphics.drawString(m_action, cx, cy);
327
328         m_offgraphics.setColor(getColor("colorText"));
329         // draw process message
330
if (m_outputMode >= 3) {
331             cx = Math.max((getSize().width - m_metrics.stringWidth(m_message)) / 2, 0);
332         } else {
333             cx = 25;
334         }
335         cy = 41;
336         m_offgraphics.drawString(m_message, cx, cy);
337
338         // draw process bar during zip creation
339
if (m_outputMode == 2) {
340             float bar = new Float JavaDoc(m_step).floatValue() / new Float JavaDoc(m_resources).floatValue();
341             String JavaDoc barText = "(" + m_step + " / " + m_resources + ")";
342             m_offgraphics.drawRect(25, 50, 450, 20);
343             m_offgraphics.setColor(Color.white);
344             m_offgraphics.fillRect(26, 51, 449, 19);
345             m_offgraphics.setColor(getColor("progessBar"));
346             m_offgraphics.fillRect(26, 51, new Float JavaDoc(bar * 449).intValue(), 19);
347             int progressWith = m_metrics.stringWidth(barText);
348             cx = Math.max((getSize().width - progressWith) / 2, 0);
349             cy = 64;
350             m_offgraphics.setColor(Color.black);
351             m_offgraphics.drawString(barText, cx, cy);
352         }
353
354         // show floater during upload
355
if (m_outputMode == 3) {
356             m_offgraphics.drawImage(m_floater, m_floaterPos, 57, this);
357             m_offgraphics.drawImage(m_source, 30, 47, this);
358             m_offgraphics.drawImage(m_target, 440, 47, this);
359         }
360
361         // copy the offcreen graphics to the applet
362
g.drawImage(m_offscreen, 0, 0, null);
363     }
364
365     /**
366      * @see java.lang.Runnable#run()
367      */

368     public void run() {
369
370         try {
371             boolean ok = true;
372             while (ok) {
373                 ok = true;
374
375                 m_message = "";
376                 m_resources = 0;
377                 m_step = 0;
378                 // create a new file chooser
379

380                 if (m_fileSelector == null) {
381                     m_fileSelector = new JFileChooser JavaDoc();
382                 }
383
384                 // file selector can read files and folders
385
m_fileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
386
387                 m_fileSelector.setDialogTitle(m_actionOutputSelect);
388
389                 // add two custom file filters (office and images) and the default filters
390
m_fileSelector.addChoosableFileFilter(new ImageFilter());
391                 m_fileSelector.addChoosableFileFilter(new OfficeFilter());
392                 m_fileSelector.setAcceptAllFileFilterUsed(true);
393                 // enable multi-selection of files
394
m_fileSelector.setMultiSelectionEnabled(true);
395                 // add custom icons for file types.
396
m_fileSelector.setFileView(new ImageFileView(m_opencms, m_fileExtensions));
397                 // add the image preview pane.
398
m_fileSelector.setAccessory(new ImagePreview(m_fileSelector, m_messageNoPreview));
399
400                 m_action = m_actionOutputSelect;
401                 repaint();
402
403                 // show the file selector dialog
404
int returnVal = m_fileSelector.showDialog(this, "OK");
405
406                 // process the results.
407
if (returnVal == JFileChooser.APPROVE_OPTION) {
408                     // count all resources
409
m_outputMode = 1;
410                     m_action = m_actionOutputCount;
411                     repaint();
412                     m_resources = countResources(m_fileSelector.getSelectedFiles());
413                     // create the zipfile
414
m_outputMode = 2;
415                     File JavaDoc targetFile = createZipFile(m_fileSelector.getSelectedFiles());
416                     // check the size of the zip files
417
if ((targetFile == null) || ((m_maxsize > 0) && (targetFile.length() > m_maxsize))) {
418                         // show some details in the applet itself
419
m_outputMode = 4;
420                         if (targetFile == null) {
421                             m_message = m_messageOutputErrorZip;
422                         } else {
423                             m_message = m_messageOutputErrorSize + " " + targetFile.length() + " > " + m_maxsize;
424                         }
425                         m_action = m_actionOutputError;
426                         repaint();
427                         // show an error-alertbog
428
JOptionPane.showMessageDialog(this, m_message, m_action, JOptionPane.ERROR_MESSAGE);
429                     } else {
430                         m_outputMode = 3;
431                         m_message = m_messageOutputUpload + " (" + targetFile.length() / 1024 + " kb)";
432                         repaint();
433                         // upload the zipfile
434
FileUploadThread uploadThreat = new FileUploadThread();
435
436                         uploadThreat.init(this);
437                         uploadThreat.start();
438
439                         uploadZipFile(targetFile);
440                         ok = false;
441                     }
442
443                 } else {
444                     //the cancel button was used, so go back to the workplace
445
ok = false;
446                     getAppletContext().showDocument(new URL JavaDoc(m_redirectUrl), m_redirectTargetFrame);
447                 }
448             }
449         } catch (RuntimeException JavaDoc e) {
450             e.printStackTrace();
451         } catch (Exception JavaDoc e) {
452             e.printStackTrace();
453         }
454     }
455
456     /**
457      * @see java.applet.Applet#start()
458      */

459     public void start() {
460
461         if (m_certificateAccepted) {
462             // certificate was accepted, start upload thread
463
m_runner = new Thread JavaDoc(this);
464             m_runner.start();
465         } else {
466             // certificate was not accepted, show error message
467
displayError();
468         }
469     }
470
471     /**
472      * @see java.applet.Applet#stop()
473      */

474     public void stop() {
475
476         m_runner = null;
477     }
478
479     /**
480      * @see java.awt.Component#update(java.awt.Graphics)
481      */

482     public void update(Graphics JavaDoc g) {
483
484         paint(g);
485     }
486
487     /**
488      * Adds a single file to the zip output.<p>
489      *
490      * @param zipStream the zip output stream
491      * @param file the file to add to the stream
492      * @param filename the name of the file to add
493      * @throws Exception if something goes wrong
494      */

495     private void addFileToZip(ZipOutputStream JavaDoc zipStream, File JavaDoc file, String JavaDoc filename) throws Exception JavaDoc {
496
497         // add to zipfile
498
String JavaDoc name = filename;
499         if (name.length() > 40) {
500             name = "..." + name.substring(name.length() - 40, name.length());
501         }
502         m_message = m_messageOutputAdding + " " + name + "..";
503         m_step++;
504         repaint();
505         ZipEntry JavaDoc entry = new ZipEntry JavaDoc(filename);
506         zipStream.putNextEntry(entry);
507         zipStream.write(getFileBytes(file));
508         zipStream.closeEntry();
509     }
510
511     /**
512      * Adds a folder and all subresources to the zip output.<p>
513      *
514      * @param zipStream the zip output stream
515      * @param file the file to add to the stream
516      * @param prefix the foldername prefix
517      * @throws Exception if something goes wrong
518      */

519     private void addFolderToZip(ZipOutputStream JavaDoc zipStream, File JavaDoc file, String JavaDoc prefix) throws Exception JavaDoc {
520
521         String JavaDoc foldername = file.getName();
522
523         prefix += "/" + foldername;
524         // get all subresources
525
File JavaDoc[] subresources = file.listFiles();
526         // loop through the results
527
for (int i = 0; i < subresources.length; i++) {
528             // add it its a file
529
if (subresources[i].isFile()) {
530
531                 // use the prefix for the filename, since it inside the folder
532
addFileToZip(zipStream, subresources[i], prefix + "/" + subresources[i].getName());
533             } else {
534                 // recurse into the subfolder
535
addFolderToZip(zipStream, subresources[i], prefix);
536             }
537         }
538     }
539
540     /**
541      * Counts all resources to add to the zip file.<p>
542      *
543      * @param files the files to be packed into the zipfile
544      * @return number of resources
545      */

546     private int countResources(File JavaDoc[] files) {
547
548         int count = 0;
549         // look through all selected resources
550
for (int i = 0; i < files.length; i++) {
551             if (files[i].isFile()) {
552                 // its a file, count it
553
count++;
554             } else {
555                 // its a folder, count all resources in it and add the number
556
count += countSubresources(files[i]);
557             }
558         }
559         return count;
560     }
561
562     /**
563      * Counts all resources in a folder.<p>
564      *
565      * @param folder the folder to count
566      * @return number of resources
567      */

568     private int countSubresources(File JavaDoc folder) {
569
570         int count = 0;
571         if (folder.isFile()) {
572             // check if is really a folder
573
count = 1;
574         } else {
575             // recurest to count
576
count = countResources(folder.listFiles());
577         }
578         return count;
579     }
580
581     /**
582      * Creates a ZipFile from all files to upload.<p>
583      *
584      * @param files the files to be packed into the zipfile
585      * @return reference to the zipfile
586      */

587     private File JavaDoc createZipFile(File JavaDoc[] files) {
588
589         File JavaDoc targetFile = null;
590         m_action = m_actionOutputCreate;
591         try {
592             // create a new zipStream
593
String JavaDoc zipFileName = ".opencms_upload.zip";
594             String JavaDoc userHome = System.getProperty("user.home");
595             // create file in user home directory where write permissions should exist
596
if (userHome != null) {
597                 if (!userHome.endsWith(File.separator)) {
598                     userHome = userHome + File.separator;
599                 }
600                 zipFileName = userHome + zipFileName;
601             }
602             ZipOutputStream JavaDoc zipStream = new ZipOutputStream JavaDoc(new FileOutputStream JavaDoc(zipFileName));
603             // loop through all files
604
for (int i = 0; i < files.length; i++) {
605
606                 // if its a file, add it to the zipfile
607
if (files[i].isFile()) {
608                     addFileToZip(zipStream, files[i], files[i].getName());
609                 } else {
610                     addFolderToZip(zipStream, files[i], "");
611                 }
612                 repaint();
613                 // free mem
614
files[i] = null;
615             }
616             zipStream.close();
617             // get the zipfile
618
targetFile = new File JavaDoc(zipFileName);
619         } catch (Exception JavaDoc e) {
620             System.err.println("Error creating zipfile " + e);
621         }
622         return targetFile;
623
624     }
625
626     /**
627      * Extracts the colors from the parameter String.<p>
628      *
629      * @param colors list of color names and values
630      * @return HashMap with color names and values
631      */

632     private HashMap JavaDoc extractColors(String JavaDoc colors) {
633
634         HashMap JavaDoc colorStorage = new HashMap JavaDoc();
635
636         if (colors != null) {
637             StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(colors, ",");
638             // loop through the tokens
639
// all tokens have the format "extension=type"
640
while (tok.hasMoreElements()) {
641                 String JavaDoc token = tok.nextToken();
642                 // now extract the file extension and the type
643
String JavaDoc colorName = token.substring(0, token.indexOf("="));
644                 String JavaDoc colorValue = token.substring(token.indexOf("=") + 1);
645                 colorStorage.put(colorName, colorValue);
646             }
647         }
648         return colorStorage;
649     }
650
651     /**
652      * Gets a color for drawing the output.<p>
653      *
654      * @param colorName the name of the color
655      * @return color
656      */

657     private Color JavaDoc getColor(String JavaDoc colorName) {
658
659         Color JavaDoc col = Color.black;
660         try {
661             col = Color.decode((String JavaDoc)m_colors.get(colorName));
662         } catch (Exception JavaDoc e) {
663             System.err.println("Error reading " + colorName + ":" + e);
664         }
665         return col;
666     }
667
668     /**
669      * Returns a byte array containing the content of server FS file.<p>
670      *
671      * @param file the name of the file to read
672      * @return bytes[] the content of the file
673      * @throws Exception if something goes wrong
674      */

675     private byte[] getFileBytes(File JavaDoc file) throws Exception JavaDoc {
676
677         byte[] buffer = null;
678         FileInputStream JavaDoc fileStream = null;
679         int charsRead;
680         int size;
681         try {
682             fileStream = new FileInputStream JavaDoc(file);
683             charsRead = 0;
684             size = new Long JavaDoc(file.length()).intValue();
685             buffer = new byte[size];
686             while (charsRead < size) {
687                 charsRead += fileStream.read(buffer, charsRead, size - charsRead);
688             }
689             return buffer;
690         } catch (IOException JavaDoc e) {
691             throw e;
692         } finally {
693             try {
694                 if (fileStream != null) {
695                     fileStream.close();
696                 }
697             } catch (IOException JavaDoc e) {
698                 // ignore
699
}
700         }
701     }
702
703     /**
704      * Uploads the zipfile to the OpenCms.<p>
705      *
706      * @param uploadFile the zipfile to upload
707      */

708     private void uploadZipFile(File JavaDoc uploadFile) {
709
710         m_action = m_actionOutputUpload;
711         repaint();
712
713         PostMethod post = new PostMethod(m_targetUrl);
714
715         try {
716             Part[] parts = new Part[4];
717             parts[0] = new FilePart(uploadFile.getName(), uploadFile);
718             parts[1] = new StringPart("action", "submitform");
719             parts[2] = new StringPart("unzipfile", "true");
720             parts[3] = new StringPart("uploadfolder", m_uploadFolder);
721
722             HttpMethodParams methodParams = post.getParams();
723             methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
724             MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams);
725             post.setRequestEntity(request);
726
727             // add jsessionid query string
728
String JavaDoc sessionId = getParameter("sessionId");
729             String JavaDoc query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
730             post.setQueryString(query);
731             post.addRequestHeader(C_JSESSIONID, sessionId);
732
733             HttpClient client = new HttpClient();
734             HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
735             connectionParams.setConnectionTimeout(5000);
736
737             // add the session cookie
738
client.getState();
739             client.getHostConfiguration().getHost();
740
741             HttpState initialState = new HttpState();
742             URI uri = new URI(m_targetUrl, false);
743             Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
744             initialState.addCookie(sessionCookie);
745             client.setState(initialState);
746
747             // no execute the file upload
748
int status = client.executeMethod(post);
749
750             if (status == HttpStatus.SC_OK) {
751                 //return to the specified url and frame target
752
getAppletContext().showDocument(new URL JavaDoc(m_redirectUrl), m_redirectTargetFrame);
753             } else {
754                 // create the error text
755
String JavaDoc error = m_errorLine1 + "\n" + post.getStatusLine();
756                 //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE);
757
getAppletContext().showDocument(
758                     new URL JavaDoc(m_errorUrl + "?action=showerror&uploaderror=" + error),
759                     "explorer_files");
760             }
761         } catch (RuntimeException JavaDoc e) {
762             e.printStackTrace();
763         } catch (Exception JavaDoc e) {
764             e.printStackTrace();
765         } finally {
766             post.releaseConnection();
767             // finally delete the zipFile on the harddisc
768
uploadFile.delete();
769         }
770     }
771 }
Popular Tags