KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > server > core > servlet > UploadServlet


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.admin.server.core.servlet;
25
26 import java.io.*;
27 import java.util.*;
28 import java.net.*;
29 import java.util.zip.*;
30 import java.util.logging.*;
31
32 import javax.servlet.ServletException JavaDoc;
33 import javax.servlet.http.HttpServlet JavaDoc;
34 import javax.servlet.http.HttpServletRequest JavaDoc;
35 import javax.servlet.http.HttpServletResponse JavaDoc;
36
37 import com.sun.enterprise.admin.server.core.AdminService;
38 import com.sun.enterprise.admin.common.constant.AdminConstants;
39
40 /**
41  *
42  * This servlet is used to upload files to application server tmp directory
43  */

44 public class UploadServlet extends HttpServlet JavaDoc {
45
46     private static final Logger sLogger = Logger.getLogger(AdminConstants.kLoggerName);
47
48     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
49         throws ServletException JavaDoc, IOException {
50
51         // check if fileName is valid
52
String JavaDoc str = request.getQueryString();
53         Properties p = new Properties();
54         try {
55             getQueryProperties(str, p);
56         } catch (Exception JavaDoc e) {
57             writeErrorResponse(response, e.getMessage());
58             return;
59         }
60         String JavaDoc fileName = p.getProperty("file");
61
62         if (fileName == null || fileName.trim().equals("")) {
63             writeErrorResponse(response, "no fileName found");
64             return;
65         }
66
67         // use tmp directory specified in domain.xml
68
File localDir = new File(AdminService.getAdminService().getTempDirPath());
69         localDir.mkdirs();
70
71         // check pre-existing file
72
File uploadFile = new File(localDir, fileName);
73         if (uploadFile.exists()) {
74             sLogger.log(Level.INFO, "mbean.temp_upload_file_exists", uploadFile.getCanonicalPath());
75             if (!uploadFile.delete()) {
76                 sLogger.log(Level.INFO, "mbean.delete_temp_file_failed", uploadFile.getCanonicalPath());
77                 writeErrorResponse(response, "cannot delete existing file");
78                 return;
79             }
80             sLogger.log(Level.FINE, "mbean.delete_temp_file_ok", uploadFile.getCanonicalPath());
81         }
82         
83         sLogger.log(Level.INFO, "mbean.begin_upload", uploadFile.getCanonicalPath());
84         
85             
86         // read data from inputstream
87
FileOutputStream fos = null;
88         InputStream is = null;
89         
90         try {
91             fos = new FileOutputStream(uploadFile);
92             is = request.getInputStream();
93             byte[] buffer = new byte[1024*64];
94             
95             for (int i = is.read(buffer); i > 0; i = is.read(buffer)) {
96                 fos.write(buffer, 0, i);
97             }
98         } catch (Exception JavaDoc e) {
99             sLogger.log(Level.WARNING, "mbean.upload_failed", uploadFile.getCanonicalPath());
100             writeErrorResponse(response, "uploading file failed");
101             return;
102         } finally {
103             if (fos != null) {
104                 fos.close();
105             }
106             if (is != null) {
107                 is.close();
108             }
109         }
110
111         // write remoteFilePath to HTTP response
112
writeResponse(response, uploadFile.getCanonicalPath());
113         return;
114
115     }
116
117     private void writeResponse(HttpServletResponse JavaDoc response, String JavaDoc msg)
118         throws IOException {
119         response.setContentType("text/html");
120         response.setCharacterEncoding("UTF-8");
121         response.setBufferSize(8192);
122         PrintWriter writer = response.getWriter();
123         writer.println("SUCCESS:" + msg);
124         writer.close();
125     }
126             
127     private void writeErrorResponse(HttpServletResponse JavaDoc response, String JavaDoc errorMsg)
128         throws IOException {
129         response.setContentType("text/html");
130         response.setBufferSize(8192);
131         PrintWriter writer = response.getWriter();
132         writer.println("FAIL:" + errorMsg);
133         writer.close();
134     }
135         
136
137     public void getQueryProperties(String JavaDoc q, Properties toAddTo) throws Exception JavaDoc {
138         if (q == null || q.length() == 0) {
139             return;
140         }
141         for (StringTokenizer iter = new StringTokenizer(q, "&");
142             iter.hasMoreElements();/*-*/) {
143             String JavaDoc pair = (String JavaDoc) iter.nextToken();
144             int split = pair.indexOf('=');
145             if (split <= 0) {
146                 throw new Exception JavaDoc ("Invalid pair [" + pair
147                     + "] in query string [" + q + "]");
148             } else {
149                 String JavaDoc key = pair.substring(0, split);
150                 String JavaDoc value = pair.substring(split + 1);
151                 try {
152                     key = URLDecoder.decode(key, "UTF-8");
153                     value = URLDecoder.decode(value, "UTF-8");
154                 } catch (UnsupportedEncodingException e) {
155                     throw new Exception JavaDoc("Invalid encoding in [" + pair
156                         + "] in query string [" + q + "]" + e.getMessage());
157                 }
158                 toAddTo.setProperty(key, value);
159             }
160         }
161     }
162
163 }
164
Popular Tags